content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def days_of_inventory_on_hand(number_of_days, inventory_turnover): """Computes days of inventory on hand. Parameters ---------- number_of_days : int or float Number of days in period inventory_turnover : int or float Inventory_turnover Returns ------- out : int or float...
14afedbf7e687ebe7bfacffa62677252e43d4319
633,459
def mostrar_estados(estado): """ dependiendo el estado que tenga la notificacion, mostramos el texto del mismo, con diferentes colores """ if estado == 1: return '<span class="label label-default">Nuevo</span>' elif estado == 2: return '<span class="label label-success">Aceptado<...
ffc2edb1d83be8b9f60477c05156edff46a2860f
633,460
def parse_state_setup(setup): """Parse state setup to name, and tuples with parameters for step.""" split = [part.split() for part in setup.split('\n')] name = split[0][-1][0] if_zero = ( [param[-1][:-1] if param[-1][:-1].isalpha() else int(param[-1][0]) for param in split[2:5]]) if...
05ed73c52097c07ce9dc671bbbf0e5e7b18a1635
633,461
def secant(f,x0,x1, TOL=0.001, NMAX=100): """ Takes a function f, start values [x0,x1], tolerance value(optional) TOL and max number of iterations(optional) NMAX and returns the root of the equation using the secant method. """ n=1 while n<=NMAX: x2 = x1 - f(x1)*((x1-x0)/(f(x1)-f(x0))) if x2-x1 < TOL: ret...
4d1bda112d6348b9a23c92eda39d99d16f3e4005
633,462
def read_evid_db(dat_content, BN): """ Returns a list of dictionaries. For each dictionary: Key: var_name Val: var_state """ # remove \n dat_content= [i[:-1] for i in dat_content] dat_db= [] # List of dictionaries. Each dictionary is a map of var_name to var_state var_lst= dat_con...
f324b890ab2b6016e6b1764876961465664e2b5f
633,463
def welcome(): """List all available api routes.""" return """Available Routes:<br> <br/> Dates and precipitation observations for last year of the measurement table<br/> /api/v1.0/precipitation<br/> <br/> List of stations from the Hawaii data<br/> /api/...
7825a3f72e16d7b94b0b826271d6820cc723d43a
633,464
import argparse def get_parser(): """Parse commandline.""" parser = argparse.ArgumentParser( prog='mlperf_logging.repo_checker', description='Sanity checks to make sure that package is github compliant.', ) parser.add_argument( 'folder', type=str, help='the fol...
f426fd0bb8827bd7f74f28845cac64e387e3f722
633,465
def j2getCart(plate): """If autoscheduled cart is present return that, else return current cart, or None if the plate is not plugged """ if plate.assignedCart is not None: return plate.assignedCart else: return plate.cartNumber
904016ed0649698c188f5a6dc254e44fa29575ab
633,466
def indent_text(indent, text): """Prepend the specified number of spaces to the specified text. Args: indent (int): the number of spaces to use as an indentation text (object): text to indent. lists will be converted into a newline-separated str with spaces prepended to each line ...
8ef7dd1f58ceb44f888b007274b27c48fd329861
633,467
def patch_program_data(program: bytes) -> bytes: """ Implement this function to return the patched program. This program should return 0 for all input files. :param data: The bytes of the source program. :return: The bytes of the patched program. """ prog_bytes_list = list(program) prog...
f5bbd484e7080c7cac7a08eebb32716a2140b7ba
633,468
from typing import List def calc_acc(pred_data: List[List[str]], gold_data: List[List[str]]): """Calculates the accuracy, precision and recall Args: pred_data (List[List[str]]): The output data from the model gold_data (List[List[str]]): The labeled data to compare with Returns: ...
df4622ce701a0427eb24ef0ce4a5b06f68641ca2
633,469
def factorial_recursion(n): """ Return the factorial of n using recursion. Parameters ---------- n : an integer of which the factorial is evaluated. Returns ------- result : The factorial of n. """ if n == 1: return 1 return factorial_recursion(n - ...
301f20efeee1011a66e184b19d2b51fd919d004c
633,470
import math def schwefel(X, Y): """ :param X: x location :param Y: y location :return: height at [X,Y] """ return 418.9829 * 2 - (X * math.sin(math.sqrt(abs(X))) + Y * math.sin(math.sqrt(abs(Y))))
04e4ed48f43c3e40e8d2fd1a156c9b2fc2b78fdc
633,471
def prep_querystring( get_params ): """ Makes querystring from params. Called by handle_bad_params() """ if get_params: querystring = '?%s' % get_params.urlencode() # get_params is a django QueryDict object, which has a urlencode() method! yay! else: querystring = '' return quer...
f72b91d4a61b1603e5927f7f23da31189ac9cad6
633,472
def fib_pair(n): """Returns the tuple (F(n), F(n+1)). Arguments: n {int} -- n'th fibonacci number """ if n == 0: return (0, 1) else: a, b = fib_pair(n // 2) c = a * (b * 2 - a) d = a * a + b * b if n % 2 == 0: return (c, d) els...
e9438f1905c313b0fdaa5819ef7bd2584bca88dc
633,473
import sh def __git_raw(*args): """ @return sh.RunningCommand Proxies the specified git command+args and returns it """ return sh.git(args)
774be7e8441c672cfa774eef6212b170a4052600
633,474
def is_prime_number(number): """ 判断数值是否为素数 :param number: :return: boolean """ if number <= 1: return False for i in range(2, number): if number % i == 0: return False return True
2f621a2851234b3ed20fefbcb7c02d1a79fb7a16
633,475
def tick_direction(*, x="inout", y="inout"): """Adjust the tick direction.""" return { "xtick.direction": x, "ytick.direction": y, }
a77c175d6898cccdf62286e131b9506e9cda5e30
633,476
def parse_bnd_pos(alt): """ Parses standard VCF BND ALT (e.g. N]1:1000]) into chrom, pos Parameters ---------- alt : str VCF-formatted BND ALT Returns ------- chrom : str pos : int """ alt = alt.strip('ATCGNRYSWKMBDHV') # Strip brackets separately, otherwise GL ...
00c3a4f680eaea91385244fec509c6ef0ab5eaf8
633,477
def union_of(lhs, rhs): """ Computes the union of two posting lists. """ i = 0 j = 0 answer = [] while (i < len(lhs) or j < len(rhs)): if (j == len(rhs) or (i < len(lhs) and lhs[i] < rhs[j])): answer.append(lhs[i]) i += 1 elif (i == len(lh...
960d3d4eb5badb8e55fdadf8dc40419a533dca00
633,478
def add_friendship(client, username): """Helper function to login""" ''' **** "query_string" is the key in arg passing in flask''' return client.post('/api/friendships/create', query_string={ 'username': username }, follow_redirects=True)
c385e7778a53a2fda395a4a21fb138f2eace7a23
633,479
import re def is_book(url): """Check if *url* hints a book. """ return url is None or re.match('https?://[^/]*books.google.com', url) is not None
69ae8ac85dc6edebdd92e3e06af2ab353b995394
633,480
def _get_item_properties(item, fields): """Return a tuple containing the item properties.""" row = [] for field in fields: row.append(item.get(field, '')) return tuple(row)
abb5d982808f968e0bb3b9f080973f91d004a5be
633,482
import re def no_yaml_char(s): """Check for characters which prevent the yaml syntax highlighter from being applied. For example [] and ? and ' """ return bool(re.match(r"^[a-zA-Z0-9()%|#\"/._,+\-=: {}<>]*$", s))
31b700e7c42d0944c8e787a0e0d129bf0a20c0b9
633,483
def _CheckForJSTest(input_api, output_api): """'js-test.js' is the past, 'testharness.js' is our glorious future""" jstest_re = input_api.re.compile(r'resources/js-test.js') def source_file_filter(path): return input_api.FilterSourceFile(path, files_to_check=[r'\.(html|js|php|pl|svg)$']) error...
33de782d831c92e6b3880c2e3fdf7e7070c9ab84
633,484
import torch def _mean_var(data: torch.Tensor, ratio: float = 0, **kwargs): """ Finds mean(x) + ratio * std(x) """ return max(data.min().item(), data.mean().item() + ratio * data.std().item() + 1e-8)
0404ee1ba654becefaacb9c80e7e15ab7f7e939f
633,485
def yaml_diff_config(yaml_diff_sample_path): """Return a list containing the key and the sample path for a different yaml config.""" return ["--config", yaml_diff_sample_path]
9c1aa2871b596e60ad77242e9f33adc455aedccc
633,486
import random import string def randomname(n): """ランダムな文字列を返す Args: n (int): 文字列長 Returns: (str): ランダムな文字列(n文字) """ return "".join(random.choices(string.ascii_letters, k=n))
1fa3be362fbfd03a6fb05dc20bdaf0e25a1ba536
633,487
def merge_distributions(distribution, new_distribution): """Adds up a new distribution structure to a map formatted distribution """ for value, instances in new_distribution.items(): if value not in distribution: distribution[value] = 0 distribution[value] += instances retur...
303911f9bdbae62d10ff116b76fa88eccc00349c
633,488
def gerundio(verb): """ >>> gerundio('cantar') 'cantando' >>> gerundio('volver') 'volviendo' >>> gerundio('abrir') 'abriendo' >>> gerundio('armar') 'armando' """ ending = verb[-2:] if ending == 'ar': return verb[:-2] + 'ando' elif ending == 'er' or ending == 'ir': return verb[:-2] + 'i...
178f30af0b7b60fa2cbebf91ba370484c352307f
633,489
import json import logging def dict_to_json(metrics, input_filepath): """ Outputs metrics dictionary as a JSON file with the same name (and directory) as the original csv file from the beginning of the pipeline. :param metrics: Dictionary of metrics :param input_filepath: The filepath of the inputted...
af786e04d94950c8f479bbd2c0a91d4b57441a29
633,490
def step(env, action, state): """ Implementation of "step" which uses the given action as an offset of the existing state. This function overloads the environment step method and should be used when actions-as-offsets are required for this particular environment. """ # if action == (0.0, 0.0...
71e8eb8b2e2f352869b0a9d7cf0c5be0574c5f2f
633,491
def zone_eval(Dx, Dy, data): """ gives back the formatted list of adjacent seats """ switch_list = [] for i in range(Dy[0], Dy[1] + 1): temp = [data[i][j] for j in range(Dx[0], Dx[1] + 1)] switch_list.append(temp) return switch_list
3e282d397af6a3518f69bedc9e986613f97c4174
633,492
import sys from typing import OrderedDict def dict_has_ordered_keys(obj): """Check if a given object is a dict that maintains insertion order. :param obj: the dict object to check :rtype: bool """ if sys.version_info >= (3, 7): # the Python 3.7 language spec says that dict must maintain i...
145fc27935afa6310424808fb0979377d2fc2bcc
633,493
def remove_zero_axis(df): """Removes axes where all values are zero""" df_r = df.loc[df.sum(axis=1) > 0, df.sum() > 0] return df_r
9ef4960084430274f02477ad6c42f3cf11634238
633,495
def det_ltri(ltri): """Lower triangular determinant""" det = ltri[0] * ltri[2] return det
3a0fdfa4cc05ea13f504b122462a7c83c94a36fb
633,498
def get_crowd_selection(selection_counts, delimiter='|', error=None): """ Figure out what the crowd actually selected :param selection_counts: output from get_crowd_selection_counts() :type selection_counts: dict :param delimiter: character to place between tied responses - response1|response2 ...
bff6498b53d7b464609d539e73c91a88e365e0ee
633,499
def square(x): """Returns the square of $x$, or $x^2$""" return x*x
2c0f81d05081d3f80ae5a07acd5f0171e7b070a3
633,500
def volume_type_delete(volume_type_id, **kwargs): """ delete the specified volume type """ url = "/types/{volume_type_id}".format(volume_type_id=volume_type_id) return url, {}
55f18c21fa10237d095236daf29826ce33d5f990
633,501
def format_symbolic_duration(symbolic_dur): """Create a string representation of the symbolic duration encoded in the dictionary `symbolic_dur`. Parameters ---------- symbolic_dur : dict Dictionary with keys 'type' and 'dots' Returns ------- str A string representation ...
4c3beb9fbe2e4ea1bf30d6b76f6b25d99530a2e6
633,502
from typing import Union def fibonacci_n_term(n: int) -> Union[int, NotImplementedError]: """Returns the nth fibonacci number""" if n < 0: return NotImplementedError('negative n is not implemented') sq_5 = 5**0.5 phi_pos = (1 + sq_5) / 2 return round(phi_pos**n / sq_5)
e31bbcfa14314ee1eb02cb95e69dbcbd737d5139
633,503
def vector(p1, p2): """ p1->p2ベクトルを返す Args: p1 (list[float, float, float]): ベクトルの起点座標 p2 (list[float, float, float]): ベクトルの終点座標 """ return (p2[0] - p1[0], p2[1] - p1[1], p2[2] - p1[2])
e4e0b5fb09fb8889091d6be74ee6ce3a028e8f68
633,504
def stringToInts(array): """ Takes an array, convets all potential ints Arguments: array -- list of items Returns: an array with all items as ints, and none ints removes """ returnArray = [] for item in array: # this is a simple for loop, python makes it easy to iterate over each item in a li...
3b0aace8fe5f13dafbb275bbe3cb70a5b84b8519
633,505
import re def isValid(text): """Return True if the given text is in context with the module or otherwise return False :param text: The input text to validate :return: Bool """ return bool(re.search(r'\bhow are you|wassup\b', text, re.IGNORECASE))
05647d8c9f3e529242c5d853fd03cdf32c827793
633,506
from typing import Any def add_tensors (t, t1) -> Any: """ Add two tensors. Args: t : t1 : (Generated by docly) """ return t + t1
1c3c71983d0846fe66f4ddb7bce1ebd24f03f83c
633,507
def auth_formatted(authors): """format the authors in intials. last name e.g. J. V. Vogelstein """ auths_format = [] for author in authors: names = author.split(", ") last = names[0] if last[0] == "{" and last[-1] == "}": last = last[1:-1] initials = [] ...
386dda08d75e0b8c4d4ee8a2f9352cc2d61463b2
633,508
def predict_data(predict_x, lr): """ 预测数据 :param predict_x: 准备预测的样本数据 :param lr: 模型 :return: """ predict_y = lr.predict(predict_x) return predict_y
cbf034d7a273323dc28193966ea77e4eb5e17bf7
633,509
def override_from(cfg, recipient, namespace="walt"): """override_from iterates over `cfg` and looks for respective keys in `recipient`. If a key exists, it's value is overridden on `cfg`""" for key, value in cfg.items(): if key.endswith("_list") or key.endswith("_map"): continue ...
3875af9a11205d66bc1c6a2336058d55e594d7b3
633,510
from typing import Callable from typing import Tuple def find_upper_and_lower_integral_upper_bound( get_integral_value: Callable[[float], Tuple[float, float]], target_value: float, min_upper_bound: float, max_upper_bound: float, ) -> Tuple[float, float]: """ This function finds approximate low...
b17d21e85e689fa5cbf1d8b301c3b83f6bbdda58
633,511
def select_element(c, i): """Given a collection and an integer "i", return the ith element of this collection """ print("Received collection value is %s" % str(c)) return c[i]
2ed1e3d906ff49df6bb0fec5a368e0c9562f73c1
633,512
def get_from_params(request, key): """Try to read a value named ``key`` from the GET parameters. """ return request.query.get(key)
22d6ad4ed7b26309fb21d240878d4a74ce882952
633,513
import sys def validate_input(args): """Validate the number of arguments is correct, and that they're working. Obviously, this is not super robust (no further input validation), but I'm not writing this to be anything more than a helpful quick and dirty script. """ if len(args) != 1: if sy...
82334ef44d5f6c0621f8ac56c364dd6f1cc33cff
633,514
def getdepcmd(distro): """returns None or proper cmd for collecting dependency package names""" cmd = None if any(distro.lower().startswith(d) for d in ["centos", "virtuozzo"]): cmd = ["rpm", "-q", "-a"] elif any(distro.lower().startswith(d) for d in ["debian", "ubuntu"]): cmd = [ ...
38b3530a2464231c934cd255050a11a6a0bad20c
633,515
def pixelwise_norm(x, eps: float=1e-8): """ Pixelwise feature vector normalization. :param x: input activations volume :param eps: small number for numerical stability :return: y => pixel normalized activations """ return x * x.pow(2).mean(dim=1, keepdim=True).add(eps).rsqrt()
de7447dee50467cc9a854470b94ddafaa2c92e0b
633,516
def describe_testcases(testcases): """ Describe all testcases from "import-testcases" """ # If we have a few, just return them all (often it's just one). if len(testcases) < 4: descriptions = [testcase['id'] for testcase in testcases] return ', '.join(descriptions) # If we have more than...
4d37ed53e60dc1bd92b6897ac358c9e6a67ddafe
633,517
def validate_full_term_is_acronym(data): """ Validate full term exists if is_acronym and is_acronym is not False """ full_term = data.data.full_term is_acronym = data.data.is_acronym if full_term and not is_acronym: return ('Please set is_acronym to true' ' or full_term to null'...
406e77adfdb022630545a698994719f817880497
633,518
def absolute_trick(bias, slope, predictor, current_value, learning_rate): """ y ~ bias + slope*predictor Performs increments wrt a given scalar """ predicted_value = bias + slope*predictor if current_value > predicted_value: slope += learning_rate*predictor bias += learning_rate...
dfffabddd940893f23c42b31bacb3a2d2ad1e872
633,520
import typing def spring_splitter_by_chunks(number_of_chunks: int, string_to_split: str) -> typing.List[str]: """ Splits string into a number of chunks specified :param number_of_chunks: number of chunks :param string_to_split: string_to_split :return: list of strings """ pieces = string_t...
6126c39f8fce2fd55fdcb313e546d81b386e9e51
633,521
def citation_metrics(publications): """ Return the h_index and total number of citations calculated from a list of publications. """ cite_counts = sorted([v['citations'] for v in publications], reverse=True) for j, k in enumerate(cite_counts): if j + 1 > k: return j, sum(cite...
240ecc9f8910d394de8b35ce0ad866348aff39d0
633,522
def xor_encode( bstring ): """一个简单编码:两次编码后与原值相同""" MASK = 0x55 ret = bytearray( bstring ) for i in range(len(ret)): ret[i] ^= MASK return ret
7c4f8da8f739d8b72c1739cdd7a2b1ac38c36bdc
633,523
def filhos(indice, dependency_filhos): """ Devolve os indices dos filhos do nó dado como input (indice) :param indice: indice de um nó :param dependency_filhos: lista com sublistas que contêm os indices dos filhos, ex: [[], [0, 4], [], [], [2, 3], [1, 6, 7], [], []] :return: Lista com os indices filhos do nó dado ...
910676b560bea23165c17e543c199105655b3067
633,524
import pathlib def get_file_path(file: str) -> pathlib.Path: """ Get path to passed in file. Example get_file_path(__file__) """ return pathlib.Path(file).parent.absolute()
1fd66872b5209de43f8e8896d88206ccbb574951
633,525
def respond_list(**kwargs): """Returns a response to `list`.""" bot = kwargs['bot'] message = kwargs['message'] game_ids = [str(g) for g, c, _ in bot.pollers if c == message.channel.id] msg = "I'm following: " + ', '.join(game_ids) return msg
b2131fb5b26c25b77f9474b0f34845eec999c476
633,526
import os def getListOfFiles(directory, extension): """ Load a list of all file names pointed in the directory variable and with the extension """ allFiles = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f)) and f.endswith(extension)] return allFil...
3564ce88ce7bc2d06e981c0d3d1bd393860ec798
633,527
def addContent(old_html, raw_html): """Add html content together""" old_html += raw_html return old_html
cd5a1677ac4f4216d4cbeb7b7565b44429872bcc
633,528
def get_f_sp_sh(): """太陽熱集熱部の集熱効率 Args: Returns: float: 太陽熱集熱部の集熱効率 """ return 0.4
9c15454742d7095ac47f0b1e54a572c222fa0a00
633,529
def build_variant_display_title(chrom, pos, ref, alt, sep='>'): """ Builds the variant display title. """ return 'chr%s:%s%s%s%s' % ( chrom, pos, ref, sep, alt )
3461166b459e9a5715353080f271ec9ee014bb34
633,530
import torch def safe_to_device(X, device): """Move the tensor or model to the device if it doesn't already live there. This function will avoid copying if the object already lives in the correct context. Works on PyTorch tensors and PyTorch models that inherit from the torch.nn.Module class. Pa...
6d5ccffc2bab4e6447447a90080fe08468966880
633,532
def quote_literal(s): """Quote a literal string constant.""" return "'" + s.replace("\\", "\\\\").replace("'", "\\'") + "'"
4be3944b286872597fe73e97f714f12c0c4204be
633,533
import requests def validate_actions(repo): """Validate if a repo has workflows/githubci.yml""" repo_has_actions = requests.get( "https://raw.githubusercontent.com/adafruit/" + repo["name"] + "/master/.github/workflows/githubci.yml" ) return repo_has_actions.ok
0f57e1a7efbea9009c6ea9127b9ecddbbcdd2888
633,534
def get_description(): """ Return a dict describing how to call this plotter """ desc = dict() desc['data'] = True desc['description'] = """This chart presents the date of the first fall (date after 1 July) temperature below threshold 1 and then the number of days after that date until threshold...
14db9fc002336215d7a658bbfe13c773cb9fdb7c
633,535
import torch def cos_difference_mem(a, b, adjacency_matrix): """ The difference of coupled states in an oscillator model. Vectorized, faster but costs more memory. :param a: the vector a :param b: the vector b :param adjacency_matrix: The adjacency matrix :return: The vector y with element...
cecf7c00a3efe5bf76b37bf5c88565e4f11e9be2
633,536
from pathlib import Path from typing import Dict def parse_id_from_relative_path(relative_path: Path) -> Dict[str, str]: """从相对路劲来解析id中的构造参数. Args: relative_path (Path): 相对路径 Returns: Dict[str,str]: 构造id时的参数字段 """ version_str = relative_path.parent.name schema_name = relativ...
60eccdc9034995dddb6cf9cd65bb44da55955a71
633,537
def replace_namespace(old_uri, target_namespace, rdf_type): """ Utility function for mapping an SBOL object's identity into a new namespace. The rdf_type is used to map to and from sbol-typed namespaces. """ # Flag as not working to ensure nobody calls this function thinking # it might do somet...
d065b70f5c80956c2b24b0911b445a6d0e6d0c9a
633,538
import re def separate(text: str) -> tuple: """Try to separate a string into three columns by white space. Args: text (str): A line in the OCR text. Returns: tuple: Tuple of strings (personReference, neighbourhood, folio). """ text = text[::-1] try: folio, n...
f9b3ee21d7456dafeede77dc8fae39ae71c2d589
633,539
def valid_block_id(block_id): """Returns True if block_id is valid Returns False if block_id is not valid """ valid = True # Valid length valid = valid and len(block_id) == 64 # Valid characters valid_chars = 'ABCDEF1234567890' tmp_block_id = str(block_id.upper()) for valid...
82f3f5c4e5c6dc3daa16605a834bf7b089af1128
633,540
def square_frobenius_distance(m1, m2): """ Square frobenius distance between two probability matrices/vectors :param m1: :param m2: :return: """ c = m1 - m2 c = c * c return c.sum()
4e3ae1cb1f5ffdec196a94252e4f95fee589d093
633,541
import argparse def _parse_input_arguments(): """Parse input arguments. """ parser = argparse.ArgumentParser(description="Unit timer.") parser.add_argument( "filename", metavar="FILE", type=str, help="Mesh files containing the geometries", ) parser.add_argume...
1207f2e98eccc8b352b1dffb8101ffe70590d930
633,542
import math def city_cost(city: int) -> float: """ Calculate the cost to purchase a specified city. :param city: The city to be purchased. :return: The cost to purchase the specified city. """ city -= 1 return 50000 * math.pow((city - 1), 3) + 150000 * city + 75000
4440d9a27b3c1b7ee1994ef1d1a12042f9335074
633,543
import itertools def generate_graph_specification(model_relations: dict) -> dict: """ Convert model relations into data structure which can be readily converted into a network. """ # group nodes by plate plate_groups = dict(model_relations["plate_sample"]) plate_rvs = {rv for rvs in plate_...
e8800b3b799fe102a0b54cd0881c56cf2e8b887d
633,544
def is_digit(arg: str): """ isdigit() method """ return arg.isdigit()
a64fa899ed8f7ef7665e2de32769ec34f372ce4d
633,545
import sys import getpass def get_input(field_name): """ Requests an input and its repetition. Check the correctness. Args: s (str): name of the requesting input. Returns: str: input sting """ def check_input(s): """ Helper function that checks the minimum length of the string a...
ddecbaaf7581f64ab68603c0d37987115955683c
633,546
def macd(dataframe_name, signal_lag = 9): """Creates MACD Signals Args: dataframe_name (df): Single security dataframe containing at least a 'macd' column signal_lag (int): Desired lag time used for macd rolling average Returns: A dataframe of: original data passed to fun...
43b86619cd215d95b4d52d0dbf0641f39defa190
633,547
from typing import List from functools import reduce def sum(l:List[int],n:bool)->int: """ Sum a list of integer. :param l: List of integer. :param n: if present, multiply the result by -1 :return: The sum of the list """ o = reduce(lambda prev,act:prev+act,l) if(n):o*=-1 return o
e5555a6f0d111a638d233e3d6d45bba1cebba03d
633,548
import multiprocessing def GetJobCount(): """Returns half of the total number of the machine's CPUs as a string. Returns half rather than all of them to avoid starving out other parallel processes on the same machine. """ return str(int(max(1, multiprocessing.cpu_count() / 2)))
c0c1e4bd94ae7ab99ff7854412f1b26e2438db17
633,550
import pickle def load_pickle(filename: str): """Load a variable from a binary file. Args: filename: file name. Returns: Returns the variable. """ with open(filename, 'rb') as f: return pickle.load(f)
fdcfebce6663881cf92fb05530a2588e4e8ad327
633,551
def get_intervals(l): """For list of lists, gets the cumulative products of the lengths""" intervals = len(l) * [0] # Initalize with 1 intervals[0] = 1 for k in range(1, len(l)): intervals[k] = (len(l[k]) + 1) * intervals[k - 1] return intervals
9cc189c288d758541617337455337a16e9046c94
633,552
def pointwise_dict_multiply(dict1, dict2): """ Inputs: - dict1, dict2: dicts with {key: float} Returns: - dict_mult: dict with {key: dict1[key]*dict2[key]} for all keys dict1 and dict2 have in common """ common_keys = set(dict1.keys()) & set(dict2.keys()) return {k: dict1[k]*dict...
27c4923da2408d4785121bd07afb7ca335bfa862
633,553
def is_version_newer(version_1, version_2): """ Indicates whether one vManage version is newer than another. Compares only the first 2 digits from version because maintenance (i.e. 3rd digit) differences are not likely to create any incompatibility between REST API JSON payloads, thus not relevant in th...
f324489d37b559783322baf6ac73574d003317dd
633,554
from pathlib import Path def get_uppermost_dir(cwd: Path) -> Path: """Returns the root directory. Example: `C:\\` fow windows, `/` for Linux. """ cur_path = cwd.parent parent = cur_path.parent while cur_path != parent: cur_path, parent = cur_path.parent, parent.parent return cur_pa...
2adc5c8bc886ce511d6ee56a1fe2464c538ec7e6
633,555
from typing import Callable import re def evaluate(homework: list, rule: Callable) -> list: """Evaluate math homework with different rules.""" results = [] for exercise in homework: while re.search(r"(\([^()]*\))", exercise): exercise = re.sub(r"(\([^()]*\))", lambda x: rule(x.group(1)...
b0cf7eb2d71c716aedf361821ffcfe8a80dda678
633,556
def binary_search(arr, value): """ Binary Search takes array and value to search """ """ returns index or-1""" count = len(arr) midpoint = count // 2 start_index = 0 end_index = count - 1 while value != arr[start_index+midpoint] and count > 1: # import pdb; pdb.set_trace() if...
0f7c149ded84c68bb627c259830572d58e9200f0
633,557
from typing import Optional from typing import Dict def cb_str_loss_wrapper(name: str, **params: Optional[Dict]) -> str: """CatBoost loss name wrapper, if it has keyword args. # noqa D403 Args: name: One of CatBoost loss names. **params: Additional parameters. Returns: Wrapped C...
bec35df2e8c511d8731554271311d7f27da4d527
633,558
def _outer(a, b): """ Return the outer product/combination of two lists. a is a multi- or one-dimensional list, b is a one-dimensional list, tuple, NumPy array or scalar (new parameter) Return: outer combination 'all'. The function is to be called repeatedly:: all = _outer(all, p) ...
f611330e9a6de27f7643de6a0f97cc9d50dba4a7
633,559
def validate_port(neutron, port_obj, this_port_name): """ Returns true if a port for a given name DOES NOT exist if the exists parameter is false conversely true. Returns false if a port for a given name DOES exist if the exists parameter is true conversely false. :param neutron: The neutron client ...
f8b7b1676e96c55e3c06c443ea068608e8042a2d
633,560
import subprocess def get_current_branch(directory=None): """Returns branch name referenced by HEAD. :param str directory: Repository directory. :returns: Branch name if HEAD refers to branch. :rtype: str :raises subprocess.CalledProcessError: If git command finished with non-zero exit co...
3af9f124724cf38329bbeb9edbe0fae9a9ddb741
633,561
def get_num_cols_at_line(bf, line): """ Retrieves the number of columns in a given line of a gtk.TextBuffer. Keyword arguments: bf -- The gtk.TextBuffer object. line -- The line number. """ line_start_it = bf.get_iter_at_line(line) it = line_start_it count = 0 while not it.is_end() and it.get_char()...
0a3bec693e1959b99c2bdc5aaed05adb645a990b
633,562
def demo_extension_3(**kwargs): """test that kwargs style functions are acceptable""" return "p3"
ede2181cd948877ced8eb1badee174edc58ae840
633,563
def is_dict_obj(obj): """Return True if obj is a dict.""" return isinstance(obj, dict)
4b30a91258a8388155eb69888deccbe46a4dc1e2
633,564
def evalBasis1D(x, basis,interval=None): """ evaluation of the basis functions in one dimension """ if interval is None: return 1. - abs(x*2**basis[0]-basis[1]) else: pos = (x-interval[0])/(interval[1]-interval[0]) return 1. - abs(pos*2**basis[0]-basis[1])
b69f9339afa14536d1fb43035a6adf419b518bd8
633,565