content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def pythonize_yang_name(name):
"""
Convert a name like "interface-name" to "InterfaceName" or
"interface" to "Interface
"""
if '-' in name:
py_name = ''
sub_components = name.split('-')
for s in sub_components:
py_name += s.capitalize()
return py_name
... | 1427d91ad9a929b7676f9d374a1237c3dca144c0 | 683,740 |
def pad_matrix(M):
"""
Pad the matrix's dimensions to the smallest
power of 2 greater than or equal to the number
of rows and columns in the matrix.
This eliminates edge cases for this example.
"""
m, n = len(M), len(M[0])
b = 1
while b < max(m, n):
b <<= 1
M += [[0] * n for _ in range(b - m)]... | 6e636822b6b3f8c0f341090b3acca2e512009551 | 683,741 |
import telnetlib
import socket
import logging
def is_port_open(port, address):
"""Determine if TCP port is accessible.
Connect to the MySQL port on the VIP.
:param port: Port number
:type port: str
:param address: IP address
:type port: str
:returns: True if port is reachable
:rtype:... | d5315129a1a36c6d9a1abff553ec220cc5b9c52b | 683,742 |
import requests
def get_tv_episode_detail(key, id, season, episode, language="en-US"):
"""
function get_tv_episode_detail
Get the TV episode details by id.
inputs: key - TMDB API key.
id - id of the movie
season - Season of the tv series (INT)
... | ce968c984a454be04d2869ccc61edaef6cc24f93 | 683,743 |
def get_attrs():
"""get attrs config"""
attrs = {
"pragma_checkcoincident": 0,
"pragma_reschedule": 1,
"pragma_modshift": 1,
"enable_bisect_optimize": 0,
}
return attrs | 39846b2cdb0b1136529a4a05bde95e7bf3b2a7be | 683,744 |
def evaluation_star(value):
"""Tag for displaying the rating in the form of stars.
Args:
value (int): Evaluation.
Returns:
dict: The return value as a dict for use in the template.
"""
return {'value': value} | b39fdc6c4dd2d36b0a1ed25a725571315b2feb53 | 683,745 |
def extract_subset_fea_col_names(df, fea_list, fea_sep='_'):
""" Extract features based feature prefix name. """
return [c for c in df.columns if (c.split(fea_sep)[0]) in fea_list] | 399f2223c2a1965bc187c090fde2fbcb5bd7431b | 683,746 |
def multi_bracket_validation(string):
"""Takes in a string argument and returns a boolean representing whether or not the brackets within the string are balanced.
"""
brackets = []
open_brackets = []
bracket_dict = {
")" : "(",
"]" : "[",
"}" : "{"
}
if string.count(... | 76e7047bd3370fc7c0703cf621724fc874859499 | 683,747 |
def ones_complement_addition(number1, number2):
"""
Build the one's complement addition as used in the calculation of IP-, TCP- and UDP-headers.
To see how the one's complement addition works, visit: https://youtu.be/EmUuFRMJbss
:param number1: A 16-bit number as Integer
:param number2: A 16-bit nu... | cb66dd3871282dd7c9802c61db7dc4c509597e0f | 683,748 |
import torch
def _kl_divergence_q_prior_normal(mu, logvar, per_dim=False):
"""
Returns KL-divergence between the variational posterior
$q_{\phi}(z|x)$ and the isotropic Gaussian prior $p(z)$.
This forms the 'regularization' part of the ELBO.
If the variational posterior is taken to be normal ... | 666e918c9ec54cc1f7d5002a811fa117083c00f8 | 683,749 |
def get_contrib_par_ids(poa_article, auth_id):
"""
In order to set xref tags for authors that link to funding award id
traverse the article data to match values
"""
par_ids = []
for index, award in enumerate(poa_article.funding_awards):
par_id = "par-" + str(index + 1)
for contri... | 1d8da5369d0a0b41fc5e0bc182c4276669b9e73c | 683,750 |
import os
def perk_upgrade_type():
"""Get perk upgrade type from environ varriable"""
return os.environ.get('PERK_UPGRADE_TYPE', None) | 66b132af39cbf743b9a869c6037870c6575bf36d | 683,751 |
import operator
def allsame_(iterable, eq=operator.eq):
""" returns True of all items in iterable equal each other """
iter_ = iter(iterable)
try:
first = next(iter_)
except StopIteration:
return True
return all(eq(first, item) for item in iter_) | afae284ae40d863489eb043764e4f09c0304c809 | 683,753 |
import json
def shiwu_str_to_list(body):
"""
把json的字符串,重新处理成数组,每个元素是(type, key, value)
:param body:
:return: [(type, key, value)]
"""
# 第一步:把body字符串转换成json
body_json = json.loads(body)
if type(body_json) == str:
body_json = json.loads(body_json)
# 第二步:处理数据
if not body_j... | b87e79e001400cca4e11d4db587244baa281061b | 683,754 |
import os
import subprocess
def check_bins(bins):
"""Check existance of ffmpeg and ffprobe binaries.
Parameters
----------
bins : tuple
A tuple `(ffmpeg_bin, ffprobe_bin)`` of the binary
names/paths. Either of the two can be ``None``, in which case
the corresponding binary is ... | 68addbc549a24c87145a944cffaee6ea36bda659 | 683,755 |
def get_list(cm_response, **data):
"""
Returns list of caller's public IPs.
@clmview_user
@cm_request_transparent{user.public_ip.get_list()}
"""
return cm_response | f44c09cbf1220d3fd4cbbf4297eeb68547b65b15 | 683,757 |
import base64
def decode(key, enc):
""" Vigenere cipher decoder """
if not len(key): return enc
dec = []
enc = base64.b64decode(enc).decode()
for i in range(len(enc)):
key_c = key[i % len(key)]
dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)
dec.append(dec_c)
return... | 491b561b089bd1a570644d22fd29bbbff086d734 | 683,758 |
def get_lmn_cursor_parameters():
"""Returns list with position 0 as the SQL query to find the gold medal counts of all the NOCs in the database and display them in descending order of gold medals."""
query = '''SELECT
national_olympic_committees.country,
COUNT(linking_table.medal_id) AS gold_medals
... | 2a84b5d2539adb895cf25e00e7eb8ad0423353fd | 683,762 |
def get_blue_green_from_app(app):
"""
Returns the blue_green object if exists and it's color field if exists
>>> get_blue_green_from_app({})
(None, None)
>>> get_blue_green_from_app({'blue_green': None})
(None, None)
>>> get_blue_green_from_app({'blue_green': {}})
(None, None)
>>... | c24c297f300fd4978aa1fd28245d835ef01ff387 | 683,763 |
def get_last_conv_layer_name(model_keras):
"""
Search for the last convolutional layer
Args:
model_keras: A keras model object
Returns:
Name of the layer (str)
"""
for layer in reversed(model_keras.layers):#loop in reverse order
# Select closest 4D layer to the end of th... | f62826d3adfb593ed52db2ced8f2c98fbfa9f947 | 683,764 |
def build_foreign_key_map(entry):
"""
Args:
Returns:
"""
cols_orig = entry["column_names"]
tables_orig = entry["table_names"]
# rebuild cols corresponding to idmap in Schema
cols = []
for col_orig in cols_orig:
if col_orig[0] >= 0:
t = tables_orig[col_orig[0]]
... | 698fa6475ae25ce6398c1d960439758ffa1188ae | 683,765 |
def flatten_args(args):
"""
Given a dictionary of arguments, produce a string suitable for inclusion
in a command line, such as "--name1 value1 --name2 value2"
"""
return " ".join(["%s %s" % (name, value)
for name, value in args.iteritems()]) | 0768cf7badc54cb01303f93f0a740864e5fc19a7 | 683,766 |
def _decimal_lshift_exact(n, e):
""" Given integers n and e, return n * 10**e if it's an integer, else None.
The computation is designed to avoid computing large powers of 10
unnecessarily.
>>> _decimal_lshift_exact(3, 4)
30000
>>> _decimal_lshift_exact(300, -999999999) # returns None
""... | 49fd101b693c4ef4bfd5612a5a34066f34e54219 | 683,768 |
import os
def is_existing_file(an_uri):
"""Returns whether the file exists and it is an actual file.
:param an_uri: the URI pointing to the file
:rtype: bool
"""
return os.path.exists(an_uri) and not os.path.isdir(an_uri) | ce8ebcd60af1b0ba648ef53a5cc190501a316b80 | 683,769 |
def calculate_polynomial_derivative_term(coefficient, variable, order):
"""Calculates the derivative of the nth order term of a polynomial.
Args:
coefficient (float): The coefficient of the nth order term in the
polynomial
variable (float): float to plug in for the variable in the p... | 46fc609334b41099fcb99784670bd93f54846353 | 683,770 |
def single_line(line, report_errors=True, joiner='+'):
"""Force a string to be a single line with no carriage returns, and report
a warning if there was more than one line."""
lines = line.strip().splitlines()
if report_errors and len(lines) > 1:
print('multiline result:', lines)
return joiner... | e150f0d9039f3f4bc0cb1213d5670bc7519b1bbf | 683,771 |
import unittest
def combined_suites(*test_suites):
"""Combines several suites into one"""
combined_suite = unittest.TestSuite(test_suites)
return combined_suite | 9016cc680dde2ef1d44280cb0bd469b78fec4db6 | 683,772 |
import os
import json
def load_model_config(args):
""" Query for the manually specified configuration"""
config= dict()
model_path = args['model_config_path']
print('Loading model configurations from {}'.format(model_path))
sim_gnn_path = os.path.join(model_path, args['sim_gnn']+ '_sim.json')
... | cc340a815f95062dd9d87249c246df2568777349 | 683,773 |
import hmac
import hashlib
def verify_payload(body, webhook_token, header_signature):
"""
:param body:
:param webhook_token:
:param header_signature:
:return:
"""
signing_key = webhook_token.encode("utf-8")
if not isinstance(body, bytes):
body = bytes(body)
hashed = hmac.... | 753f8ce537e8d4c8bbd8d9e5af599a1ea0e95893 | 683,774 |
def get_player_graph_types():
"""Update this with more chart types for individuals"""
options = [{'label': 'Rolling CF%', 'value': 'CF'},
{'label': 'Rolling GF%', 'value': 'GF'},
{'label': 'Rolling boxcars', 'value': 'Box'}]
return options | c24cb278291fa41a0f647078701891d1286ac54c | 683,776 |
import unicodedata
def strip_diacritics_2(input_string: str) -> str:
"""Return a copy of `input_string` without diacritics, such that
strip_diacritics('skříň') == 'skrin'
"""
trans_dict = {char: int(unicodedata.decomposition(char).split()[0],
base=16)
f... | 40cbb8522fdd20adb5e2e355613fdb01581ff80b | 683,777 |
def convert_to_quint(num, digits):
"""It converts a string number to the quintential number system value. Digits is a list of characters, So it is not recommended to be used for other projects."""
carry = ""
for i in num:
carry += digits.index(i).__str__()
return carry | 4522790e45016136fcf6565c383783fa136ea885 | 683,778 |
def liquidViscosity(T, lVP):
"""
liquidViscosity(T, lVP)
liquidViscosity (centipoise) = 10^(A + B/T + C*T + D*T^2)
Parameters
T, temperature in K
vPP, A=lVP[0], B=lVP[1], C=lVP[2], D=lVP[3]
A, B, C, D and E are regression coefficients
Returns
liquid viscosity... | 4bf76ae09b844f5ccfa0afa91df364beecd543b4 | 683,779 |
def valid_xml_char_ordinal(c):
"""Filters out certain bytes so that XML files contains valid
characters. XML standard defines a valid character as:
Char ::= #x9 | #xA | #xD | [#x20 - #xD7FF] |
[#xE000 - #xFFFD] | [#x10000 - #x10FFFF]
Args:
c: Character to be checked
Returns:
... | 32ae643ec970f00d4e65fd511de09bc8370ae9c6 | 683,780 |
def _contract(number):
"""Undo dilation."""
number = number & 0x09249249
number = (number | (number >> 2)) & 0x030C30C3
number = (number | (number >> 4)) & 0x0300F00F
number = (number | (number >> 8)) & 0x030000FF
number = (number | (number >> 16)) & 0x000003FF
return number
# Explanat... | a588d6b50ee5791aa2ecef688c4dd2fc9a4997af | 683,781 |
def moveRects(rects, pos):
"""This function moves the rects to a certain position."""
return [rect.move(pos[0],pos[1]) for rect in rects] | 84c5f6e4b630000331cdd5eadb05cbdc4e635906 | 683,782 |
def add_vp_vs(df):
"""Calculates the Vp and Vs for a las file
Args:
df (Pandas.DataFrame): input dataframe MUST CONTAIN `DTCO` and `DTSM`
Returns:
pandas.DataFrame: input dataframe with vp and vs calculated
"""
df['Vp'] = (1000000 / df['DTCO']) / 3.281
df['Vs'] = (1000000 / df['... | 1b237862b88e5c6f690f26ce60bee23445d3a57a | 683,783 |
def calculate_simpson_index(set1, set2):
"""Calculates the Simpson index of two sets"""
size_intersection = float(len(set1.intersection(set2)))
size_smaller_set = min(float(len(set1)), float(len(set2)))
return size_intersection / size_smaller_set | 0df02e34c283f604a87fe68b8e0b76cd87d09b36 | 683,784 |
def move_item_to_front(lst, item):
""" Move an item to the front of a list.
:param lst: the list
:type lst: list or tuple
:param item: the item, which must be in `lst`
:returns: the list, with the item moved to front
:rtype: tuple
"""
lst = list(lst)
lst.insert(0... | ceba6a893d6c83add79eb6cd341f855cd32f04a6 | 683,786 |
def cost_function_part2(num_steps: int) -> int:
"""Recursive cost function for the second part.
The first step costs 1, the second step costs 2, the third step costs 3,
and so on.
Args:
num_steps (int): Number of Steps
Returns:
(int) cost
Examples:
>>> cost_function_p... | 398aa6ec5665253ac77a892b114fe76003c37c52 | 683,787 |
def return_label(file_path):
"""
Extract label from filename
Inputs:
---------------
file_name: Source of raw wav signal str
Outputs:
---------------
y: target as string
"""
if "silence" in file_path.lower():
y = 'silence'
e... | e81f61edd2f1535b8061089103d5d06ab2d6af85 | 683,788 |
def get_pole_pair_number(self):
"""Returns the number of pole pairs of the machine
Parameters
----------
self : Machine
Machine object
Returns
-------
p: int
Pole pair number of the machine
"""
# Get list of laminations
lam_list = self.get_lam_list()
p = l... | b9020b73732aefd9682a0b39ef88c1d2e0ed2633 | 683,789 |
import ast
def ast_to_func(node, name):
"""Convert an `ast.FunctionDef` node into a callable object.
partof: #SPC-asts.ast2func
"""
ast.fix_missing_locations(node)
code = compile(node, __file__, "exec")
context = {}
exec(code, globals(), context)
return context[name] | b58abcf3bcaa912dde78986a36c5f2e15e082ba7 | 683,790 |
from typing import List
def get_sum_of_elements(lst: List) -> int:
"""Sum of list."""
return sum(lst) | e73fa9a407f655798979dd2a3101c5d7c35a1009 | 683,791 |
from typing import Optional
def get_location_id(data: dict) -> Optional[str]:
"""
Returns location_id from a data dictionary, or defaults to None
:param dict data: The event data
:return str|None: A string containing the location id, or None
"""
try:
return data["event"]["data"]["new"]... | 3250113d03ec1a8ef907ad3195bac738a10135ec | 683,792 |
import os
def __is_script__(fpath):
""" Return true if the path is a file
"""
return os.path.isfile(fpath) | 5719e9d69d726cabd4107761eca7fd734a5769c6 | 683,794 |
import re
def get_cell_barcode(record, cell_barcode_pattern):
"""Return the cell barcode in the record name.
Parameters
----------
record : screed record
screed record containing the cell barcode
cell_barcode_pattern: regex pattern
cell barcode pattern to detect in the record name... | 2b8d39cb2b49cde1f6de060dad7d780f88fd9062 | 683,795 |
def r_json(request):
"""Test fixture to allow testing of @render_json decorator
"""
return {'rendered_as': 'json'} | 7c822522169824f95201449f81a7ad135796b697 | 683,797 |
from typing import List
def spooler_pids() -> List[int]:
"""Returns a list of all spooler processes IDs."""
return [] | 9b2791d1c09d2db7eb2cd49322638e5d115cc625 | 683,798 |
import base64
def encode_file_to_base64(fpath_in, prefix):
""" encode_file_to_base64: gets base64 encoding of file
Args:
fpath_in (str): path to file to encode
prefix (str): file data for encoding (e.g. 'data:image/png;base64,')
Returns: base64 encoding of file
"""
... | 081cc794eeca30b3fb0b71a68238b07763823444 | 683,799 |
def add(a, b):
"""
>>> add(10, 20)
30
>>> add(20, 40)
60
>>> add(87, 9)
96
"""
return a + b | adfce69afa5fd290c67f44ecf093b2661199024c | 683,800 |
def loadCarbonSources(path):
"""docstring for loadCarbonSources"""
try:
file = open(path, 'r')
content = file.read().split('\n')
file.close()
return content
except:
pass | 8a9176380f557135de17ffdbd040c8cf0a0c1b19 | 683,801 |
def get_name():
"""MUST HAVE FUNCTION! Returns plugin name."""
return "C# Route" | 7bdbc6551d6a3573f0dc4631c3282de222db4e2a | 683,804 |
def le_bytes_to_int(as_bytes: bytes, signed: bool) -> int:
"""Converts a little endian byte array to an integer.
:param as_bytes: A little endian encoded byte array integer.
:param signed: Flag indicating whether integer is signed.
"""
return int.from_bytes(as_bytes, byteorder='little', signed=sig... | 6ca6f5a30a3576bd0d694d66943d0c8781997472 | 683,805 |
import string
def base26(x, _alphabet=string.ascii_uppercase):
"""Return positive ``int`` ``x`` as string in bijective base26 notation.
>>> [base26(i) for i in [0, 1, 2, 26, 27, 28, 702, 703, 704]]
['', 'A', 'B', 'Z', 'AA', 'AB', 'ZZ', 'AAA', 'AAB']
>>> base26(344799) # 19 * 26**3 + 16 * 26**2 + 1 ... | 44f7e68e97c0d4ac72701ce807a3b3192936ed2a | 683,806 |
def LoadWavSpeakerInfo(info_file):
"""return dict of wav: spk_list"""
info_file = open(info_file, "r", encoding="utf-8")
raw_info = list(map((lambda x: x.split("\t")), (info_file.read()).split("\n")))
wav_spk_info = {}
for mapping in raw_info[1:]:
if len(mapping) < 2:
continue
... | 852dc94e8952c8da604a2c2ab276881045847cbf | 683,807 |
def BoundingBox_collision(BB1, BB2):
""" return true if two N-D bounding boxes collide, False otherwise"""
for B1, B2 in zip(BB1,BB2):
if (B1[1] < B2[0]) or (B2[1] < B1[0]):
return False
return True | 71a15ea7f29963afc71d91855ff2b53a6ac6a979 | 683,808 |
def string2list(string, separator):
"""
Función que divide un string en una lista usando un separador.
:param string: String inicial
:type string: str
:param separator: Separador
:type separator: str
:return: Lista proveniente de la separación del string
:rtype: list
"""
return... | 2c56172613e93b9dfb2391b08ec9f3dadb62e9d9 | 683,809 |
def pgcd(a, b):
"""Renvoie le Plus Grand Diviseur Communs des entiers ``a`` et ``b``.
Arguments:
a (int) : un nombre entier
b (int) : un nombre entier
"""
if a < 0 or b < 0:
return pgcd(abs(a), abs(b))
if b == 0:
if a == 0:
raise ZeroDivisionError(
... | af036c18c6895afe38c2f55fc9051c1f68897134 | 683,812 |
from pathlib import Path
def get_package_root():
"""Get root path of `pmaf` package."""
return str(Path(__file__).parent.parent) | b2a8111e5aca69afb415d3b34e088b3d2aa6112e | 683,815 |
from typing import Dict
from typing import Tuple
from typing import Set
def prepare_senses_index_for_search(senses_dict: Dict[str, Dict[str, Tuple[tuple, Tuple[int, int]]]]) -> \
Dict[str, Set[str]]:
""" Build a search index for a fast selection of sentence candidates, which contain some sense from the Ru... | e5b53846b355450d9383d4359c83ec0c2e029bff | 683,816 |
from typing import Sequence
def to_sequence(obj):
"""Convert an object to sequence.
Parameters
----------
obj : `object`
Returns
-------
`collections.Sequence`
Examples
--------
>>> to_sequence(None)
()
>>> to_sequence(1)
(1,)
>>> to_sequence('str')
('str... | 9e9aaa5c0c0990b69b988309aa8fd068db015563 | 683,817 |
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_exchange package"""
reload_params = {"package": u"fn_exchange",
"incident_fields": [],
"action_fields": [u"exchange_delete_if_no_subfolders", u"exchange_destination_folder_path", u"exchange_email"... | d7ea207493709936cf336d6cb3ce371e9978b2e5 | 683,818 |
from typing import Counter
def build_vocab(datasets, min_count=10):
"""Build vocabulary from an iterable of datasets objects
Args:
datasets: a list of dataset objects
min_count: (int) if token appears less times, do not include it.
Returns:
a set of all the words in the dataset
... | d3cf3561e74acfd82ae8325530dfbb9767f7a03d | 683,819 |
def select(t, *columns):
""" Select columns from table
>>> t = Symbol('t', 'var * {x: int, y: int, z: int}')
>>> select(t, t.x, t.z)
t[['x', 'z']]
"""
return t[[c._name for c in columns]] | 90144b096a91aed341d0047627b0a9c3f158ce22 | 683,820 |
import os
def get_sgtk_module_path():
"""
Returns the path to ``sgtk`` module. This path can be used by another process to update its
``PYTHONPATH`` and use the same ``sgtk`` module as the process invoking this method.
For example, if the Toolkit core was installed at
``/home/user/.shotgun/bundle... | 6e2c698275892f17138950cbdf61e6cd7c7ec110 | 683,821 |
from typing import Dict
import pickle
def _from_checkpoint(
fname: str='checkpoint.pkl') -> Dict:
""" Load a checkpoint file """
with open(fname, 'rb') as f:
checkpoint = pickle.load(f)
return checkpoint | 66674dde389936e45c3d8935bcd8174c4844f5cc | 683,822 |
from typing import List
from typing import Dict
from typing import Any
def _transform_dto_list_to_list_of_dicts(dto_list) -> List[Dict[str, Any]]:
"""
Given a list of DTO objects, this function returns a list of dicts, that can be passed to jsonify function.
"""
return [vars(dto_obj) for dto_obj in dt... | 41d4d587aa78cf1e3879c22c2d95e28f9e4b0507 | 683,823 |
def phymem_buffers():
"""Return the amount of physical memory buffers used by the
kernel in bytes.
This reflects the "buffers" column of free command line utility.
"""
f = open('/proc/meminfo', 'r')
for line in f:
if line.startswith('Buffers:'):
f.close()
return i... | b2595b739719c23a261c76c907973b1cbd377ecd | 683,824 |
def join_rows(rows, joiner=' '):
"""
Given a series of rows, return them as a single row where the inner edge cells are merged. By default joins with a single space character, but you can specify new-line, empty string, or anything else with the 'joiner' kwarg.
"""
rows = list(rows)
fixed_row = rows... | caefb9f78c0213dad42a0a82cb381a76f619814a | 683,825 |
def _escape_regex(pattern: str) -> str:
"""Taken from Python 3.7 to avoid escaping '%'."""
_special_chars_map = {i: "\\" + chr(i) for i in b"()[]{}?*+-|^$\\.&~# \t\n\r\v\f"}
return pattern.translate(_special_chars_map) | 4e7693779a8808d668368156f1d6b5b1a86804a2 | 683,826 |
from typing import List
def individualList() -> List[int]:
"""Method creates list for storing individual info"""
return [0 for _ in range(7)] | 6bbde13ffe9de94c8bead4e4830d5d90ab07fa93 | 683,827 |
def get_w2v_emb(net, id2word):
"""get word2vec embeddings according to net parameters and dictionary that maps id to word.
"""
w2v_emb = dict()
parameters = [item for item in net.c_emb.get_parameters()]
emb_mat = parameters[0].asnumpy()
for wid, emb in enumerate(emb_mat):
word = id2word... | c04fd7bf549de8ae3054db859919cb08cb314d21 | 683,828 |
def parse_float(val):
"""parses string as float, ignores -- as 0"""
if val == '--':
return 0
return float(val) | 116bab60da24a492561a6893e280027543eb3764 | 683,829 |
import argparse
def setup_argparse():
"""Function to set up the argparser for the command line arguments
Supported arguments:
--dev: To turn on developper mode and store locations in memory instead of a database
Returns:
Returns arguments parser object that contains the parsed args
... | 5c7f541b8f033977cf135258f8c4e015513d46d4 | 683,830 |
def make_act_limit_data(act_tp, act_typ):
"""
限额
:param act_tp:
:param act_typ:
:return:
"""
if act_tp == "11":
if act_typ == "3":
act_limit = float(100000)
elif act_typ == "2":
act_limit = float(10000)
elif act_typ == "1":
act_limi... | 2bbe5773fdc7cff4cdf7eee4cbca4b6be2b33e61 | 683,831 |
def running_mean(l, N):
"""From a list of values (N), calculate the running mean with a
window of (l) items. How larger the value l is, the more smooth the graph.
"""
sum = 0
result = list(0 for x in l)
for i in range(0, N):
sum = sum + l[i]
result[i] = sum / (i + 1)
for i ... | 6ecd738d9b0dc6c72201149ad236858c462ecc8a | 683,832 |
def get_outbreaks(flowmat, incidence, R0=2.5, asymf=10, attenuate=1.0):
"""
Calculate the probabilities of outbreak for all regions
:param flowmat: Arriving passengers row -> column
:param incidence: fraction of infectious in the populations
:param R0: Basic reproduction number
:param asymf: ho... | 3d7b1ba3a61ebe574a4672fb7c1876dee4a7cc48 | 683,833 |
from typing import TextIO
def write_diversity_alpha(out_fp: str, datasets_phylo: dict, trees: dict,
dat: str, qza: str, metric: str, cur_sh: TextIO,
qiime_env: str) -> bool:
"""
Computes a user-specified alpha diversity metric for all samples in a feature ta... | b55b644ae74211f498d653f957ce7f903bcb8f39 | 683,834 |
def bin_to_hex(x):
"""Convert Binary to Hex."""
y = hex(int(x, 2))[2:]
if len(y) < 8:
y = (8 - len(y)) * "0" + y
return y | 045e879a6413666d06f8acbfd6b1f617d8178549 | 683,835 |
def _build_species_list_from_input(input_filename: str):
"""Parse an input.geos file and build a list of advected species."""
inputf = open(input_filename, 'r') # Open the input file.
tracers = [] # Make an empty list that will contain advected species.
adv_species = False # Line 1 doesn't conta... | 3e4a49714eb3396c61aa51360363e20c6e75f38f | 683,836 |
import re
def process_tweets(text):
"""Exclude mentions, urls, and html reference characters in a string using regular expression"""
text = re.sub("(\@|https:\/\/)\S+", "", text) # remove mentions and urls
text = re.sub(r"&[a-z]+;", "", text) # exclude html reference characters
return text | 934d78f691767bc12bdc40701a1953c0eba1d97d | 683,837 |
def f90bool(s):
"""Convert string repr of Fortran logical to Python logical."""
assert type(s) == str
try:
s_bool = s[1].lower() if s.startswith('.') else s[0].lower()
except IndexError:
raise ValueError('{0} is not a valid logical constant.'.format(s))
if s_bool == 't':
re... | d2e92906c355710762e472c42191834ba8806f5d | 683,838 |
import subprocess
def gzipped_result_file_same_as_reference(result, reference):
"""
Return True if a gzipped file result matches the gzipped reference file and False
otherwise. Do not compare a header of a gzipped file, which contains information
on when the file was compressed.
"""
cmd_args =... | 072e68b69c377827425ebb33d7141b5a2286e93b | 683,840 |
from functools import cmp_to_key
def argsort(mylist, comp=None):
"""Returns the indices that sort a list.
Parameters
----------
mylist : list of objects
List to sort.
comp : function, optional
A comparison function used
to compare two objects in the list.
Defaults ... | d73c592113058a5f7c28034fa840eb0c618ea26a | 683,841 |
from typing import Optional
import torch
def file2ckpt(path: str, device: Optional[str] = None) -> dict:
"""
Load the ckpt file into a dictionary to restart a past simulation. It is a thin wrapper around torch.load.
Args:
path: A string specifying the location of the ckpt file (required)
... | 220c6ff92a74e6f87d1c75b55bcf6142f668c3e1 | 683,842 |
def test_cooke(request):
"""
Return the result of the last staged test cookie.
returns cookie_state = bool
"""
if request.session.test_cookie_worked():
request.session.delete_test_cookie()
cookie_state = True
else:
cookie_state = False
return cookie_state | f76f47e5ad07ffb730e538cbc7a1bc8d84450021 | 683,843 |
from typing import Sequence
from typing import Sized
def are_none(sequences: Sequence[Sized]) -> bool:
"""
Returns True if all sequences are None.
"""
if not sequences:
return True
return all(s is None for s in sequences) | ed067bf08fef251fdf9835c144d72bd4746564c1 | 683,844 |
def getManifestApiVersion(manifest):
""" returns Api Version for for manifest"""
return manifest["Docker-Distribution-Api-Version"] | 621eebe6a46db5963d2594d5f7d273fd2953561c | 683,845 |
def concat(str_one, str_two):
"""
Returns the concatenation of 2 strings. A string
with null value is considered as an empty string.
"""
if not str_one:
str_one = ""
if not str_two:
str_two = ""
return str_one + str_two | 949cf41745f8800ce033a102ff78d525d7676696 | 683,846 |
def DecifrarUsuarios ():
"""
Lê e decifra os usuários criptografados no arquivo de usuários
:return dicionario:
"""
ArquivoUsuarios = open ("Arquivos/usuarios.txt", 'r')
codigo = '^.^'
dicionario = {}
while (codigo != ''):
codigo = ArquivoUsuarios.readline() #Caso não seja o fim ... | 3010c94664e5369f0447de0aeafd80f43324a9b6 | 683,847 |
from shutil import which
def is_tool(name):
"""Check whether `name` is on PATH and marked as executable."""
# from whichcraft import which
return which(name) is not None | baebb314d631973cbca94499358a667a842786fd | 683,848 |
import functools
def cached(func):
"""Decorator to cache the result of a function call."""
func.cache = {}
@functools.wraps(func)
def wrapper(*args, **kwargs):
if kwargs:
key = args, frozenset(kwargs.items())
else:
key = args
if key not in func.cache:
... | 132063628387f13b43969536f66b2093e63d6b45 | 683,849 |
import re
from datetime import datetime
def _get_iso_date(date_string: str) -> str:
""" convert date from the form 1/22/2021 13:28:27 to iso format """
regex = r'\d{1,2}/\d{1,2}/\d{4} \d{1,2}:\d{1,2}:\d{1,2}'
found_list = re.findall(regex, date_string)
if found_list:
date_value = datetime.strp... | fa9d6c733014ad4d738d63f2399085f08949c108 | 683,851 |
def relaxation_model_ttc(p, state, dt):
"""Alternative relaxation model for short/dangeorus spacings - applies control to ttc (not recommended).
Args:
p (list of floats): list of target ttc (time to collision), jam spacing, velocity sensitivity, gain
target ttc: If higher, we require larger... | 45bb48fbdc1a6dfe88b3dbcedcd4d78a48c2efd7 | 683,852 |
def remove_erroneous_blocks(blocks, delta_time=2.0, n_blocks=3):
""" Remove sessions with erroneous data due to a NeuroPsy Research App malfunction.
The error causes block data to be duplicated and the values for df1 & df2 multiplied again by 100.
The duplicated blocks are identified by comparing their time... | a0df0fac6835b85141f45de6ff4ed61ecfdfe413 | 683,853 |
def get_sitemap(app, excludes=("/", "/static/<path:filename>")):
"""Returns a sitemap for the given application.
Args:
app (flask.Flask): Application to be scanned.
excludes (tuple): Tuple of endpoints to be hidden.
Returns:
list: Returns a list containing valid endpoint urls and ... | 578541f58e3bd4a2b38da802b18f6f46226c66c9 | 683,854 |
def estimate_infectious_rate_constant(events,
t_start,
t_end,
kernel_integral,
count_events=None):
"""
Returns estimation of infectious rate for given events on... | d1a83bd79988de9467dbc6c952aec35e3d496cd2 | 683,855 |
def survey_media(instance, filename):
"""Return an upload path for survey media."""
if not instance.survey.id:
instance.survey.save()
return 'survey/{0}/{1}'.format(instance.survey.id, filename) | 5a7aadf99634a19ef6d3dbba59a1a3935548defe | 683,856 |
import requests
def check_main_service_healthcheck(SVC_URL):
""" Check the main service url health. Returns True of False based on HTTP response code"""
try:
r =requests.get(SVC_URL+'/NexTrip')
if r.status_code ==200:
return True
else:
return False
except Ex... | 227a37cbdf769ba63bdb50654d6c2992ba2aaa71 | 683,857 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.