content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def steps(execution_id, query_params, client):
"""Get execution steps for a certain execution."""
return client.get_execution_steps(execution_id, **query_params) | 4b2a29ec32db80cbe02980d5f2585c48e8284338 | 661,371 |
def gen_labor_force_change(shortened_dv_list):
"""Create variables for the change in labor force for the current and
previous months."""
labor_force_change = round((shortened_dv_list[5] - shortened_dv_list[4]) * 1000)
prev_labor_force_change = round((shortened_dv_list[4] - shortened_dv_list[3]) * 1000)... | f40ff058e81d6f2bfa3f17a6e0165618fab7cebb | 661,372 |
import json
def validate(resp):
"""Check health status response from application.
Args:
resp (string): Response will be converted to JSON and then analyzed.
Returns:
(bool): True if application healthy.
"""
print(resp)
try:
data = json.loads(resp)
except:
... | 87ec568e908c01496f4b3c4fca1b25f518a6a2b3 | 661,373 |
def get_index_size_in_kb(opensearch, index_name):
"""
Gets the size of an index in kilobytes
Args:
opensearch: opensearch client
index_name: name of index to look up
Returns:
size of index in kilobytes
"""
return int(
opensearch.indices.stats(index_name, metric='s... | a5a339d5055e66e007caa82f7a70cb2cf4d84e6a | 661,374 |
def getbox(face):
"""Convert width and height in face to a point in a rectangle"""
rect = face.face_rectangle
left = rect.left
top = rect.top
right = left + rect.width
bottom = top + rect.height
return top, right, bottom, left | c30b8647785518e9aebb94adf9945ac7ea79faa5 | 661,376 |
def exponential(start_at):
"""Return and exponentially increasing value
:param float start_at: Initial delay in seconds
:rtype func:
"""
def func(count):
count -= 1
return start_at * (2**count)
return func | 0245a7a19f354dbafd51ba78467e77a7eae12b6c | 661,379 |
def use_node_def_or_num(given_value, default_func):
"""Transform a value of type (None, int, float, Callable) to a node annotation function."""
# Default: use pre-defined function from this module
if given_value is None:
func = default_func
# Transform: value to function that returns the value
... | e3cd540dd8272647c18f6d2d9e65f40bf509e63b | 661,381 |
def find_root(ds):
"""
Helper function to find the root of a netcdf or h5netcdf dataset.
"""
while ds.parent is not None:
ds = ds.parent
return ds | 0deed0eac3164b23a6df67e8fa5ed175b95f2952 | 661,382 |
from typing import List
def make_parallel_commands(
commands: str, repeats: int, parallel: int
) -> List[List[str]]:
""" Build list of lists,
where the inner list contains a group of commands to be executed in a sequence"""
command_list = commands.split("|")
command_list = [comm.strip() for comm... | 813b662f6d31c01e25cf32811fc452f5e7e07b92 | 661,384 |
def prime_sieve(n):
"""
Return a list of all primes smaller than or equal to n.
This algorithm uses a straightforward implementation of the
Sieve of Eratosthenes. For more information, see
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
Algorithmic details
-------------------
... | 180dc6a2ff1d3096630a6279ace841e4c5efdd83 | 661,389 |
def _create_into_array_list(phrase):
"""Create load or store into array instructions
For example, with the phrase 'astore':
[
'iastore',
'fastore',
...
'aastore'
]
"""
# noinspection SpellCheckingInspection
return [letter + phrase for letter in 'lfdibcsa'] | 3ae0bfbcd1ef3b6fcb8538ccb02c3a150151458e | 661,390 |
def removekeys(toc, chapnum):
"""Return new dictionary with all keys that don't start with chapnum"""
newtoc = {}
l = len(chapnum)
for key, value in toc.items():
if key[:l] != chapnum:
newtoc[key] = value
return newtoc | 91d1986e8addf1906a0e7694b229e53148e5d3cf | 661,392 |
import builtins
import gzip
def open(filename, mode='r', compress=False, is_text=True, *args, **kwargs):
""" Return a file handle to the given file.
The only difference between this and the standard open command is that this
function transparently opens zip files, if specified. If a gzipped file is
... | 59edbe674ba434326ba9a09b71ae9e0ed770c29a | 661,399 |
import random
import string
def generate_random_string(length):
"""Utility to generate random alpha string for file/folder names"""
return ''.join(random.choice(string.ascii_letters) for i in range(length)) | b33734caf1c95e5a2f000f9673e8956e16c11614 | 661,402 |
def check_header_gti(hdr):
"""
Check FITS header to see if it has the expected data table columns for GTI
extension.
Require the following keywords::
TELESCOP = 'NuSTAR' / Telescope (mission) name
HDUCLAS1 = 'GTI' / File contains Good Time Intervals
NAXIS = ... | b478b0165244cf36019d26af3d6518b82e5d3925 | 661,406 |
def convert_args_to_list(args):
"""Convert all iterable pairs of inputs into a list of list"""
list_of_pairs = []
if len(args) == 0:
return []
if any(isinstance(arg, (list, tuple)) for arg in args):
# Domain([[1, 4]])
# Domain([(1, 4)])
# Domain([(1, 4), (5, 8)])
... | 2c0e10244a85e68f7da87db4e420648b702c1391 | 661,407 |
import re
def has_datas(command):
""" Function to determine if there is data in the curl command, even if the datas are empty
or only if there is --data or -d without something next to it."""
has_datas_pattern = r"(-d|--data)"
has_datas = re.search(has_datas_pattern, command)
return True if has_d... | 4f7c639f428aeca2239a9468a6f723db4dfb2419 | 661,422 |
def check_key(data, key):
""" Check if key in data. If so, then return the value, otherwise
return the empty string.
"""
if data.keys().__contains__(key):
return data[key]
else:
return '' | b74bda9a268b19918844a779365b0ca8022a2ec8 | 661,423 |
def guess_type_value_type(none=True):
"""
@param none if True and all values are empty, return None
@return the list of types recognized by guess_type_value
"""
typstr = str
return [None, typstr, int, float] if none else [typstr, int, float] | 5926dc0ce7f766cb1e596fe8d4f5ff97f41fa9c9 | 661,424 |
from typing import Any
def decode_answer(response_data: dict) -> Any:
"""
Decode the answer described by *response_data*, a substructure of an
enrollment document.
Returns a string, number, tuple of strings, or None.
"""
answer = response_data["answer"]
if answer["type"] in ["String", "N... | e0c88644f09412a95ab6df929f691d6936140fc3 | 661,425 |
def extract_line_coverage(coverage):
"""Extract line coverage from raw coverage data."""
line_coverage = {}
# file name -> function data
for filename, function_data in coverage.items():
line_coverage[filename] = {}
# function -> line data
for _, line_data in function_data.items(... | 1c7727353b9089e02a07fa447904e8333415718f | 661,438 |
import random
def reduce_dicts(titles, gold, shuffle=False):
""" reduce 2 dictionaries to 2 lists,
providing 'same index' iff 'same key in the dictionary'
"""
titles, gold = dict(titles), dict(gold)
titles_list = []
gold_list = []
for key in titles:
titles_list.append(titles[key])
... | 374b814fc59d5caa8500d567c9e7eb6b0b542628 | 661,440 |
def int_list_to_str(lst):
"""
Given a list of integers: [1, 10, 3, ... ]
Return it as a string of the form: "[1,10,3,...]"
"""
return "[%s]" % ','.join([str(l) for l in lst]) | af21e4142a4a7819a5e64950416ac919b0d0b44d | 661,441 |
import time
def wait_for(predicate, timeout, period=0.1):
"""
Wait for a predicate to evaluate to `True`.
:param timeout: duration, in seconds, to wait
for the predicate to evaluate to `True`.
Non-positive durations will result in an
indefinite wait.
:param period: predicate evaluat... | 03564b07b51ad29785562611bca36490156d205e | 661,443 |
def _create_statistics_data(data_list, is_multi_series=False):
"""
Transforms the given list of data to the format suitable for
presenting it on the front-end. Supports multi series charts (like
line and bar charts) and or single series ones (like pie/donut
charts).
:param data_list: a list of ... | 2376cfe38e5ad7828db096a6163e37656a65f220 | 661,446 |
import struct
def ubyte_to_bytes(byte_data: int)->bytes:
"""
For a 8 bit unsigned byte
:param byte_data:
:return: bytes(); len == 1
"""
result = struct.pack('<B', byte_data)
return result | 7d4c834d527e0fce3cca5575636047423ce44f6e | 661,448 |
def member_to_beacon_proximity(m2badge, id2b):
"""Creates a member-to-beacon proximity DataFrame from member-to-badge proximity data.
Parameters
----------
m2badge : pd.DataFrame
The member-to-badge proximity data, as returned by `member_to_badge_proximity`.
id2b : pd.Series
... | 458f2894190689ea3ca31483c1e814ccc31a9795 | 661,449 |
def get_height_magnet(self):
"""get the height of the hole magnets
Parameters
----------
self : HoleM50
A HoleM50 object
Returns
-------
Hmag: float
height of the 2 Magnets [m]
"""
# magnet_0 and magnet_1 have the same height
Hmag = self.H3
return Hmag | 99bd4c0d503fc86ba4491cde1b3fc7db904af91c | 661,452 |
def get_deployment_labels(deployments):
"""
Get labels for a given list of deployments.
Returns a dictionary in the below format:
{ deployment_name: {dictionary of deployment labels}, ...}
"""
deployment_dictionary = {}
for deployment in deployments:
deployment_dictionary[deploymen... | 418786845c1f9313e6f1e670927f3f600553dab7 | 661,457 |
def getFloatFromStr(number: str) -> float:
""" Return float representation of a given number string.
HEX number strings must start with ``0x``.
Args:
numberStr: int/float/string representation of a given number.
"""
numberStr = number.strip()
isNegative = False
if "-" in numberStr:
... | de5ee4e8193bd8127bb8d42946e184f45d1f3b23 | 661,459 |
from typing import List
import math
def calculate_percentile(times: List[int], percent=0.95) -> int:
"""
Calculate percentile (by default 95%) for sorted `times`.
If we cannot choose one index, we use average of two nearest.
"""
index = (len(times) - 1) * percent
if index.is_integer():
... | fafde68141aa7a788d334acd21f488df435479b9 | 661,461 |
def insertion_sort(array: list, ascending=True) -> list:
"""This function sort an array implementing the insertion sort method
Parameters
----------
array : list
A list containing the elements to be sorted
ascending : boolen
Indicates whether to sort in ascending order
Retu... | 6083b4918048ec19ddde159391d7be284c2feabf | 661,463 |
import re
def get_pool_uuid_service_replicas_from_stdout(stdout_str):
"""Get Pool UUID and Service replicas from stdout.
stdout_str is something like:
Active connections: [wolf-3:10001]
Creating DAOS pool with 100MB SCM and 0B NvMe storage (1.000 ratio)
Pool-create command SUCCEEDED: UUID: 9cf5be... | 276dca436ce16b23fb2dd9f108ef4c309c030c8e | 661,464 |
import copy
def copy_list(src, deep_copy=False):
"""
Copies list, if None then returns empty list
:param src: List to copy
:param deep_copy: if False then shallow copy, if True then deep copy
:return: Copied list
"""
if src is None:
return list()
if deep_copy:
return co... | 4e658232de46c196983597e4410413f812ef1882 | 661,465 |
def get_head(text, headpos, numchars):
"""Return text before start of entity."""
wheretostart = headpos - numchars
if wheretostart < 0:
wheretostart = 0
thehead = text[wheretostart: headpos]
return thehead | 25c8b90f341b328c8c452d88a98c52b8107734cd | 661,467 |
def get_in(dct, keys):
"""Gets the value in dct at the nested path indicated by keys"""
for key in keys:
if not isinstance(dct, dict):
return None
if key in dct:
dct = dct[key]
else:
return None
return dct | 1445fbfd3b47a5b0f23968dcf8695cdb0716eeea | 661,468 |
def initial_investment(pv_size, battery_size, n_batteries = 1, capex_pv = 900, capex_batt = 509):
"""Compute initial investment"""
return pv_size*capex_pv + battery_size*capex_batt*n_batteries | fbc34697b933fac22ae047213bef5a23a70e6dd2 | 661,470 |
def compress(years):
"""
Given a list of years like [2003, 2004, 2007],
compress it into string like '2003-2004, 2007'
>>> compress([2002])
'2002'
>>> compress([2003, 2002])
'2002-2003'
>>> compress([2009, 2004, 2005, 2006, 2007])
'2004-2007, 2009'
>>> compress([2001, 2003, 2004, 2005])
'2001, 20... | f506476fd073246d7827104d338c4226ca6d28b9 | 661,478 |
import torch
def predict_cmap_interaction(model, n0, n1, tensors, use_cuda):
"""
Predict whether a list of protein pairs will interact, as well as their contact map.
:param model: Model to be trained
:type model: dscript.models.interaction.ModelInteraction
:param n0: First protein names
:type... | a90efa0026a50ed5fa6d59e9d0dd42eefcfc2394 | 661,479 |
def parse_country_details(response, pos=0):
"""Parses the country details from the restcountries API.
More info here: https://github.com/apilayer/restcountries
Args:
response (:obj:`list` of `dict`): API response.
Returns:
d (dict): Parsed API response.
"""... | 33c6a0f3430a928ad5e11fd4e150dc0a174cad04 | 661,480 |
def obtain_factorial(x):
"""
Helper function obtain_factorial() for the factorial() function.
Given value x, it returns the factorial of that value.
"""
product = 1
for ii in list(range(x)):
product = product * (ii + 1)
return(product) | 66b576072522d8b21a4bb0b93734f7fff78a21fe | 661,483 |
def get_ascii_from_char(char: str) -> int:
"""Function that converts ascii code to character
Parameters
----------
char : character
character to convert to ascii
Returns
-------
ascii_code : int
Ascii code of character
"""
return ord(char) | 044c0f2d7f9b773edefa89a98db13738f18538d9 | 661,487 |
def get_comments(github_object):
"""Get a list of comments, whater the object is a PR, a commit or an issue.
"""
try:
return github_object.get_issue_comments() # It's a PR
except AttributeError:
return github_object.get_comments() | 8afb6d9c7123d6e54aae686ba908cfae994c9a65 | 661,488 |
def _resolve_subkeys(key, separator='.'):
"""Resolve a potentially nested key.
If the key contains the ``separator`` (e.g. ``.``) then the key will be
split on the first instance of the subkey::
>>> _resolve_subkeys('a.b.c')
('a', 'b.c')
>>> _resolve_subkeys('d|e|f', separator='|')
... | f7b749a0645a71048aaa3ffa693540c97772653a | 661,489 |
import math
def gcd(x, y):
"""
gcd :: Integral a => a -> a -> a
gcd(x,y) is the non-negative factor of both x and y of which every common
factor of x and y is also a factor; for example gcd(4,2) = 2, gcd(-4,6) =
2, gcd(0,4) = 4. gcd(0,0) = 0. (That is, the common divisor that is
"greatest" in... | a3d3e9947ca96de93712efd574a17ee62db59844 | 661,490 |
import re
def problem1(searchstring):
"""
Match phone numbers.
:param searchstring: string
:return: True or False
"""
str_search = re.search(r'^(\S?\d+\W?)\W?(\d+)\-(\d+)',searchstring)
#str_search1 = re.search(r'^(\S\d+\W)(?=(\s|\d)\d+)',searchstring)
#print(str_search)
... | 3b2c2d8bf56516b796bc4757ccae10d35ef507cc | 661,491 |
def rank_as_string(list1, alphanum_index):
"""
Convert a ranked list of items into a string of characters
based on a given dictionary `alph` of the format that contains
the ranked items and a random alphanumeric to represent it.
Parameters
----------
list1 : list
A lis... | c3de9118abe5ead47e9e84e1682b9a16ead0b5fc | 661,495 |
def _get_date_from_filename(filename):
""" Returns date (first part of filename) """
return filename.split("/")[-1].split("_")[0] | 9dd84ef278fbbe48a421a5b708bb09200ef93912 | 661,496 |
def get_n_params(model):
"""
Returns the number of learning parameters of the model
"""
pp=0
for p in list(model.parameters()):
nn=1
for s in list(p.size()):
nn = nn*s
pp += nn
return pp | c8d160293a2870d3550c5e5f9a56e5005fe50ba1 | 661,502 |
def get_instances(ClassName, arguments, attributes):
"""Get instances of a class with specific attributes
Assumes ClassName is a class type
Assumes arguments is an ordered collection of dictionaries as defined
in the module documentation
Assumes attributes is a list of dictionaries that maps stri... | 0d3a554e4b0f7150905ef45e700ceb656cdfeae5 | 661,508 |
def _remove_field(metadata, field):
"""Remove a certain field from the metadata
Args:
metadata (dict): Metadata to be pruned
field ([string]): Coordinates of fields to be removed
"""
if len(field) == 1:
if field[0] in metadata:
del metadata[field[0]]
else:
... | eaba71615053e3a70b242d1fe60e404aa68da527 | 661,509 |
import math
def is_pentagon(x):
"""
Checks if x is a pentagon number
"""
n = (1 + math.sqrt(24*x + 1))/6
return(n == round(n)) | d765b841a4790371d2eb07bcb30bd13c5e5d344a | 661,512 |
def compute_user_vector_with_threshold(array, threshold=3.5):
"""Compute a user profile by summing only vectors from items with a
positive review.
Item vectors with a rating above a set threshold are included, other
vectors are discarded. The user profile is not normalized.
Args:
array (rdd ob... | 9bfe7bb6be20884f18b6a0995a6d1b46abd0757c | 661,513 |
import math
def two_divider(num):
"""Solution to exercise P-1.30.
Write a Python program that can take a positive integer greater than 2
as input and write out the number of times one must repeatedly divide
this number by 2 before getting a value less than 2.
"""
if not isinstance(num, int) o... | 2bc6cdf305d2ed423e9bab0a5011dbb8a6c9efd1 | 661,517 |
import re
from datetime import datetime
def is_valid_timestamp(timestamp):
"""Checks whether timestamp is a string that is a proper ISO 8601 timestamp
Format for string is is YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]]
e.g. 2008-01-23T19:23:10+00:00
Parameters:
timesta... | c3fdb1cb1dfe069e8e4a69557ce7b2e85d2a843c | 661,518 |
def feasible(growth_rate):
"""Feasibility function for the individual. Returns True if feasible False
otherwise."""
if growth_rate > 1e-6:
return True
return False | 466635645a67a84a64e4dcc03f0dc66c1fea218b | 661,519 |
def is_kind_of_class(obj, a_class):
"""checks if an object is an instance of, or if the object is an instance
of a class that inherited from, the specified class"""
return (isinstance(obj, a_class) or issubclass(type(obj), a_class)) | 8eb04c13c1f8776aed8bd3bdc3e3c4764d090dc2 | 661,524 |
def str_list_to_dict(pairs_list):
"""
Parses strings from list formatted as 'k1=v1' to dict with keys 'k1', 'v1'.
Example: str_list_to_dict(['k=v', 'a=b']) —> {'k':'v', 'a': 'b'}
:param pairs_list: list of strings
:return: dict with parsed keys/values
"""
result = {}
for l in pairs_list:... | 3ace4d8d85258000cba67fe2417cf605158def00 | 661,525 |
def get_auth_type_from_header(header):
"""
Given a WWW-Authenticate or Proxy-Authenticate header, returns the
authentication type to use. We prefer NTLM over Negotiate if the server
suppports it.
"""
if "ntlm" in header.lower():
return "NTLM"
elif "negotiate" in header.lower():
... | 069aa3a04e9c6128f18b1c59c81e0abe469f0c45 | 661,526 |
def _get_number_of_warmup_and_kept_draws_from_fit(fit):
"""Get number of warmup draws and kept draws."""
if 'warmup2' not in fit:
n_warmup = 0
n_draws = fit['n_save'][0]
else:
n_warmup = fit['warmup2'][0]
n_draws = fit['n_save'][0] - fit['warmup2'][0]
return n_warmup, n... | e1928cd5eb6eb47d1d1347ebf05f65434fb1336c | 661,531 |
import ast
def get_all_names(tree):
"""
Collect all identifier names from ast tree
:param tree: _ast.Module
:return: list
"""
return [node.id for node in ast.walk(tree) if isinstance(node, ast.Name)] | 643c6032c93c5ac562ba081bff4aabecc99febba | 661,532 |
from typing import List
from typing import Dict
import functools
def merge_list_of_dicts(list_of_dicts: List[Dict]) -> Dict:
"""A list of dictionaries is merged into one dictionary.
Parameters
----------
list_of_dicts: List[Dict]
Returns
-------
Dict
"""
if not list_of_dicts:
... | 81a05a7b16a4fa09d621e092fb525736811c63c9 | 661,533 |
from typing import Dict
import json
def load_user(filename: str) -> Dict:
"""Load json file with Discord userid and corresponding wellcome message
Args:
filename (str): filename of a json file
Returns:
Dict: {userid: text, date}
"""
with open(filename, 'r', encoding='utf-8') as f... | 69e5b05f09a1be58437f13bc150e102b7e41391f | 661,534 |
import string
def find_words(text):
"""
text: string
Returns a list of words from input text
"""
text = text.replace("\n", " ")
for char in string.punctuation:
text = text.replace(char, "")
words = text.split(" ")
return words | 86c2691b9f0e57e758f7bc2d5b8fa51adcc1ebc0 | 661,537 |
def hexdump(data: bytes) -> None:
"""
https://code.activestate.com/recipes/579064-hex-dump/
>>> hexdump(b'\x7f\x7f\x7f\x7f\x7f') #doctest: +NORMALIZE_WHITESPACE
0000000000: 7F 7F 7F 7F 7F .....
"""
def _pack(a):
"""
['7F', '7F', '7F', '7F', '7... | d0dab2898522292847b0b24a49fa23edb8ccdfb4 | 661,539 |
def get_note_head(note_path):
"""
Return first line of a text file
Parameters
----------
note_path : str
A text file path
Returns
-------
str
First line of the text file
"""
with open(note_path, "r") as f:
head = f.read()
return head | 987038ba80b0fdae7f209b172ed2daaf287ee19a | 661,546 |
def MassFlowProperty(self):
"""Mass flow (kg/hr)."""
return self.mol[self.index] * self.MW | 4d8000cc8c1b2876c9e07bc9799c0318e16f996b | 661,548 |
def encode_db_connstr(name, # pylint: disable=too-many-arguments
host='127.0.0.1',
port=5432,
user='postgres',
password='password',
scheme='postgresql'):
""" builds a database connection string """
con... | 5db05ad434f429714183da8d3d1c1ed058f1bff7 | 661,549 |
import copy
def override_config(config, kwargs):
""" Helper function to override the 'config' with the options present in 'kwargs'. """
config = copy.deepcopy(config)
for k, v in kwargs.items():
if k not in config.keys():
print('WARNING: Overriding non-existent kwargs key', k)
... | 42c3dce04fdf5d501ecdd1026cd7a75036bfca32 | 661,550 |
from typing import Counter
def system_call_count_feats(tree):
"""
arguments:
tree is an xml.etree.ElementTree object
returns:
a dictionary mapping 'num_system_calls' to the number of system_calls
made by an executable (summed over all processes)
"""
c = Counter()
in_all_secti... | 15f2e8cb7ce46a84732e2641b10c0e1bf9e4d0b2 | 661,551 |
def create_marker_and_content(genome_property_flat_file_line):
"""
Splits a list of lines from a genome property file into marker, content pairs.
:param genome_property_flat_file_line: A line from a genome property flat file line.
:return: A tuple containing a marker, content pair.
"""
columns ... | 6084f8c3ea752d8e6901a3bd043a990da4193f19 | 661,553 |
def init_model_nn(model, params):
"""
## Description:
It initializes the model parameters of the received model
## Args
`model`: (Pytorch Model)
The model to be initialized
`params`: (dict)
Parameters used to initialize the model
## Returns:
The initialized model
"""
... | 46b1c51227a8cb07e8cb5456807459d1670e67a7 | 661,554 |
import pickle
def load_config(filename):
"""Loads in configuration file.
Args:
filename (string): The filename of the config file.
Returns:
object: A deserialised pickle object.
"""
with open(filename, 'rb') as file_ptr:
return pickle.load(file_ptr) | 1264149e7d6065ec7772818835d092415e9d52bc | 661,555 |
def _get_or_create_main_genre_node(main_genre_name, taxonomy_graph):
"""
Return the node for the main genre if it exists, otherwise create a new node and
make it a child of the root node.
"""
if main_genre_name in taxonomy_graph:
main_genre_node = taxonomy_graph.get_node(main_genre_name)
... | b3f999de588c6eef82290543b56b2b48e25230eb | 661,556 |
def format_time(time_):
""" Returns a formatted time string in the Orders of magnitude (time)
Args:
time_: if -1.0 return 'NOT-MEASURED''
Returns:
str: formatted time: Orders of magnitude (time)
second (s)
millisecond (ms) One thousandth of one second
micros... | 0afd2d093a29ac446df1ed5f73ca110a52ee4e54 | 661,558 |
from datetime import datetime
def default(obj):
"""Encode datetime to string in YYYY-MM-DDTHH:MM:SS format (RFC3339)"""
if isinstance(obj, datetime):
return obj.isoformat()
return obj | 69ef19bf42e411fcc753214eb839d5de044e7d8f | 661,560 |
import hashlib
def is_placeholder_image(img_data):
"""
Checks for the placeholder image. If an imgur url is not valid (such as
http//i.imgur.com/12345.jpg), imgur returns a blank placeholder image.
@param: img_data (bytes) - bytes representing the image.
@return: (boolean) True if placeholder image otherwise... | 59d92b6cbde9e72d6de19a300ce90f684cf6ca69 | 661,562 |
def list_to_lower(string_list):
"""
Convert every string in a list to lower case.
@param string_list: list of strings to convert
@type string_list: list (of basestring)
@rtype: list (of basestring)
"""
return [s.lower() for s in string_list] | 35097ddb6a665c50851bf6c98b60e9de88fb147b | 661,563 |
def is_handler_authentication_exempt(handler):
"""Return True if the endpoint handler is authentication exempt."""
try:
is_unauthenticated = handler.__caldera_unauthenticated__
except AttributeError:
is_unauthenticated = False
return is_unauthenticated | cbc5871084a961ada0225bdb5ee58eb2e6cce8bd | 661,567 |
import requests
def live_data(key):
"""
Requests latest covid-19 stats from rapidapi using requests.
Parameters
----------
key: rapidapi key
Returns
-------
response: A dictionary containing data in json format.
"""
# https://rapidapi.com/astsiatsko/api/coronavirus-monitor
... | c7905e39e3040d824c38e681ac4bf09ca1cb24fb | 661,569 |
import textwrap
def pike_tmp_package(pike_init_py):
"""Fixture: Create a Python package inside a temporary directory.
Depends on the pike_init_py fixture
:param pike_init_py: fixture with py.path.local object pointing to
directory with empty __init__.py
:return: t... | 28c30c4ce36a9e5ec745765a42712f49a334d98d | 661,570 |
def normalize_min_max(x, min_val=None, max_val=None):
"""
normalize vector / matrix to [0, 1].
:param x: a numpy array.
:param min_val: the minimum value in normalization. if not provided, takes x.min()
:param max_val: the maximum value in normalization. if not provided, takes x.max()
:return:
... | 4e4c9d24e48b214a7af725b17e0175a88e95c0ce | 661,571 |
def _get_nn_idx(row, neigh, radius, columns):
"""Retrieve the NN of a sample within a specified radius.
Parameters
----------
row : pd.Series
neigh : sklearn.NearestNeighbors
radius : float
columns : list
Returns
-------
list
Nearest Neighbors of given sample within rad... | 2fa5cbaa3a8d7d91e8c69b892dc26a3b42dcda66 | 661,575 |
def mdot(matrix, benchmark_information):
"""
Calculates a product between a matrix / matrices with shape (n1) or (a, n1) and a weight list with shape (b, n2)
or (n2,), where n1 and n2 do not have to be the same
"""
n1 = matrix.shape[-1]
weights_t = benchmark_information.T
n2 = weights_t.sha... | 0c3136d021ba65de173f891231838eb62bd255f9 | 661,578 |
def number_to_name(number):
"""
Converts an integer called number to a string.
Otherwise, it sends an error message letting you know that
an invalid choice was made.
"""
if number == 0:
return "rock"
elif number == 1:
return "Spock"
elif number == 2:
return "pap... | d711634578b8d67475044f8b24589944c81a16ca | 661,581 |
def makeSiblingTemplatesList(templates, new_template_file,
default_template=None):
"""Converts template paths into a list of "sibling" templates.
Args:
templates: search list of templates (or just a single template not in a
list) from which template paths will be extracted ... | a0cd622aba15305c8bfb47ebb9cfab71f757b585 | 661,589 |
import re
def n_credit(sentence):
"""
If a phrase in the form "X credit" appears in the sentence, and
X is a number, add a hyphen to "credit".
If "X-credit" appears, split it into "X" and "-credit".
Do not hyphenate "X credits" or "Y credit" where Y is not a number.
Run this after the tokenize... | 240743aa1a653ab8c50e505c28333964e1e85dc7 | 661,591 |
def _convert_dict_to_list(d):
"""This is to convert a Python dictionary to a list, where
each list item is a dict with `name` and `value` keys.
"""
if not isinstance(d, dict):
raise TypeError("The input parameter `d` is not a dict.")
env_list = []
for k, v in d.items():
env_list... | 0eef0f65bda3a40a0538742f9a286b3d020c0862 | 661,594 |
def readrecipe(recipebook, index):
"""
Returns one recipe, for command line output
"""
try:
return recipebook.recipes[index].prettyprint()
except IndexError:
return "Error: no such recipe" | 32b46f34b152a05104c59ff8c95be7ad23abeff7 | 661,595 |
from typing import Sequence
from typing import Any
from typing import Optional
def binary_search_iter(seq: Sequence, value: Any) -> Optional[int]:
"""
Iterative binary search.
Notes
-----
Binary search works only on sorted sequences.
Parameters
----------
seq : Sequence
where... | a882a30aa8c8c5a55e2adf43234302da6ab6266c | 661,596 |
import csv
def csv_readline_to_list(csv_file):
"""
Read the CSV content by line.
Example:
csv content:
|name|age|
| a |21 |
| b |22 |
| c |23 |
| d |24 |
| e |25 |
ret = csv_readline_to_list("d/demo.csv")
Ret... | 7e6359df416174eb501868845edfbbcb5fe00e57 | 661,598 |
def append_instr(qobj, exp_index, instruction):
"""Append a QasmQobjInstruction to a QobjExperiment.
Args:
qobj (Qobj): a Qobj object.
exp_index (int): The index of the experiment in the qobj.
instruction (QasmQobjInstruction): instruction to insert.
"""
qobj.experiments[exp_ind... | 87f341e9f378a9e79321ae1d34416087c2b38593 | 661,601 |
def cols_to_string_with_dubquotes(cols, backslash=False):
"""
Gets a string representation of a list of strings, using double quotes.
Useful for converting list of columns to a string for use in a query.
Backslashes are possible if the query will be passed as a string argument to (for instance) Shuttle... | aadf71c8c419466a3dbaa388baa17cba88f32aad | 661,602 |
def get_shock_sds_index_tuples(periods, factors):
"""Index tuples for shock_sd.
Args:
periods (list): The periods of the model.
factors (list): The latent factors of the model.
Returns:
ind_tups (list)
"""
ind_tups = []
for period in periods[:-1]:
for factor in... | bb249a0b885da103a7ec608807b0d8689dd5930f | 661,606 |
def applymap_numeric_columns(df, func):
"""Map a function elementwise to numeric columns.
All other columns are returned unchanged.
"""
columns = df._get_numeric_data().columns
df[columns] = df[columns].applymap(func)
return df | 08998e64f20f0433e13382d742d50e92fc846d2a | 661,608 |
def subs(text, subst):
"""Based on substitution dict, replace letters in text by their subst
First converts to lower case. Every non-letter is left intact"""
text = text.lower()
return ''.join([subst[l] if l in subst else l for l in text]) | 3d150c2e955166e03ed886b71d213a234ff67010 | 661,612 |
def transform_pos(word_pos):
"""Map POS tag to first character lemmatize() accepts"""
if word_pos == 'Noun':
return 'n'
elif word_pos == 'Verb':
return 'v'
elif word_pos == 'Adjective':
return 'a'
elif word_pos == '':
return '' | 3f871b679392c09e65bed90c425656050a599512 | 661,619 |
def longest_common_prefix(items1, items2):
"""
Return the longest common prefix.
>>> longest_common_prefix("abcde", "abcxy")
'abc'
:rtype:
``type(items1)``
"""
n = 0
for x1, x2 in zip(items1, items2):
if x1 != x2:
break
n += 1
return items1[:n] | 4f4a3724e50e37a632f2f761828d5edcd8c79f00 | 661,621 |
def to_list(arr):
"""Transform an numpy array into a list with homogeneous element type."""
return arr.astype(type(arr.ravel()[0])).tolist() | 1773f2563533ebd76f9dd4acc8f446750f6e8a52 | 661,624 |
def fact(n):
"""Factorial. fact(5) = 5! = 5 * 4! = 5 * 4 * 3 * 2 * 1 = 120"""
if n == 1:
return 1
return n * fact(n - 1) | 8af471f8ef4aeb49606ce864400b968737c97597 | 661,629 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.