content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_first_key(dictionary, value): """Get first key in a dict for a given value. :param dict dictionary: :param string value: """ for key, val in dictionary.items(): if val == value: return key return None
635792f6188529d1246419dc54172e6c54add006
604,259
from typing import List from typing import Tuple import re def get_subphrases(line: str) -> List[Tuple[str, str]]: """ Given a ground truth transcription, extracts all subphrases. A subphrase is defined as a set of words with a single timestamp. In our ground truth file, it is possible for a single line to con...
de28255ebc012c144a49e7482bee5b721069c9e3
604,261
import requests import json def get_quote(url, cat = None): """ :param url: the base url for the API :param cat: Category of the quote requested. :return: Dict of the responce form the API """ if cat == None: responce = requests.get(url).content else: payload = {"category":...
d3a1f2d2311970c6e9400c58669b01a92238509d
604,265
from glob import glob def get_subjectdcmdir(subjid, dcm_template): """Return the TrioTim directory for each subject Assumes that this directory is inside the subjects directory """ dirlist = glob(dcm_template%subjid) if not dirlist: raise IOError('Directory %s does not exist'%(dcm_templat...
f07d31216d5d978a1f4f4ab46a9dcbb65b6d3447
604,267
import json def read_runtime_stats(stats_filepath): """Read from a file runtime statistics used for generating spans.""" with open(stats_filepath) as json_file: return json.load(json_file)
58fccd7461ac416b9d527eb7a8beb3cd3985272f
604,269
import hashlib import base64 def sha512t24u(blob): """generate a base64url-encode, truncated SHA-512 digest for given binary data The sha512t24u digest is a convention for constructing and formatting digests for use as object identifiers. Specifically:: * generate a SHA512 digest on binary d...
0024d0d9ebdfeb7edaf45b472bd8d7a6623b62ae
604,272
def get_fileobject(title, objtype): """ Returns the id of the object if it exists, otherwise returns False. Arguments: title -- The filename to be queried. objtype -- Image, Document from Wagtail. Returns: False if the object does not exist in this environment, object's integer ID ...
d8aaf7e9a35d4b13bd5397d70abc568d00deec5f
604,273
def get_term(value, level, goal_type, shape): """Get treatment plan utility term value. Parameters ---------- value : float Clinical goal value. level : float Clinical goal AcceptanceLevel. goal_type : str Clinical goal type (e.g., 'MaxDose') shape : {'linear', 'line...
cf9e4db9f404b63846ff5d2890af2c47e4dba74e
604,274
def rename(funcname): """Renames a function to take on the new :funcname:. Modifies __name__ and __qualname__. Use as a decorator: >>> @rename('bob') ... def janet(): ... pass >>> janet.__name__ 'bob' """ def _rename(func): func.__name__ = funcname loc = func.__qualn...
56ce8c9659638c57d1a3f7d1373b594f5d0fc951
604,276
def selected(value, target): """Return 'selected' if `value` equals `target`.""" if value == target: return 'selected' return ''
025a85645a868a465c66cc53824ad71be8d661ec
604,280
def dist2(p1,p2): """Square of the distance between p1 and p2""" return (p1.x-p2.x)**2 + (p1.y-p2.y)**2 + (p1.z-p2.z)**2
94dbef27019795f1621eddd4e7f86e7f34ea81ec
604,286
from bs4 import BeautifulSoup import requests def get_total_game_count(url: str) -> int: """ Supply url to scrape, returns number of games with achievements. :param url: - The url to scape from. :return: - Total number of games with achievements. """ soup = BeautifulSoup(requests.get(url).text...
4fa1383aa1692bfab5bf0b89f00cd6bfe3d4a32a
604,287
def enum(**enums): """ Defines ENUM type. | Usage: | enum(name1=value1, name2=value2) """ return type('Enum', (), enums)
22f35af94ec65d8272916b6371eaa4aa4a233bf2
604,299
def taputil_find_header(headers, key): """Searches for the specified keyword Parameters ---------- headers : HTTP(s) headers object, mandatory HTTP(s) response headers key : str, mandatory header key to be searched for Returns ------- The requested header value or None ...
667a232d6a87d578234b22189d15c0211a3448b0
604,300
def locations_of_substring(string, substring): """Return a list of locations of a substring.""" substring_length = len(substring) def recurse(locations_found, start): location = string.find(substring, start) if location != -1: return recurse(locations_found + [location], loc...
e276de58aceb3a84f19773d4ec0b37be948ee5c3
604,304
import ipaddress def get_prefix_with_offset(base, offset): """Compute prefix from base prefix plus offset. >>> get_prefix_with_offset(ipaddress.ip_network("10.0.0.0/16"), 0) IPv4Network('10.0.0.0/16') >>> get_prefix_with_offset(ipaddress.ip_network("10.0.0.0/16"), 3) IPv4Network('10.3.0.0/16') ...
b781ba077068a101311ed5b3ae461bccf1bca35f
604,308
def _path_to_target(package, path): """ Converts a path to a Bazel target. """ return "@{package}//:{path}".format(package = package, path = path)
d7fcc55f3758112320a8e1b8b3e2c4980c1a5982
604,312
def login_not_required(view_func): """ Decorator for views that marks that the view is accessible by unauthenticated users. """ view_func.login_required = False return view_func
829725447240e891e7d1007da0ddb47e3d275ae9
604,318
def calcK(bw, N, srate): """Calculate K for a given bandwidth, length, and sampling rate. bw = 2p * fr, where fr = srate / N (frequency resolution). p specifies the half bandwidth in bins (fr units). K = 2p - 1""" K = int(bw * float(N) / srate + .5) - 1 if K < 1: K = 1 return K
2a3aba2368b3bea6bb30c7430d6462229373e3bc
604,319
import re def substitute_repeats_fixed_len(text, nchars, ntimes=3): """ Find substrings that consist of `nchars` non-space characters and that are repeated at least `ntimes` consecutive times, and replace them with a single occurrence. Examples: abbcccddddeeeee -> abc...
a26e3611321ca45b58b3f1383e2fb7a33239f689
604,320
import re import string def clean_text(text: str) -> str: """Realiza a limpeza do texto passando para o formato minúsculo e removendo caracteres indesejados. Args: text (str): texto a ser limpo Returns: str: texto limpo """ text = text.lower() text = re.sub('[%s]' % r...
b21ea5b41b8fd423dbcda1fdcca9b3f8923f4fd7
604,323
def convert24(time, meridiem): """Convert hour to 24 hour format Arguments: time {list} -- Array of Hour, Minute meridiem {str} -- String of meridiem Returns: int -- 24 Hour format of hour """ if meridiem == 'am' and time[0] == '12': return 0 elif meridiem == '...
9b65966c93abedb4c5c9a286ee37d2bc72331da9
604,324
def latest (scores): """ :param scores - list of high scores :return: int - the last added score from the list """ return scores[-1]
cd83ff9e4ecf94cfe08c7f6bcd69438fb36043b4
604,330
def _no_schultz_repetition(contour, allow_unflagged=False): """ Step 10. If all values are flagged and no more than one repetition of values exists, excluding the first and last values, returns True. >>> contour_with_extrema = [ ... [1, {-1, 1}], ... [0, {-1}], ... [2, {1}], ... [0, {-1}], ... [2, {1}], ...
6adb05915d69c7cab93106ced495b2817afe6bf5
604,336
from typing import List def join_list(_list: List, separator: str = ", ", end_separator: str = " and ") -> str: """Joins elements in a list, using a different separator for the last item. :param _list: The list to join. :param separator: The string that will separate the items. :param end_separator: ...
cd6e6e08ab771b48347dec3655c824dba93b37c4
604,337
import click def validate_role(context, param, value): """ Validates existance of role. Fetches the role by name, returning it if it exists; otherwise throws BadParameter """ role = context.obj.api.role_by_name(value) if role: return role else: raise click.BadParameter("\"%...
0e0909727e069262362ff7cf20e1f192fb12ccf0
604,338
def importAny(*modules): """ Import by name, providing multiple alternative names Common use case: Support all the different package names found between 2.0 add-ons, 2.1 AnkiWeb releases, and 2.1 dev releases Raises: ImportError -- Module not found Returns: module -- I...
e688763afb48fb5ac2fb02bdad41b383b1f6048c
604,339
def split_query_string(query_string): """ Splits a query string into a dictionary >>> split_query_string('a=1&b=2&name=abc&y=&z=ab23') {'a': '1', 'y': '', 'b': '2', 'name': 'abc', 'z': 'ab23'} """ qs_dict = {} qs_parts = query_string.split('&') for qs_part in qs_parts: k,v = q...
ce53938a00d0771060b7dd4c19ac8d260e65a127
604,341
import math def find_pythag_triplet_optimized(s=1000): """ Find the Pythagorean triplet (a, b, c) that satisfies a + b + c = s :param s: a + b + c :return: (a * b * c, (a, b, c)) """ s2 = s // 2 lim = math.ceil(math.sqrt(s2)) - 1 for m in range(2, lim + 1): if s2 % m == 0: ...
d2072759fecb770210a8b715e1c96c922326689e
604,342
def dup_degree(f): """Returns leading degree of `f` in `K[x]`. """ return len(f) - 1
04ee26e6d02d5df7ce42083b289be69674bfd597
604,352
def featurize_holidays(history, holidays_df): """Function to obtain holiday features as dummy variables to use as external regressors. Parameters ---------- history: pd dataframe to get holiday features for holidays_df: pd dataframe containing dt and holiday columns to featurize ...
5432ee2aae3b4323a611ca163011e5e57b659ce3
604,355
def fill_list_article_object(article_id, title, site, updated, cover_url, is_fav): """ list article object: { article_id: article_id, title: title, site: site_title, updated: YYYY-MM-DD, cover_url: url, may be None is_fav: is_fav, b...
64eafc9e527a7743f66a950a251959ed590c1a9f
604,356
def is_multiline(node): """ Checks if node is a multiline string """ if isinstance(node, list): return any(is_multiline(n) for n in node) for leaf in node.leaves(): if "\n" in leaf.prefix: return True return False
b4971d289f1d85cf88f159486c8dabfecc127b7f
604,363
import re def camel_string_to_snake(name): """ Convert a camelcase string to snakecase The camelcase string could be 'provisionIpAddress', after convert it could be 'provision_ip_address'. :param name: A camelcase string :type name: string :return: A snakecase string :rtype: string "...
e74221a6e4e434a88876e6f7fa2bb69f1e793834
604,365
def synset_to_wnid(synset): """ Converts synset to wnid. Synset is a wordnet node object""" return synset.offset()
ba68060b66ab6cd12edd7322ed091b4b5244112e
604,369
def get_matched_midi_md5(msd_id: str, msd_score_matches: dict): """ Returns the MD5 of the matched MIDI from its MSD id. :param msd_id: the MSD id :param msd_score_matches: the MSD score dict, use get_msd_score_matches :return: the matched MIDI MD5 """ max_score = 0 matched_midi_md5 = None for midi_m...
d9cc97763be12322131af9943e38faa694326d3a
604,371
import re def PHONOTACTIC(pattern): """Takes a string representing the regex pattern of a particular phonotactic restriction, and returns a function that will count the number of times that pattern occurs in an unparsed output string.""" def F(output): return len(re.findall(pattern, output...
44bb47602df700f4400d8abad4cc45424d42a35e
604,373
def get_forms(data): """Takes a JSON data object and returns a list of its forms""" to_return = [] forms = data.get('forms') if forms: for form in forms: form_value = form.get('form') if form_value != None: to_return.append(form_value) word = data.get(...
16596a877b77012e43588fe152dd9731a9dc867d
604,380
def nullHeuristic(state, problem=None): """ A example of heuristic function which estimates the cost from the current state to the nearest goal in the provided SearchProblem. This heuristic is trivial. You don't need to edit this function """ return 0
9d66e532763438b9272f65bac04ecc03138873d4
604,382
def sec2year(seconds): """ Convert seconds into decimal Julian years. Julian years have 365.25 days. Parameters: * seconds : float Time in seconds Returns: * years : float Time in years Example:: >>> print sec2year(31557600) 1.0 """ return ...
42faccaa8f3468ff911f8e0ec1acf9b19621701a
604,393
def ShortenMask(mask, size): """ Parameters ---------- mask : tuple tuple of n 1d array of size l coordonate of l points size : int size of the shortened mask Returns ------- shortened_mask : tuple tuple of n 1d array of size equal to the si...
b73033627d905e5cac6cfdfab3cd4dc5d187c802
604,396
def city_country(city, country): """Return a string like 'Santiago, Chile'.""" return f"{city.title()}, {country.title()}"
e6de0b132832651f166c4ba786ac0d044d63a2a3
604,399
import torch def pen_dual( embedding: torch.Tensor, param: torch.Tensor, device: torch.device ) -> torch.Tensor: """Computes the non-collapsing penalty for the dual formulation. In the dual formulation, when we project n points to low_dim dimensions, the model parameter 'param' is an n*low_dim ...
d8f677776f4a0a9a6f64d3ba87e476fea956be08
604,400
import requests def get_node_list(addr): """ Returns a list of available nodes. """ return requests.get(addr + '/status/nodes').json()
9c62cc34c090e19dd5ae1794c75d17aeba8c182e
604,404
def compare_method_names(name1, name2): """Return -1 if name1 < name2, 0 if name1 == name2 and 1 if name1 > name2""" if name1 < name2: return -1 else: return 1
2c1f6814365c26508e5eef2bae963057541a824e
604,407
import unittest import fnmatch def find_tests(entity, pattern): """ search for a unit tests with a matching wildcard pattern Looks for the first 'unittest.case.TestCase' instance where its identifier matches the provided wildcard pattern. Args: entity: the unit test entity to search for ...
f7075e2bbd23b707c791f4d90b61e7567b2dcb9e
604,408
def is_long_within_range(longitude: float) -> bool: """ Checks if a Longitude coordinate is within the acceptable range of -180.0 and 180.0 """ return (longitude >= -180.0) and (longitude <= 180.0)
6c0bf663599e39eb4fe7a92075c1af3c0052e2cc
604,409
def dict_union(*args): """ Generate union of dictionaries. This helper function is used to combine dictionaries of keyword arguments so that they can be passed to the string format method. Arguments: *args: zero or more container objects either representing a mapping of key-value ...
fff5026af97b15e797132c04c8b7f51a7fce77a2
604,413
import struct def _read_varlen_int(f): """Read a variable-length integer.""" nbytes = struct.unpack('B', f.read(1))[0] if nbytes == 1: return struct.unpack('B', f.read(1))[0] elif nbytes == 4: return struct.unpack('<I', f.read(4))[0] elif nbytes == 8: return struct.unpack('...
7dacf16edcb8a41d41beff00c6ab7daaa31ffa87
604,414
import jinja2 def create_main_protocol_hoc( template_path, protocol_definitions, rin_exp_voltage_base, mtype ): """Create main_protocol.hoc file. Args: template_path (str): path to the template to fill in protocol_definitions (dict): dictionary defining the protocols rin_exp_volta...
8374b01151f8e624f10f4ad2f2e9db7266e88bf1
604,415
def int_to_bytearray(value: int, num_byte: int) -> bytearray: """ Convert a long integer to a 'bytearray' object. Args: value: The long integer value to convert. num_byte: Number of bytes in the 'bytearray' object. Returns: The 'bytearray' object from long integer value. ""...
2a144d43801e13c40f14e32892ae4c3932ac4646
604,417
def neighbour_coordinates(grid, point_coords): """Returns list of coordinates for neighbours of the given point, within the bounds of the grid""" grid_width = len(grid[0]) grid_height = len(grid) point_row, point_col = point_coords neighbour_coords = [ (point_row, point_col - 1), ...
614e936c0992b734ec47c61405fda64b2a0ad348
604,418
from typing import Dict from typing import Any from typing import List def waveFuncToSeq(waveForm: Dict[str, Any], maxDt: int, dt: float) -> List[float]: """ Transform the callable waveform to sequences. :param waveForm: waveData. :param maxDt: duration in unit dt (arbitrary wave generator (AWG) samp...
e8dfd455cb0a3bc63d66fcb405902a1a3fec4b15
604,422
def reverse(in_list1: list) -> list: """ Reverse a list :param in_list1: The input list :return: the reversed version """ if len(in_list1) == 0: return [] _list = reverse(in_list1[1:]) return _list + [in_list1[0]]
843d75f55517035905bd11e7fcaa6e7351b16a0f
604,426
def add_bar_labels(plot, labels, text_color): """Draws text labels just above (below) bars in the plot for positive (negative) values. Args: plot: matplotlib.AxesSubplot object. labels: List of strings corresponding to bars in plot. text_color: matplotlib RGB color tuple. """ ...
b5c9366bec809c99c833679081f404d3103d06c0
604,434
import glob def find_files(model, ensemble, var_id): """ Finds files that correspond to the given arguments. :param model: (string) Model chosen as argument at command line. :param ensemble: (string) Ensemble chosen as argument at command line. :param var_id: (string) Variable chosen as argument ...
c3b4b5528f81bea086be849362acafa981a5647a
604,436
def count_digits (val): """ Counts the number of digits in a string. Args: val (str): The string to count digits in. Returns: int: The number of digits in the string. """ return sum(1 for c in val if c.isdigit())
4cf99f0d5df18bee81ef0e50438d672a92c29367
604,439
def dont_give_me_five(start: int, end: int) -> int: """This function returns the count of all numbers except numbers with a 5.""" count = 0 for item in range(start, end+1): if '5' not in str(item): #print (item) count += 1 return count
83d1fe6bebba342df608b51e2a59476c0978f0d2
604,440
def orangePurchase3(m,priceFunction): """ Calculate number of oranges that can be purchased for quantity of money m given the (user-defined) price function priceFunction for each orange. :param m:total amount of money available (nb m<2,147,483,647) :param priceFunction: points to a pricer funct...
0933634b3437ab2cc38edd87706e2ddd798d3643
604,446
def setup_registry(registry): """set up the given registry for use with pint_xarray Namely, it enables ``force_ndarray_like`` to make sure results are always duck arrays. Parameters ---------- registry : pint.UnitRegistry The registry to modify """ if not registry.force_ndarray...
1888eaece4a388307854251012ea75dc213ddd43
604,450
import types import asyncio async def apply_coroutine(func: types.FunctionType, *args, **kwargs) -> object: """ Call a function with the supplied arguments. If the result is a coroutine, await it. >>> async def foobar(): return 'hi' >>> async def async_foobar(): return 'hi' >>> await apply_co...
49361251ce5fab412a51787583c493e349f56ef5
604,452
def linspace(a, b, n=25): """Return N linearly distributed numbers between a and b.""" if n < 2: return b diff = (float(b) - a) / (n - 1) return [round(diff * i + a, 4) for i in range(n)]
61f3b92ceb87dae703a035413254bc53598faae3
604,455
def get_dat_from_filtered(dataset: str, datasets_filt: dict) -> str: """Return the dataset corresponding to the non-filtered version of the dataset. Parameters ---------- dataset : str Filtered dataset name datasets_filt : dict Mapping Filtered dataset name -> Raw dataset name ...
0dca30938e5ad32b3e5975ab4792b687469629d0
604,458
def add_uic_ref(shape, properties, fid, zoom): """ If the feature has a valid uic_ref tag (7 integers), then move it to its properties. """ tags = properties.get('tags') if not tags: return shape, properties, fid uic_ref = tags.get('uic_ref') if not uic_ref: return shap...
aac398f818c443f5e555f37924989b658864ff82
604,462
from typing import Callable from typing import Any from typing import Optional def find(items: list, predicate: Callable[[Any], bool]) -> Optional[Any]: """Find the first item in the list matching the predicate or returns `None` if no match is found.""" return next((item for item in items if predicate(ite...
e1d34a28f2b1a50758c2c040992d07417d027831
604,465
def get_bleeding_limbs(life): """Returns list of bleeding limbs.""" _bleeding = [] for limb in life['body']: if life['body'][limb]['bleeding']: _bleeding.append(limb) return _bleeding
30f47987a95b0eabd1d89ddcfc168295037413dd
604,466
from typing import Any from typing import Optional def to_code(node: Any) -> Optional[str]: """ Reconstruct code for the given node, and strip it of whitespace. Args: node (Any): An object representing a node of the Parso abstract syntax tree. Returns: str: The string representation ...
b4f361c7ba754d75d056884cc4ed33eeaa1d3c74
604,468
import io import base64 def send_bytes(writer, filename, mime_type=None, **kwargs): """ Convert data written to BytesIO into the format expected by the Download component. :param writer: a writer that can write to BytesIO :param filename: the name of the file :param mime_type: mime type of the fil...
4c497a0d43e58580d0f17840146b22825037ec24
604,469
def extract_port_num(arg): """Extract port number from command line argument.""" port = 0 try: port = int(arg) except ValueError: print("Invalid port number\n") return port
30265a91d39718fc890cc87fc4f20743773b0aba
604,471
def summation(n, term): """Sum the first N terms of a sequence. >>> summation(5, cube) 225 """ total, k = 0, 1 while k <= n: total, k = total + term(k), k + 1 return total
62afffc81316b695b39a53d183bbff80c8a6889f
604,472
def white_to_len(string, length): """ Fills white space into a string to get to an appropriate length. If the string is too long, it cuts it off. :param string: String to format. :param length: The desired length. :return: The final string. """ if len(string) < length: string = stri...
ef77b36d76ba43e6eaa51b9962da622e060fa029
604,473
def _cell_above_exists(column_index: int, rows: list) -> bool: """ Return True if the cell above the current cell exists. Keyword arguments: column_index -- the index of the column rows -- the rows to check """ return column_index < len(rows[len(rows) - 1])
bca10a5d765144a77e6cf9fe5c703b69f2fa71b8
604,479
import struct def read_unpack(fmt, f): """ calls struct.unpack with fmt reading bytes as necessary from f if struct.unpack only returns 1 value, the tuple is unpacked into a single return value """ size = struct.calcsize(fmt) tup = struct.unpack(fmt, f.read(size)) if len(tup) == 1: return tup[0] ...
165cfda0e792fd05d9916c2a127ca4fff844257a
604,490
import logging def identity(image): """Return the image as is.""" logging.info("identity({})".format(repr(image))) return image
a82c2d2b70d8c7de14568b3a34f503086f50c072
604,491
def get_single_value_from_xref_dic(xref_dic): """ If the given dictionary contains only one entry, get its value, independent of key. Args: xref_dic (dict): A nested dictionary of the form {'xref': {xref: ...
05a53906573f85d20be2b795e2cb545fb62676e6
604,493
def center_crop(x, size): """ Given a tensor x, crop the center most portion along the last dim such as to match the provdied size. Args: x (tensor): tensor to crop. size (int): desired output size of the last dimension. Returns x (tensor): cropped tensor. """ s ...
b265eedf85c5ad9d7c4972ed5e85848beaf59293
604,494
def get_annotations(o: object): """ Internal function to get the annotations of an object. Parameters ---------- o : object The object to get the annotations of. Returns ------- dict[str, Any] The annotations of the object. """ return o.__annotations__ if hasatt...
221bb08b655ac9b7183277f57ba4d4782aaef2fb
604,500
def vehicle_type_and_mav_sys_id(vehicle_id, vehicle_color): """Get the vehicle_type and mav_sys_id from the vehicle's id and color.""" # valid MAV_SYS_IDs 1 to 250 # the first 25 vehicles per team are iris # the second 25 vehicles per team are plane (delta_wing) vehicle_type = 'iris' if vehicle_id ...
0f2f415f4242f8586e46b542380c280989fb6ec1
604,502
def shorten_str(text: str, width: int = 30, suffix: str = "[...]") -> str: """Custom string shortening (`textwrap.shorten` collapses whitespace).""" if len(text) <= width: return text else: return text[: width - len(suffix)] + suffix
9b41b35222bdbdc528ab64aae05bb52851561ebb
604,503
def will_be_caught(layers, positions): """Check if you will be caught on any layer, based on initial positions.""" for depth, params in layers.items(): if (positions[depth] + depth) % params['range'] == 0: return True return False
79ab23f7d6529d8efd6399a99b47904a58fa61ee
604,508
def waterSolubility(T, wSP): """ waterSolubility(T, wSP) waterSolubility (ppm by wt) = 10**(A + B/T + C/T^2) Parameters T, temperature in Kelvin wSP, A=wSP[0], B=wSP[1], C=wSP[2] A, B, and C are regression coefficients Returns water solubility in ppm by weight at T ...
897cb4b4ba572342454f3d8d1e7b42642f4368e9
604,509
def intToBitString(a, bit = 256): """ Converts an integer to a binary string representation (without '0b') :param a: The integer to convert (integer) :param bit: The size of the representation in bit (integer) :return: Binary string representation (String) """ str = bin(a)[2:] return (bi...
288f9b77063ca23f544ae561780e47c9f5bac684
604,514
def humantime(seconds, ndigits=2, one_hour_digit=False): """Format a duration as a human readable string. The duration in seconds (a nonnegative float) is formatted as ``HH:MM:SS.frac``, where the number of fractional digits is controlled by `ndigits`; if `ndigits` is 0, the decimal point is not pr...
8d07d9120a7e6c6aec984c608fd8b1dd90608b44
604,517
def Ret_everyndays(DF,n): """ This function takes in the SnP data, calculates the returns every n days, returns a list""" df = DF.copy().drop('Return', axis = 1).iloc[::n, :] ret = df['Adj Close'].pct_change().to_list() return ret
0bb06e71907bf6f3d5beba30de101763fcbefbf8
604,519
def get_difference(num1, num2): """ Get difference between number one and number two. """ return num1 - num2
e0e450d19d3a421acd0514e28201688a57f00be2
604,521
import re def is_biosample_record(accession: str) -> bool: """ check whether the accession is a valid BioSamples accession :param accession: the accession to be checked :return: True when it is BioSamples accession """ if type(accession) is not str: raise TypeError("The method only tak...
8a46426e2c127d3bebf4cfcd4b6429a08271b325
604,523
def batch_size(value): """Check if batch size is a non-negative integer""" value = int(value) if value < 0: raise ValueError('Batch size must be positive, %s given' % value) return value
3dd7483c10f54e86fff42ac9713303c744febf81
604,530
import itertools def split_every(n, iterable): """Returns a generator that spits an iteratable into n-sized chunks. The last chunk may have less than n elements. See http://stackoverflow.com/a/22919323/503377.""" items = iter(iterable) return itertools.takewhile(bool, (list(itertools.islice(items...
de47464f0d0dba19540d7f1fc56ed7ce5c6e2c0b
604,532
import re def is_valid_url(url): """ Returns True if url is valid, else False. Accepted url examples are: "http://www.example.com:8000", "https://www.example.com", "www.example.com", "example.com" """ if not url: return False regex = re.compile( r'^(https?://)?' # option...
d5fd372e01d983e49cd13504955ad5e11fceb863
604,539
def create_filename(ticker, interval, mmyy): """ Create a filename based on a set of given parameter values. :param ticker: the ticker symbol :param interval: the time interval of the data :param mmyy: the date (in mmyy format) for which data is being fetched :return: filename string """ ...
8ed5f59dacfc381748b19be3bdea6f255308c6cb
604,546
def glyph_order(keys, draw_order=[]): """ Orders a set of glyph handles using regular sort and an explicit sort order. The explicit draw order must take the form of a list of glyph names while the keys should be glyph names with a custom suffix. The draw order may only match subset of the keys and a...
55fc43b58de23cc9dfde8fd452f97cad481c9679
604,549
def undecorate(name): """Undecorate a name by removing the leading Xr and making it lowercase.""" lower = name.lower() assert(lower.startswith('xr')) return lower[2:]
cf9791d6fee5218654a7665de82258163639e7cd
604,552
def split_location_string(location): """ Split location string into a list [Country, City] "United KingdomCambridge" -> ['United Kingdom', 'Cambridge'] """ for char_pos, char in enumerate(location): if char.isupper() and char_pos != 0: if location[char_pos - 1].islower(): ...
a088ae58e3359e9e2841011238e218cf47049222
604,560
def norm(type_=None, name=None): """ Function decorator for defining a norm :param type_: norm's type :param name: norm's name """ def decorator(func): func.norm = type_ func.name = name return func return decorator
9eeca52dcebf146b814434c03f35b78c25071bb9
604,561
import re def remove_xml_tags(string: str): """ Clean str of all XML tags or \\n \\t \\r etc ... :param string: String to clean """ spacing = "\n|\t|\r" return re.sub("<[^<]*?/?>|" + spacing, "", string)
e10160a8e55d18533c067e9203749502db4db588
604,562
import six import json def json_ast_format(ast): """Returns the given JSON AST formatted as bytes :param ast: JSON AST :returns: formatted JSON :rtype: bytes """ return six.b( json.dumps(ast, sort_keys=True, indent=2, separators...
7ae43b9a12963699e8fa77d0c0b2d5f9b2801143
604,568
def traverse_to_dict(data, path, delimiter='/'): """ Returns the dictionary at the end of the path defined by `path` :param data: A dict with the contents of the json file :param path: A string defining the path with or without leading and trailing slashes :param delimiter: The delimiter to con...
577d933bbe55ed3ef7adab353d66c5981bc55d51
604,574
def convert_rain_code(rain_code): """ Convert rain code into the following code SKY Code: refer to weather station API document 0: No rain 1: Rainy 2: Rainy and Snowy 3: Snowy Weather Code: Own implementation 1: sunny (not handled by this function) 2: ra...
07645d4ea44e2547488c02e5c2073b63770f35c6
604,575
def decode_present_weather(obj, variable=None, decoded_name=None): """ This function is to decode codes reported from automatic weather stations suchas the PWD22. This is based on WMO Table 4680. Parameters ---------- obj : ACT Dataset ACT or xarray dataset from which to convert codes ...
22213fe62b6293df36059fa96fa9dc368d4582f1
604,578
def calculate_mean(numbers): """Calculates the mean of a list of numbers Parameters ---------- numbers: iterable[numbers] Returns ------- number """ return sum(numbers) / len(numbers)
919ac8abf38f5469e422fe8720b61189a23d19d5
604,579