content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _prepare_shape_for_expand_dims(shape, axes):
"""
Creates the expanded new shape based on the shape and given axes
Args:
shape (tuple): the shape of the tensor
axes Union(int, tuple(int), list(int)): the axes with dimensions expanded.
Returns:
new_shape(tuple): the shape wit... | b7851761c84c9fef40a82099a63cba0d3e68085f | 688,436 |
import math
def is_prime(number):
"""
Testing given number to be a prime.
>>> [n for n in range(100+1) if is_prime(n)]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
"""
if number < 2:
return False
if number % 2 == 0:
retur... | f07ac0c9f581ea8e2b8d659c00f5b564ab761858 | 688,437 |
def menu_relatorios(request):
"""
Funcão que contém as configurações do menu de relatórios do Controle de combustível.
Retorna um dicionário com as configurações
"""
menu_buttons = [
{'link': '/patrimonio/combustivel/talao/relatorios/mes', 'text': 'Mensal'},
{'link': '/patrimonio/co... | 87ade6244e7b8622ef7159d670944330e1c1052f | 688,438 |
from typing import BinaryIO
import os
def search_public_key(priv_key: str) -> BinaryIO:
"""
Looking for public key. Usually file name have suffix .pub.
Args:
priv_key (str): Path to private key.
Returns:
BinaryIO: Public part of SSH public as opened binary file.
"""
priv_key... | 082e33e6b9b2a2e1eddf5de62e452906c1c9f2bc | 688,439 |
import torch
def init_control(ctrl_obj, env, live_plot_obj, rec, params_general, random_actions_init,
costs_tests, idx_test, num_repeat_actions=1):
"""
Init the gym env and memory. Define the lists containing the points for visualisations.
Control the env with random actions for a number of steps.
Args:
ct... | 57b1b94afb5fd3772fc57c56e393fd88a1769055 | 688,440 |
def convert2DDict(twoDdict, header=None, row_order=None):
"""Returns a 2 dimensional list.
Parameters
----------
twoDdict
a 2 dimensional dict with top level keys corresponding to
column headings, lower level keys correspond to row headings but are
not preserved.
header
... | 26296f7f418f4b5e10f7b2d5bfe3e142402ad6d1 | 688,441 |
def create_keyword_string(command_string):
"""Creates the keyword string. The keyword string is everything before
the first space character."""
cmd_str = command_string.split(" ")[0]
return cmd_str | 2f12eb133a187b3f3fc376a1203bfb2c6b94e6d8 | 688,442 |
def normalize_azimuth(azimuth):
"""Normalize azimuth to (-180, 180]."""
if azimuth <= -180:
return azimuth + 360
elif azimuth > 180:
return azimuth - 360
else:
return azimuth | 18392629573b0a89d97f737e264ce5cf708a619e | 688,443 |
def real_calculate_check_digit(gs1_value):
"""
Calculate the check digit without specifying the identifier key.
:param gs1_value: GS1 identifier.
:return: Check digit.
"""
multipliers = []
counter = 0
total = 0
for i in reversed(range(len(gs1_value))):
d = gs1_value[i]
... | a8526c18358e68ef4ecf08d6385e40420f17679c | 688,444 |
def mock_write_handle_incorrect_return_value(mock_handle):
"""
Fixture that yields a mock USB device handle used for writing that yields back and incorrect
number of bytes written.
"""
mock_handle.bulkWrite.side_effect = lambda *args: len(args[1]) - 1
return mock_handle | 019990495797c5279bc51411c18248abd3aa843a | 688,445 |
def extract_compile_reports(events):
"""Get a list of all compiler reports in the event list.
Args:
events: A list of trace event serialized protobufs.
Returns:
A list of tuples containing the module name and report."""
return [] | abbccfb336c6fbbaf3dc20dec797bdf16795489f | 688,447 |
import re
def latex_compliant_name(name_string):
"""this function is required as latex does not allow all the component names
allowed by nnet3.
Identified incompatibilities :
1. latex does not allow dot(.) in file names
"""
node_name_string = re.sub("\.", "_dot_", name_string)
return ... | a905f98615c077bc0c068626f90fac771900c3c4 | 688,448 |
import os
import base64
def convert_file_to_base64(file_path):
"""
Return the content of a file given its path encoded in Base64.
:param file path: file path using slash as separator (e.g. "resources/files/doc.txt")
:return: string with the file content encoded in Base64
"""
file_path_parts =... | 4ab033edb7ef018373e92cf778816e32ea2da8d4 | 688,449 |
import hashlib
def make_epoch_seed(epoch_tx_count, ledger_count, sorted_ledger, address_from_ledger):
"""
epoch_tx_count = number of transactions made in a given epoch
ledger_count = the total number of ledger entries in the ledger database.
sorted_ledger = iterable that returns the nth ledger item. M... | d97915fdd6def978e72c443682a21628219c54cd | 688,450 |
def change_list_value(array: list, value_old: str, value_new: str) -> list:
""" Returns a given list with a changed value. """
for index, value in enumerate(array):
if value == value_old:
array[index] = value_new
return array | 1213c2407566360aa39393dfd1a837ef6aa12323 | 688,452 |
import os
def get_g_dir():
"""Gets the .goblet directory"""
return f"{os.path.realpath('.')}/.goblet" | 2ba1ef4bcf98b3b316546fe8e513deff99b660be | 688,453 |
def get_dict(key, value):
"""Returns the dictionary with command:page.html
:rtype : dict
:param key: commands
:param value: html page name
:return: dictionary of the commands and names of the pages
"""
return {k.lower(): v for (k, v) in zip(key, value)} | 3fca65b0b65be13d4bf10ad0210508625f613fa0 | 688,454 |
import json
def load_clusters(infile):
"""
Loads clusters in a sparse format from a JSON file.
Parameters
----------
infile : str
The JSON file containing sparse cluster information.
Returns
-------
list of set of tuple of int
The sets are clusters, the tuples are the... | cf7a418aa68f30fdbb42fe51ab758bad0d507775 | 688,455 |
def inclusion_one_default_from_template(one, two='hi'):
"""Expected inclusion_one_default_from_template __doc__"""
return {"result": "inclusion_one_default_from_template - Expected result: %s, %s" % (one, two)} | ecf3b4a300753a55972b21da4c8dec8e230edaf2 | 688,456 |
def innertext(node):
"""From
https://stackoverflow.com/questions/49783799/how-to-get-all-text-inside-xml-tags"""
t = ""
return " ".join(node.itertext()) | 89c1e13f1c77cff6f0a44b0db034e06d96831e94 | 688,457 |
def get_all_SN(pmgr):
""" Returns a list of all the motor SNs currently in the pmgr"""
pmgr.updateTables()
SNs = []
for obj in pmgr.objs.keys():
if pmgr.objs[obj]['FLD_SN'] > 0:
SNs.append(pmgr.objs[obj]['FLD_SN'])
return SNs | 4b8717a4ed3e2f5631fffcb89315e4ad211dfa5b | 688,459 |
def find_begin_end_numbers(name):
"""Finds numbers at the beginning or end of a string."""
name = list(name)
numbers = ''
while name[0].isdigit():
numbers += name.pop(0)
while name[-1].isdigit():
numbers = name.pop(-1) + numbers
return ''.join(name), int(numbers) if numbers else ... | 194cf99ea88d3258138daf86c47b753d1ea37633 | 688,460 |
def _todict(variable): # pragma: no cover
"""Construct dicts from Mat-objects."""
dict = {}
for strg in variable._fieldnames:
elem = variable.__dict__[strg]
dict[strg] = elem
return dict | 835008235f8a76ec974619b6585425f6f40cd0f4 | 688,462 |
def build_metric_link(region, alarm_name):
"""Generate URL link to the metric
Arguments:
region {string} -- aws region name
alarm_name {string} -- name of the alarm in aws
Returns:
[type] -- [description]
"""
url = 'https://{}.console.aws.amazon.com/cloudwatch/home?... | 00c79ec9a1aa66ceee91d8bdae93ae78fcd1d804 | 688,464 |
def vector_multiply(vector_in, scalar):
""" Multiplies the vector with a scalar value.
This operation is also called *vector scaling*.
:param vector_in: vector
:type vector_in: list, tuple
:param scalar: scalar value
:type scalar: int, float
:return: updated vector
:rtype: tuple
""... | 975178f4bcaa0348c7fb26f8f1d72ef80995bcfe | 688,465 |
def get_nltk_data(synsets_right_pos) -> object:
"""
Combine all three function from below to only iterate synsets_right_pos once
------------
Return only lemmas from all synsets, double values deleted through set
:return Dict[str, List] lemmas_set
-----
Return the antonyms from all synsets,... | b69464a5ea0d395190239e270cee7d9ac8cf71a8 | 688,466 |
def add_car_into_group(group, car):
"""
If car can be inserted into group, it must satisfy one of below condition:
1. Insert into middle.
insert car into .*b->b.* ==> car == b+
2. Insert into first.
car[-1] == group[0][0]
3. Insert into last.
car[0] == group[-1][-1]
:para... | 6bee19b797f38565d4285b658ec763f116dc2a95 | 688,467 |
import os
def fxtr_mkdir():
"""Fixture Factory: Create a new directory."""
def _fxtr_mkdir(directory_name: str):
"""
Fixture: Create a new directory.
Args:
directory_name (str): The directory name including path.
"""
os.mkdir(directory_name)
return _f... | 1c92b91c2a84195e3d350a766c022802487078f9 | 688,469 |
def tpm3():
"""Create test fixture for TPM3"""
return {
"variant": "1-154157570-C-T",
"assembly": "GRCh38",
"total_observations": {
"allele_count": 1,
"allele_number": 152152,
"decimal": "0.000006572"
},
"max_pop_freq": {
"p... | 27d9acfdd90753085a6f47f58f79e731a3539613 | 688,471 |
def load_meta(meta_file):
"""Load metadata file with rows like `utt_id|unit_sequence`.
Args:
meta_file: Filepath string for metadata file with utterance IDs and
corresponding quantized unit sequences, separated by pipes. Input
unit sequences should be separated by spaces.
Returns:
... | cdb76ebe61baaf162d953ef8f36a526c68d629e3 | 688,472 |
def _module_name(*components):
"""Assemble a fully-qualified module name from its components."""
return '.'.join(components) | 014650c55113e8632ac7872e12c73d1b2f2da46f | 688,473 |
from typing import Tuple
def find_prefix(root, prefix: str) -> Tuple[bool, int]:
"""
Check and return
1. If the prefix exsists in any of the words we added so far
2. If yes then how may words actually have the prefix
"""
node = root
# If the root node has no children, then return Fals... | aa8d7aec5c158e7fe0df3d31e73bfe53b183dedf | 688,474 |
def get_alpha(value, capital=False):
"""
Convert an integer value to a character. a-z then double, aa-zz etc.
@param value: int, Value to get an alphabetic character from
@param capital: boolean: True if you want to get capital character
@return: str, Character from an integer
"""
# Calcula... | 07aba1b72c9bcc356b758043422828f2cbc6ac89 | 688,475 |
def logfile_opt_to_str(x):
"""
Detypes a $XONSH_TRACEBACK_LOGFILE option.
"""
if x is None:
# None should not be detyped to 'None', as 'None' constitutes
# a perfectly valid filename and retyping it would introduce
# ambiguity. Detype to the empty string instead.
return "... | afd97b22ad1e8a3d916c18c4f5b60af713e6db16 | 688,476 |
def X_or_Y_numeric(left: float, right: float, x_and_y: float) -> float:
""" Calculates the OR area between `left` and `right`
Parameters
----------
left, right: pandas.Series
The two series to calculate the exclusive area on.
x_and_y: float
Precomputed values for the area of `left`, `right`, and x_and_y.... | f4276d8081c1757e498d9a5d9902b4913fcfb03b | 688,477 |
def apps(request):
"""
Apps to test
"""
return request.config.option.apps.split(',') | b1236f2e234354d4884eacf61973c8805b05266e | 688,478 |
from PIL import ImageFile as PillowImageFile
import zlib
import struct
def get_pillow_attribute(file, pil_attr):
"""
Returns an attribute from a Pillow image of the given file,
file
a file. wrappable by Pillow. Must be open
pil_attr
the attribute to read.
return
the attrib... | 195927484249535d6c097a3132d7b251b4c75305 | 688,480 |
from datetime import datetime
def get_time():
"""Get current server time - used for troubleshooting, MFA can be picky"""
return str(datetime.now().timestamp()) | d30ed2eeb99c81bc639857c1ba3aa1723bc40caf | 688,481 |
def find_check_run_by_name(check_runs, name):
""" Search through a list of check runs to see if it contains
a specific check run based on the name.
If the check run is not found this returns 'None'.
Parameters
----------
check_runs : list of dict
An array of check runs. This can be an ... | bc8f20ab6b60ee331115bef226ea89709bf4dbc0 | 688,482 |
def count_words(item):
"""Convert the partitioned data for a word to a
tuple containing the word and the number of occurances.
"""
word, occurances = item
return word, sum(occurances) | d0587dbca4b8eb7f0817119f392db6079efd579d | 688,483 |
def _get_oauth2_info(_helper_cfg):
"""This function parses OAuth 2.0 information if found in the helper file.
.. versionchanged:: 2.2.0
Removed one of the preceding underscores in the function name
"""
_oauth2 = {}
_oauth2_keys = ['client_id', 'client_secret', 'redirect_url']
for _key in... | 8a573a222d80ab523af705ed36173b60f73df505 | 688,484 |
import torch
def randomized_argmax(x: torch.Tensor) -> int:
"""
Like argmax, but return a random (uniformly) index of the max element
This function makes sense only if there are ties for the max element
"""
if torch.isinf(x).any():
# if some scores are inf, return the index for one of the ... | 115423d3da3770e1247f8980a09e193d9c37e934 | 688,485 |
from typing import Literal
def compatible_operation(*args, language_has_vectors = True):
"""
Indicates whether an operation requires an index to be
correctly understood
Parameters
==========
args : list of PyccelAstNode
The operator arguments
language_has_vectors : bo... | 7fe422dab78fac2aa06d67cdac3ce00eed7e4cc6 | 688,487 |
from typing import Dict
from typing import Any
def _get_player_pts_stat_type(player_pts: Dict[str, Any]) -> str:
"""
Helper function to get the stat type within the pulled player
points. Will be either 'projectedStats' or 'stats'.
"""
unique_type = set([list(v.keys())[0] for v in player_pts.values... | fe6560a7bb8096810ed56b4a2334997823103a27 | 688,488 |
def formatEdgeDestination(node1, node2):
"""
Gera uma string que representa um arco node1->node2
Recebe dois inteiros (dois vértices do grafo), e o formata com a notação de
aresta a->b onde a é o vértice de origem, e b o de destino.
Args:
node1 (int): número de um dos vértices ligados à ar... | 517997fb634b0c9c12fc61d1e582f584786c6196 | 688,489 |
def make_response(response):
"""
Make a byte string of the response dictionary
"""
response_string = response["status"] + "\r\n"
keys = [key for key in response if key not in ["status", "content"]]
for key in keys:
response_string += key + ": " + response[key] + "\r\n"
response_strin... | c3ed39fdce286dbc1462258a31395818b58668cb | 688,490 |
def repetition_plane(repetitions, n=8):
"""
:param int repetitions: Number of times a chess position (state) has been reached.
:param int n: Chess game dimension (usually 8).
:return: An n x n list containing the same value for each entry, the repetitions number.
:rtype: list[list[in... | fd73daa9ba178e810acbcc1428a26175c2daf6d7 | 688,491 |
def test_service():
"""
Test service is running correctly. This route exposes an endpoint that returns a service is running prompt.
"""
return "Transit backend service is running." | a6e4f25ca1aca04cc498867a5b6504a480b62d2d | 688,492 |
def line_from_text(content='', some_text=[]):
"""
returns the first line containing 'content'
:param content:
:param some_text: list of strings
:return: line containing text
"""
matching_line = ''
for line in some_text:
if line.find(content) >= 0:
matching_line = line... | 51fb74d92440e0521c87cdfd441ba3421a675cf3 | 688,494 |
import torch
def batch_matrix_norm(matrix, norm_order=2):
""" normalization of the matrix
Args:
matrix: torch.Tensor. Expected shape [batch, *]
norm_order: int. Order of normalization.
Returns:
normed matrix: torch.Tensor.
"""
return torch.norm(matrix, p=norm_order, dim=... | 8e26db83d49ce6886866ca9e53df0ad10628c5b8 | 688,495 |
def extract_patterns(line, frequent_words):
"""
Take single LogLine and output a tuple of frequent words and frequent words with skips
Args:
log_lines(LogLine): Input log line
Returns:
(tuple([str]), list[str]) : tuple of (frequent words in order, freq words with skip counts between f... | f00652e3f991278b7860181a94817f4624cd83cb | 688,496 |
def _jaccard(a, b):
""" Return the Jaccard similarity between two sets a and b. """
return 1. * len(a & b) / len(a | b) | 0d744b71b4b6fbc0530631aa7daad206349a63d9 | 688,497 |
def compute_grade(questions_coeff, questions_grade):
"""
Compute a grade from grade for each question (/2) and
associated coefficients
:param questions_coeff: list of coefficients for each question
:param questions_grade: list of grade for each question
"""
assign_grade = 0
sum_coeff = ... | 5f2b194017f96248c6a68ae46b9a810d0e5d671a | 688,498 |
def fetch(request, fields, blanks=[]):
""" Extremely rudimentary validation simply checks whether the
fields are present and non-empty in the POST parameters. """
values = {}
ok = True
for field in fields:
val = request.POST.get(field, '')
if val == '' and field not in blanks:
... | aa6fa633cbfe9076f66ea976b65c3d2f25d521e1 | 688,499 |
def _do_step(x, y, z, tau, kappa, d_x, d_y, d_z, d_tau, d_kappa, alpha):
"""
An implementation of [1] Equation 8.9
References
----------
.. [1] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
optimizer for linear programming: an implementation of the
homog... | 0c38e2f18f7c934d910c024c23d35e13660eec08 | 688,500 |
def bgr_to_rgb(color: tuple) -> tuple:
"""Converts from BGR to RGB
Arguments:
color {tuple} -- Source color
Returns:
tuple -- Converted color
"""
return (color[2], color[1], color[0]) | c8d121e43034b441ac38342d005e308cec8d02ee | 688,501 |
import copy
import torch
def lp_path_norm(model, device, p=2, input_size=[3, 32, 32]):
"""
Path norm (Neyshabur 2015)
"""
tmp_model = copy.deepcopy(model)
tmp_model.eval()
for param in tmp_model.parameters():
if param.requires_grad:
param.abs_().pow_(p)
data_ones = tor... | 1c4acdc210491504bbd298e52875b9feb61e2dc4 | 688,502 |
def get_run_data_from_cmd(line):
"""Parser input data from a command line that looks like
`command: python3 batch_runner.py -t benders -k cache -i s6.xml -v y -r 0`
and put it into a dict.
"""
words = line.split(" ")[3:]
word_dict = {}
for (i, word) in enumerate(words):
if word.sta... | cb29a4be45abebb463e96fc4f36938ebdb2f6e52 | 688,503 |
import importlib
def model_fn_builder(runner_config, mode):
"""Returns `model_fn` closure for TPUEstimator."""
rel_module_path = "" # empty base dir
model = importlib.import_module(rel_module_path + runner_config["name"])
model_config = runner_config["model_config"]
return model.Encoder(model_config, mode) | f20fe03dcd139d4ec974a256c9e807dfe583e2f2 | 688,504 |
import numpy
import itertools
def triangle_smooth_bounds_matrices(lmat, umat):
""" smoothing of the bounds matrix by triangle inequality
Dress, A. W. M.; Havel, T. F. "Shortest-Path Problems and Molecular
Conformation"; Discrete Applied Mathematics (1988) 19 p. 129-144.
This algorithm is directly fr... | a376637b4ebe100abc9911e5c844efb8dd67413f | 688,505 |
def slurp(fname: str) -> str:
"""
Reads a file and all its contents, returns a single string
"""
with open(fname, 'r') as f:
data = f.read()
return data | f94e6140eb79e25da695afe2f4bd44a1e96cf55c | 688,509 |
def _make_request_pb(request, request_pb_type):
"""Helper for converting dicts to request messages."""
if not isinstance(request, request_pb_type):
request = request_pb_type(**request)
return request | 766c1ad3cfaf17cdbcfcc588781dd9f0e8b96ed1 | 688,510 |
def tables_from_src(src_data):
"""
:param src_data: A source data file (either column or table)
:return: All tables found in file prefixed with schema.
"""
return set([s['schema']+"."+s['table'] for s in src_data]) | 21b4d533e34626b87fef1733253903b1cef34d2c | 688,511 |
import os
def generate_key():
"""Takes 6 bytes one at a time from the OS random device,
converts them to integers, adds them together, and takes
the modulo 6 value as a piece of a 5 digit key.
Returns a key for a value in the Diceware dictionary.
"""
key = ''
for _ in range(5):
d... | 0bd25e166e3f37d02239cdc252c6218bd3af8e70 | 688,512 |
def create_img(height, width, color):
"""
Creates an image of the given height/width filled with the given color
PARAMS/RETURN
height: Height of the image to be created, as an integer
width: Width of the image to be created, as an integer
color: RGB pixel as a tuple of 3 integers
re... | d2f5b3d881c75e2f2b9664584748439d8b7e5ae9 | 688,513 |
def acc_dialogue(current_platform):
""" acc_dialogue
Arguments:
* current_platform: Current platform accession ID specified in
settings.py
Returns:
* User-specified platform accession ID, based on prompt outcomes.
"""
input2 = current_platform
prompt1 ... | a7aa0c317fff8f5618363b48f9ff1c1ad547bb56 | 688,514 |
import zipfile
def _NoClassFiles(jar_paths):
"""Returns True if there are no .class files in the given JARs.
Args:
jar_paths: list of strings representing JAR file paths.
Returns:
(bool) True if no .class files are found.
"""
for jar_path in jar_paths:
with zipfile.ZipFile(jar_path) as jar:
... | 828e078e33ef129ab151346611fbe0a9be8bf739 | 688,516 |
import torch
def process_sequence_wise(cell, x, h=None):
"""
Process the entire sequence through an GRUCell.
Args:
cell (DistillerGRUCell): the cell.
x (torch.Tensor): the input
h (tuple of torch.Tensor-s): the hidden states of the GRUCell.
Returns:
y (torch.Tensor)... | 520889174cd83b6fb598a78f9fbec6018d0dc8bb | 688,517 |
import csv
def file_to_position_depths(file_path):
"""Get the position and depths from one file. Read into memory as a dictionary with (lat, lon) as the key and depth
as the value."""
# create the dictionary
result = {}
# read the position and depth data from the input csv file
with open(fil... | 461b9eac168795e4259f38800caa9c29fe620dec | 688,518 |
def check_storage_type_compatibility(source_storage,
target_storage):
"""Checks if the storages are compatible or not."""
return not (source_storage.is_archive and target_storage.is_archive) | 2ac9385d73abca01e45c829a0f4a92eb0bfee1af | 688,519 |
def serialize_email_principal(email):
"""Serialize email principal to a simple dict."""
return {
'_type': 'Email',
'email': email.email,
'id': email.name,
'name': email.name,
'identifier': email.identifier
} | d6b821f735ff28d007286ef6523be9f17fade928 | 688,520 |
def convert_values(any_dict):
"""
input : dict
this function make appropriate dict to use of tabulate function
returns : list
"""
result_list = []
for n in range(20):
sub_list = []
for key in any_dict:
sub_list.append(any_dict[key][n])
... | 9fb29e5759fb3464fe7105b801a05aad09ddd6a0 | 688,521 |
import struct
def randbyteshex(bytecount, source="/dev/urandom"):
"""Return bytecount good pseudorandom bytes as a hex string."""
src = open(source, "rb")
thebytes = struct.unpack("B" * bytecount, src.read(bytecount))
hexstring = "%02x" * bytecount % thebytes
src.close()
return hexstring | bb3e29f4ab44cc4c1d167a57816d79c57e47a5db | 688,522 |
def precondition_betas(betas, pc_factors):
"""Precondition the parameters before minimization."""
betas = betas.reshape(betas.shape[0] * betas.shape[1], len(pc_factors))
betas_tmp = [list(b * pc_factors) for b in betas]
betas_pc = [item for sublist in betas_tmp for item in sublist]
return betas_pc | 8d859af65c52b2d0ba0e8113e1c6c612c59bc559 | 688,524 |
import collections
def _determine_image_distribution(nodes):
"""Finds the current distribution of cached images across available nodes.
Returns a dictionary where the keys are image uuids and the values are
the integral frequency of their occurance.
"""
cached_images = [node.cached_image_uuid for... | ede6a425555dc059d858fd9e3f3b9c50e95809ba | 688,526 |
def AAPILoad():
""" called when the module is loaded into Aimsun """
return 0 | 987a28d25b1574ddf6cff066264dfed3eceee748 | 688,527 |
def dates_to_str(dates):
"""Transforms list of dates into a string representation with the ARRAY keyword heading.
Parameters
----------
dates: list
Returns
-------
dates: str
"""
heading = 'ARRAY DATE'
footing = '/'
res = [heading] + [d.strftime('%d %b %Y').upper() for d in... | 7f50569322bd06a38b9d1a4229ba25afdd244307 | 688,528 |
def create_ordered_list(data_dict, items):
"""Creates an ordered list from a dictionary.
Each dictionary key + value is added to a list, as a nested list.
The position of the nested item is determined by the position of the key
value in the items list. The returned list is the dictionary ordered on... | 929538546a2f8d2ebbcb22c2eac6effc87769339 | 688,529 |
import logging
import time
def create_org_id():
"""
生成机构唯一标识----org_id
:return:
"""
logging.info('create_org_id')
return "G" + str(int(time.time())) | 74a03bd7c859f59fb5af2c9b36e0472170b95c73 | 688,530 |
def convert_size_in_points_to_size_in_pixels(size):
"""
6pt = 8px = 0.5em
7pt = 9px = 0.55em
7.5pt = 10px = 0.625em
8pt = 11px = 0.7em
9pt = 12px = 0.75em
10pt = 13px = 0.8em
10.5pt = 14px = 0.875em
11pt = 15px = 0.95em
12pt = 16px = 1em
13pt = 17px = 1.05em
13.5pt = 18px... | 1c5be5557a6b32dee96f3f4ed6238f2e3e6475d0 | 688,531 |
def drop_empty(df, percent=10):
"""
Remove columns with more than {percent} missing values
"""
print(f"Suppresion des colonnes avec plus de {percent}% de données manquantes")
new_df = df.copy()
for col in df.columns:
if round((1-df[col].notna().sum()/len(df))*100, 2)>percent:
... | 90261a18d4fd92f9af5cfbf2b5b2e067ffe3fa0d | 688,533 |
def get_color(count):
"""Simple color scale."""
color = ""
if count == 0:
color = "is-danger"
elif count < 20:
color = "is-warning"
elif count < 300:
color = "is-primary"
elif count < 1000:
color = "is-success"
else:
color = "is-black"
return color | 5f80900597b57323bd3ba881d424f5d8b9883031 | 688,535 |
from typing import List
import traceback
def stacktrace(ex) -> List[str]:
"""Get list of strings representing the stack trace for a given exception.
Parameters
----------
ex: Exception
Exception that was raised by flowServ code
Returns
-------
list of string
"""
try:
... | 32bd9148d9f885a19017894be4417e64b9ff1f3d | 688,536 |
from operator import concat
def add_delimiter(items):
""" Concats a list of strings as an JSON array"""
content = ''
size = len(items)
for item in range(0, size):
new_item = concat(items[item], '***')
content = concat(content, new_item)
return content | 71e8870c1aeee12e9d2ee39bf222605726af4239 | 688,537 |
def scaleto255(value):
"""Scale the input value from 0-100 to 0-255."""
return max(0, min(255, ((value * 255.0) / 100.0))) | fdf0ba0717df4c85fc055c1b8bc2590a22c4bd09 | 688,538 |
def receivables_turnover(revenue, average_receivables):
"""Computes receivables turnover.
Parameters
----------
revenue : int or float
Revenue
average_receivables : int or float
Average receivables for the period
Returns
-------
out : int or float
Receivables tu... | 0b88bf43cc7d8c3513534db82b4ae54964eefb42 | 688,539 |
def clean_battlefield(battlefield: str) -> str:
"""
Clean the battlefield and return only survived letters
:param battlefield:
:return:
"""
result = battlefield.split('[')
result = [string for string in result if string != '']
result = list(reversed(result))
temp = list()
while result:
for i, r in enumerat... | 3a2a277987f5341db265d948e14a7bfd210decf1 | 688,540 |
import json
def map_uniprot_to_external(json_mapper_file):
"""
Maps primary uniprot ids to different external source ids based on the mapping table
Also retrievs the database which the id is from (id type)
:param uniprot: uniprot id that we want to fing external references for
:return: external re... | 5ddfdbd015d5bd8e6220b3eb0bfd00167a05573a | 688,541 |
import pathlib
def get_files(extensions):
"""List all files with given extensions in subfolders
:param extensions: Array of extensions, e.g. .ttl, .rdf
"""
all_files = []
for ext in extensions:
all_files.extend(pathlib.Path('cloned_repo').rglob(ext))
return all_files | c8b697c555ec49866f0e2dba6166415d69df22a4 | 688,542 |
from typing import Union
from typing import List
from typing import Tuple
def flatten(xs: Union[List, Tuple]) -> List:
""" Flatten a nested list or tuple. """
return (
sum(map(flatten, xs), [])
if (isinstance(xs, list) or isinstance(xs, tuple))
else [xs]
) | e520fb245e5a681ca446f50c7bb4fd55cfaedc18 | 688,543 |
import csv
def read_csv(filepath, encoding='utf-8'):
"""
This function reads in a csv and returns its contents as a list
Parameters:
filepath (str): A str representing the filepath for the file to be read
encoding (str): A str representing the character encoding of the file
Returns:
... | aee38a14ca7194c7040b6e8652ad9d43b10e0144 | 688,544 |
def build_complement(dna):
"""
Loop the character in DNA. Concatenating the complement character in ans list.
:param dna: string, the strand we need to complement.
:return: ans: string, the complement strand of DNA sequence.
"""
ans = ''
for nucleotide in dna:
if nucleotide == 'A':
... | 2efc564168dcb6bd552eaa4d5129779cdd2da60f | 688,545 |
def subtract_year(any_date):
"""Subtracts one year from any date and returns the result"""
date = any_date.split("-")
date = str(int(date[0])-1) + "-" + date[1] + "-" + date[2]
return date | b5183d66931cfcc374384868ee646c551e12dd40 | 688,546 |
import re
def remove_whitespace(s, right=False, left=False):
"""
Remove white-space characters from the given string.
If neither right nor left is specified (the default),
then all white-space is removed.
Parameters
----------
s : str
The string to be modified.
right : bool
... | 8bc8e9efbdb726878814c538f07d390c11a1a3d3 | 688,547 |
import ipaddress
def ipstring_from_list(ipstrings):
"""
Creates a string of format a.b.c.d+x from a list of ips.
"""
ips = [ipaddress.IPv4Address(ip) for ip in ipstrings]
ips.sort()
if ips[0] + len(ips) - 1 != ips[-1]:
raise RuntimeError("IP list not continous")
return "{}+{}".fo... | c112c597102ee8216c2705fd1a43d8c19bd871ea | 688,548 |
def fun_z(weights, inputs):
"""计算神经元的输入:z = weight * inputs + b
:param weights: 网络参数(权重矩阵和偏置项)
:param inputs: 上一层神经元的输出
:return: 当前层神经元的输入
"""
bias_term = weights[-1]
z = 0
for i in range(len(weights)-1):
z += weights[i] * inputs[i]
z += bias_term
return z | 4cf92cdafa3d86480f66b8dc1400be3fe59a437f | 688,549 |
def get_aux_verbs(tokens):
"""Identify, color and count auxiliary verbs """
aux_verbs = [k for k in tokens if k.full_pos.startswith('VA')]
for t in aux_verbs:
t.pos_color.append('Auxiliary verbs')
return len(aux_verbs) | e7f8b7c9d69b24e8211ebbb824761be61c7cb935 | 688,550 |
def containsDuplicateB(nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums:
return False
d={}
for i in nums:
if i in d:
return True
else:
d[i] = True
return False | 6f3053b1e0fe03da33ff208b99c1f794ee7dd1a9 | 688,551 |
def compact(text, **kw):
"""
Compact whitespace in a string and format any keyword arguments into the
resulting string. Preserves paragraphs.
:param text: The text to compact (a string).
:param kw: Any keyword arguments to apply using :py:func:`str.format()`.
:returns: The compacted, formatted ... | 66c095b7cf180dc2db7e83a306e6d9bb8af0cecc | 688,552 |
import argparse
import sys
def get_args():
"""Get all parsed arguments."""
parser = argparse.ArgumentParser(description="CLASP training loop")
# data
parser.add_argument("--id", type=str,
help="run id")
parser.add_argument("--path-data", type=str,
h... | 90674650e248689e145e8d5febde6992dc8e7b1c | 688,553 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.