content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def get_problem(keys, soup): """ Format individual solved problem """ link = soup.find(class_='name_column').find('a', href=True)['href'] row = soup.get_text() return dict(zip(keys, [link.split('/')[2]] + list(row.strip().split('\n'))))
79a7901d0a21fdc3bb288893e8601c68cb737e64
659,497
import logging import sys def set_console(): """Init function for the console handler logger.""" console_format = logging.Formatter( '%(name)s %(levelname)-8s %(module)-10s%(funcName)-15sL:%(lineno)-5d :: %(message)s') console = logging.StreamHandler(stream=sys.stdout) console.set_name('Consol...
923127147cefe2c48c5c726360fa055f168f5f4f
659,499
def mock_project_path(): """This is a partial path, found in the user's home folder.""" mock_project_path = 'harvey/projects/test_user/test-repo-name' return mock_project_path
4613221e030c1bb8bcb6fc156ec0d488adf48f58
659,500
def removeLiquidity_Qh(params, substep, state_history, prev_state, policy_input): """ This function updates and returns the amount Q after a liquidity removal in a specific risk asset; spec 6-28-21 as delta R is assumed to be positive, the signs are reversed """ asset_id = policy_input['asset_id'] #...
f7551d3a2986bbf6bc2a7197b136c2fc1b377791
659,502
def two_level_to_single_level_dict(two_level_dict): """ Converts a two-level dictionary to a single level dictionary dict[meeting][speaker] --> dict[speaker] """ assert isinstance((next(iter(two_level_dict.values()))), dict) single_level_dict = {} for _, value1 in two_level_dict.item...
6932b5f0643fed2c9dd352e843798d444362fc98
659,503
import inspect def run_unit_test(c, verbose=True): """ Runs all methods in a unit test class. Parameters ---------- c : Class Unit test class """ if verbose: print('BEGIN testing {}'.format(c.__name__)) methods = inspect.getmembers(c, predicate=inspect.isfunction) ...
9f7c87b76e5bbc8645d46518613d60ffe633f10f
659,504
import logging def infolog(caplog): """Sets the log capture level to ``logging.INFO``.""" caplog.set_level(logging.INFO) return caplog
fcddbcd53ce7caf4577bf43c3f83420d4b2a6d01
659,505
def merge(lista, listb, verbose=False): """Merges two lists together""" ptra = 0 ptrb = 0 if verbose: print('\na = {}, b = {}'.format(lista, listb)) output = list() while ptra < len(lista) or ptrb < len(listb): if ptra == len(lista): output.extend(listb[ptrb:]) ...
41574285464d13ceed6eec2a1f6a3e2698df9bac
659,506
import re import os def _tar_ls(tar, path): """ Helper function: "ls" the given path in the tar, i.e. list files/subdirectories contained in the given path. :param str path: the subdirectory which should be listed. Empty refers to the root of the tar. :returns: sorted list of file-names/subdirecto...
fbf55eda6ddac9f822c7152154b52f8404ee3703
659,507
def transform_attr(name): """ Transform camel case attributes to CSS style """ res = "" for ch in name: if ch.isupper(): res += "-" + ch.lower() else: res += ch return res
c438ce33f7c6716a929d9772e903fc703ee6e1d1
659,508
def stack(trials_list): """Return an instance of a trials object of all trials. Arguments: trials_list: A tuple of trial objects to be stacked. All objects should be of the same class. Returns: A new trials object. """ trials_stacked = trials_list[0].stack(trials_list)...
daa7ca3410f334635e3487b7a4dbc58bd1fbed5f
659,509
import binascii def hex2b64(hex_string): """Convert a hex string into a base64 encoded string.""" return binascii.b2a_base64(binascii.a2b_hex(hex_string)).strip()
9af02ed09923682726a9087f0a141a4a459bf484
659,511
import pyarrow.parquet as pq def parquet_decoder(stream): """ Read parquet formatted files """ table = pq.read_table(stream) return table
c45522e686101d93cd798d2334b5a58c43b96080
659,512
import itertools def hyperparameter_combinations(hyperparameters): """ Generate all possible combinations of hyperparameters. Inputs: hyperparameters: dict containing pairs of hyperparameter names and set of values to try. Example: {"learning_rate": [0.1, 0.2], "epoch...
15fc39acf3caafa27c5da4eb541a43d984aaac05
659,514
import os import re def upperCaseName(gedcomFilename, outputFilename = None): """ gedcomFilename : str of the gedcom file to import outputFilename : str of the output gedcom to generate. If None, the function appends '_WithUpperCase.ged' to the gedcomFilename ...
69db5dc1cf5b5f37e096437c5139c807a030f42f
659,515
def get_intercept(model): """get intercept from trained model""" return model.layers[-3].get_weights()[1]
6e1b8b6357004e443748e73f7d82b5f030836728
659,516
import ntpath def cleanUpPath(path): """ This function: 1) Removes extra beginning/trailing quotes, spaces and newlines. 2) Normalizes the paths. 3) Appends './' to all paths. All paths are assumed to be relative to the Makefile. Returns a clean up path. """ # Remove extra quotes and ...
5ef6adf496aa4d3de1360ccbceaf49d7d9c7647e
659,517
def rotate_pitches(chord, n=1): """ Given a chord (tuple) of pitch classes, such as (1, 2, 3, 4), returns the next rotation of pitches, such as (2, 3, 4, 1), depending on what n is. Params: * chord (tuple): an ordered pitch class set * n (int): number of places to shift. A positive...
e9f29d891d79e47ca351a9ef4b934e2422b04ca7
659,518
def blanknone(v): """ Return a value, or empty string if it's None. """ return '' if v is None else v
76c472257e4c19da55136353de950ab00b1531e0
659,519
def fib0(n): """ Iteration """ fibPrev1, fibPrev2 = 1, 0 result = 0 if n == 1: result = fibPrev1 elif n == 0: result = fibPrev2 while n > 1: result = fibPrev1 + fibPrev2 fibPrev2 = fibPrev1 fibPrev1 = result n -= 1 return result
9cbd7f4006e194beb434a344a7ff41913988be2b
659,520
def ts_mul_from_reaction_muls(rcts, prds, spc_dct): """ evaluate the ts multiplicity from the multiplicities of the reactants and products """ nrcts = len(rcts) nprds = len(prds) rct_spin_sum = 0 prd_spin_sum = 0 rad_rad = True rct_muls = [] prd_muls = [] if nrcts == 1 an...
c997a56d5f092e5ac6558e101ee9474a28134e92
659,521
import math def calculate_rmse(y, yhat): """ Calculates Root Mean Square Error :param y: Actual values as series :param yhat: Predicted values as series :return: RMSE value """ error_sqr = (y - yhat)**2 error_sqr_rooted = list(map(lambda x: math.sqrt(x), error_sqr)) rmse = sum(erro...
ae939377e3430eeb8fdca6fa6fa4ce1136328ac6
659,522
def calc_sma(df, window, column, new_column_name): """Calculate simple moving averages. Calculate SMA for data frame columns and expand data frame with simple moving averages. :param df: Input/output data frame :param window: Number of data points to use in moving average :param column: which ...
53e983be5933e56ad5b28c676f0b956e5c95a41f
659,523
import re def remove_tags(s): """Removes xml-style tags.""" return re.sub('</*.*?>', '', s)
6f9824aca918c13e3f78ae1b2b0e5226524a6900
659,524
def scalar_td(request): """ Several variants of Timedelta scalars representing 5 minutes and 4 seconds """ return request.param
22b6e36052da66078c267f7895354109ab2d4ee8
659,525
def getblock(h): """Gets a block""" print("GetBlock(" + h + ")") blockData = bytes(4) return blockData
e284b1e7ecd9a7741fa0fb5a5244ae30f74af413
659,527
def _compute_support(datas, ck): """ helper function, compute item-set's support without div length :param datas: list of list :param ck: list of frozenset :return: the ck's support (without div data length) """ res = [] for c in ck: count = 0 for d in datas: ...
616f1b6b3202b0046b24012e4ff4d4055603d443
659,528
from string import capwords def just_do_it(text): """ >>> just_do_it('kaczka') 'Kaczka' >>> just_do_it('opodal krzaczka mieszkała kaczka dziwaczka') 'Opodal Krzaczka Mieszkała Kaczka Dziwaczka' >>> just_do_it("powieść jules'a verne'a") "Powieść Jules'a Verne'a" """ return capwords(...
476887ec7706b39d3a59e9dd0b40ce528e4e4732
659,529
import time def check_limit(limit_status): """ Check limit status and sleeps when appropriate in order to prevent rate-limiting by GitHub. """ if limit_status["limited"]: # Wait until we can query again. time.sleep(limit_status["wait_time"]) limit_status["limited"] = Fa...
fe5a6f07a4ccc54e021e5f5d7a4a3858027696b3
659,530
def extract_string_type(field): """ Extracts the string types """ types = { 1: "Double", 2: "Float", 4: "UInt64", 5: "Int", 8: "Bool", 9: "String", 13: "UInt32", 11: str(field.type_name.split(".")[-1]), 14: str(field.type_name.split(".")[-1...
291af3005d57fa5bacdfcdb31944aba47b9839c4
659,532
import sys import os def _resource_path(relative_path: str) -> str: """ Get absolute path to resource. Obtain the path to a resource, even after the app has been frozen by Pyinstaller. Args: relative_path (str): Path relative to the current file Returns: str: absolute path to res...
ff4a9447ccee6af97baa94c4d8d1e4968e44b0a7
659,533
def _prepareTargets(trade_data, lookback): """ Prepare targets for training 0 (nop), 1 (sell), 2 (buy) """ # rev = trade_data["vwap"][::-1] # rev_targets = ( # (rev.rolling(lookback).min() == rev).astype(int).replace(1, 2) # | (rev.rolling(lookback).max() == rev).astype(int) ...
2157f28785ede942a0183efe3a2aa5e0b371b31f
659,534
import glob import os from pathlib import Path def get_netifaces(): """Returns list of interfaces from /sys/class/net """ ret = [] for i in glob.glob('/sys/class/net/*'): rec = {'ifname': os.path.basename(i), 'iftype': 'wired'} if os.path.isfile(i + '/address'): rec['mac'] ...
141914c593d18119fe8013394c370c289015d7c7
659,535
def _check_flag(elems, value): """ Checks that a value is a member of a set of flags. Note that we use a top-level function and `partial`. The trouble with lambdas or local defs is that they can't be pickled because they're inaccessible to the unpickler. If you don't intend to pickle your encoders...
852dfd8201e00adfd665510ad1793e478a2cb46c
659,536
import json def make_json_writer(func, *args, **kwargs): """ Return a function that receives a file-like object and writes the return value of func(*args, **kwargs) as JSON to it. """ def writer(f): json.dump(func(*args, **kwargs), f, indent=1, ensure_ascii=False) return writer
f320312f292081804ac196ae778b3171baa2d9fb
659,537
def dequote(string: str) -> str: """ Return string by removing surrounding double or single quotes. """ if (string[0] == string[-1]) and string.startswith(('\'', '"')): return string[1:-1] return string
f4becde62a4c095daee1ece013485562445638b5
659,538
def _ConvertOldMastersFormatToNew(masters_to_blacklisted_steps): """Converts the old masters format to the new rules dict. Args: masters_to_blacklisted_steps: A dict in the format: { 'master1': ['step1', 'step2', ...], 'master2': ['step3', 'step4', ...] } Returns: A dict in the l...
94d4259c20be9b7231b3d1e06524fc7896737841
659,539
import operator def calculate_group(group): """ >>> calculate_group([1, '+', 2, '*', 3, '+', 4, '*', 5, '+', 6]) 231 """ for(c, op) in (('+', operator.add), (('*'), operator.mul)): while c in group: i = group.index(c) group[i - 1:i + 2] = [op(group[i - 1], group[i ...
8edae0e006616074f1586b609cfb1f019ec295ef
659,541
def wallpaper_image_and_style(properties=[0, "C:\\Wallpaper.bmp", 0]): """Especificar a Imagem e o Estilo do Papel de Parede DESCRIPTION Estas configuracoes lhe permitem especificar a imagem de papel de parede e o estilo de amostragem. COMPATIBILITY Windows 2000/Me/XP ...
6a22f7846d28feee64b31e146d7858e6e2724fa1
659,542
def show_run_error(exit_status, output): """An easy-to-read error message for assert""" return 'Failed with exit status %s\n' \ '--------------\n' \ '%s' % (exit_status, output)
2676c2b25b826d613af9a9af389a1b4bd2dcf07f
659,543
import re def remove_tags(tweet): """ Takes a string and removes retweet and @user. """ tweet = re.sub('(^rt:? @[a-z]+[a-z0-9-_]+)|(\W+rt:? @[a-z]+[a-z0-9-_]+)', ' ', tweet) # remove retweeted at tweet = re.sub('(@[a-z0-9]+[a-z0-9-_]+)', ' ', tweet) # remove users return t...
d2adcc0b90b3eaddda765997d8a1f1037d897392
659,544
import csv def load_smartphones(scenario, path): """ Load phone types forecast. The function either uses the specific data for the country being modeled, or data from another country in the same cluster. If no data are present for the country of the cluster, it defaults to the mean values across a...
b018c5c849e6243ef7a8551b441a287bed826731
659,545
def list_groups(client, display_name=None, query_filter=None): """List groups in the directory""" sub_filters = [] if query_filter: sub_filters.append(query_filter) if display_name: sub_filters.append("startswith(displayName,'{}')".format(display_name)) return client.group_list(filte...
220b5b02b7fd887a5d84af739313cfb1405eb9bc
659,546
import numpy as np def _find_new_gfa_coordinates(x, y, rotatemat): """ Used as a helper function to the on_gfa function to find the new GFA coordinates given a list of x coordinates, y coordinates, and a rotation matrix Parameters: x: a list of x coordinates for the GFAs y: a list of y coordin...
dad9f971c3bd854be8aaa6852ed6b9430536ff52
659,547
def merge(arr1: list, arr2: list) -> list: """Merge two arrays for merge sort Args: arr1 (list): the first array arr2 (list): the second array Returns: list: the merged array """ merged = [] # Compare elements for both arrays while arr1 and arr2: if (arr1[0...
792011afc178c72cd1496b4889567c9c995ff097
659,548
import random def divide_into_validation_and_train(spam_mail_model, ham_mail_model): """ This is the function used to divide the data into test and train data :param spam_mail_model: This is the representation(list) of each spam document in the given format :param ham_mail_model: This is the represent...
cd381361c24360e0a5be98b0acce132d02b615f0
659,550
def betweenness_node_time_family(n_nodes, n_times, n_layers, node_index, time_index): """ find the set of nodes in the static graph with node_index as vertex and time_index as starting time. See betweenness_centrality. """ node_time_family = range(node_index + n_nodes * time_index, n_nodes * n_time...
8a9514b259703ee72cb4e80a3220ea3fe3c3466f
659,551
import argparse def __config_parser(): """ Configuring command-line arguments parser """ ret = argparse.ArgumentParser(description="A simple chained videos" + " downloader") ret.add_argument('-c', '--config-file', help='the configuration ...
cf622c314d006e85b6b4d4cf1b983190dcae0c2f
659,553
def write_csv_string(data): """ Takes a data object (created by one of the read_*_string functions). Returns a string in the CSV format. """ keys = data[0].keys() result = ','.join(keys) result += '\n' # Didn't find a way of convertng to csv # using the csv module ...
e3dea2a9364fc38ae7b2d64e534f475e3e6f11a0
659,554
import string import random def generate_keyword(chars=None, k_length=None): """ Generate keyword for annotators and batches. Args: chars (str): type of characters used to generate keyword, *default:* ``string.ascii_letters+string.digits`` k_length (int): length of the keyword, *default:* ``random.randin...
cd0e22e747a3045e25e65ea265ab722323d05567
659,555
def format_size(size): """ Format into byes, KB, MB & GB """ power = 2**10 i = 0 power_labels = {0: 'bytes', 1: 'KB', 2: 'MB', 3: 'GB'} while size > power: size /= power i += 1 return f"{round(size, 2)} {power_labels[i]}"
a7a9294e86ecc7c4b8e08db7588c82e03ce7d664
659,556
import math import numpy def affineToValues(matrix): """ Converts a libcv matrix into human readable text """ tiltv = matrix[0,0] * matrix[1,1] rotv = (matrix[0,1] - matrix[1,0]) / 2.0 if abs(tiltv) > 1: tilt = math.degrees(math.acos(1.0/tiltv)) else: tilt = math.degrees(math.acos(tiltv)) if tilt > 90.0: ...
b3076d7f53f164bae9cad71fbae087bbc1064d4c
659,558
def get_user_decision(soup, code_block): """Gets user input on a comment it's not able to classify. Separate multiple languages in a single post with a '/'. """ print("Need input.", soup.prettify(), sep="\n") while True: language = input("Language (<Enter> for None): ") or "None" ...
c3c765e54ae6c325540338e8dbd3ce17cb3cc3ba
659,559
from io import StringIO def create_wrapper(text_as_string): """Allow to mock many times a call to one address. Without this function, the StringIO is empty for the second call. """ def _create_wrapper(): return StringIO(text_as_string) return _create_wrapper
1b16cc2aeae98f28e0dc4dfb64f3dc23acabc654
659,560
def sanitize_path(path): """Cleaning up path for saving files.""" return "".join([c for c in path if c.isalpha() or c.isdigit() or c in ' .-_,']).rstrip()
2a054bf2010cd4ec672672a04cf1ac29e776f914
659,561
from typing import Dict import json def read_dict(file_path: str) -> Dict: """ Read dictionary from path""" with open(file_path) as f: return json.load(f)
6b3201f6e6573dafd4f65d3ae9e63ac244027f37
659,562
def get_vsp_trim_from_SUAVE_trim(seg_span_percents,vsp_segment_breaks,trim): """Compute OpenVSP span trim coordinates based on SUAVE coordinates Assumptions: Wing does not have end caps Source: N/A Inputs: seg_span_percents [-] range of 0 to 1 vsp_segment_breaks [-] range of 0 to 1...
e536640844f0e05085a9287fb086d79ed602869f
659,563
import json def persist_state(f): """If your ptk wants state, and you don't want to manage it yourself, use this as a decorator on your 'act' implementation. It'll store JSON in the 'data' property of the weavr token, presenting it as the 'state' property of the prosthetic instance. @pers...
53e3ba143c9efd78d762d15e49fbbf728d80e7d0
659,564
def patch_save_intermediate_df(mocker): """Patch the save_intermediate_df function.""" return mocker.patch("src.make_feedback_tool_data.make_data_for_feedback_tool.save_intermediate_df")
6c668407857c3ddbd1b3a29aa5e0e24dfae19d72
659,565
def take_action(embedding, action, expect_success=True): """Takes an action by text, to ease testing""" possibilities = embedding.possibilities() for possibility in possibilities: if str(possibility) == action: embedding.take_action(*possibility) return True if expect_suc...
c10f24f59e2ad6935fcfcdd297dc644cb800c153
659,566
def normalize_number(number): """ normalize arabic number to english """ arabic_to_english_number_dict = { '۰': '0', '۱': '1', '۲': '2', '۳': '3', '۴': '4', '۵': '5', '۶': '6', '۷': '7', '۸': '8', '۹': '9', } fo...
86fead6f4eecbcd04aae1e34dbab3d359bbd125f
659,567
def pretty(sbox): """ Return a pretty printed SBox. """ # List of Columns p = '\nS-BOX ' for i in range(16): p += '%02x' % i + ' ' p += '\n' for i in range(70): p += '-' p += '\n' # Row for i in range(16): p += '%02x' % i + ' | ' # Entries ...
78228c3fa64e26c60f3d99df6d9ba9a035b263b2
659,568
def sanitizte_color(value): """clean string for color codes. the sting is inserted directly in the SVG and it must be ensured that the user can not insert arbitrary code""" if len(value) == 7 and value[0] == '#': return "#%06x" % int(value[1:], 16) raise ValueError('invalid color')
42de92905d4b8d8d1aaf45d3d002ebe2e13d166d
659,569
def get_GS2011(): """ Get GS2011 data :return: (pairs-of-vso-triples, scores, high-bools) """ pairs = [] scores = [] highs = [] with open('../data/Oxford/GS2011data.txt', 'r') as f: f.readline() for line in f: _, v1, s, o, v2, sim, hilo = line.split() ...
103dee3cf96ca93be541e1b3dbaacc16abce14b6
659,570
import os def is_in_rootdir(): """ Check whether the current dir is the root dir of pyelftools """ dirstuff = os.listdir('.') return 'test' in dirstuff and 'elftools' in dirstuff
5f64e416efc418f53235b030216c4ee8670c4ff9
659,571
def _relabel_nodes_in_edges(edges, idx): """ edges is a list of tuples """ return [(idx[e[0]], idx[e[1]]) for e in edges]
89f40c0fa2283d60b0be0a4931464dc6b91c5a12
659,572
def comparison_pre_validation_checks( workflow_config_dict, wf_key, command_name): """ Checks if provided workflow is correct for commands which need to compare samples """ file = '' file = workflow_config_dict[wf_key][command_name][0] if len(file) > 0: if fi...
91d23514bfde525559aafe7929c7f517efe309c8
659,573
import mimetypes def getMimeType(pathToFile): """returns mime type Args: pathToFile (String): absolute path Returns: String: mime type """ mime = mimetypes.guess_type(pathToFile, strict=True) return mime[0]
388d7512322f72166d5a936b6a6ad9086ec60379
659,574
import torch def to_grayscale(image): """ input is (d,w,h) converts 3D image tensor to grayscale images corresponding to each channel """ # print(image.shape) channel = image.shape[0] image = torch.sum(image, dim=0) # print(image.shape) image = torch.div(image, channel) # print...
c170d728f26391233f92b27006d14040a2c5854a
659,575
def puppies_function(): """App route function for the URI '/puppies'.""" return "Yes, puppies!"
a6303fafb55db3e7ed0ac9edcb1b64886c71c30a
659,576
def _next_is_internal(tb): """Return True if the next traceback refers to an internal part of datatest. """ tb_next = tb.tb_next if not tb_next: return False return (tb_next.tb_frame.f_globals.get('__datatest', False) or tb_next.tb_frame.f_globals.get('__unittest', False))
c7fc240329f582f940c7c871a8fa37e30aecb77a
659,577
def minimal_generalizations_cons(h,d): """returns all minimal generalizations of h that are consistent with positive example d""" generalizations=set() mg=[f for f in h] for i,f in enumerate(h): if f!=d[i]: if f!="0": mg[i]="?" else: mg...
4357581b305265118e7e38010e537cf9e132baf6
659,578
def packagesNewestByNameArch(pkgs): """ Does the same as PackageSack.returnNewestByNameArch() The last _two_ pkgs will be returned, not just one of them.""" newest = {} for pkg in pkgs: key = (pkg.name, pkg.arch) if key in newest and pkg.verLE(newest[key]): continue ...
5f34f656944eaa79d7f26d55d8c8c2f6ad36ac84
659,579
def getOriginalFileName(fileName, fileExtension=".c"): """ Strips a file name off digits and underscores and returns the original file name """ originalFileName = fileName.replace("_","").replace(fileExtension,"") # Now remove the digits for i in range(10): originalFileName = originalFileName.rep...
825fc2963903c6972c52deff0a4faaf8036680cc
659,580
def human_file_size(num): """Readable file size""" for unit in ["", "KB", "MB", "GB", "TB", "PB", "EB", "ZB"]: if abs(num) < 1024.0: return "%3.1f %s" % (num, unit) num /= 1024.0 return "%.1f%s" % (num, "YB")
7faf231d5daca8d1c66ad6cb894b61013f37ac78
659,582
def definition(): """ View of most recent finances. """ sql = f""" SELECT f.period, f.costc, f.acad_year, f.coefficient*ISNULL(f.amount,0)*-1 as amount, s.set_cat_id, fsc.description as set_cat_name, sc.internal as is_internal, sc.description as summary_description, sc.position as su...
698976178f424cb832f059b38b46eff6399859dc
659,583
import itertools def partition(iterable, k): """ Partition finite iterable into k almost-equal partitions in round-robin manner. :type iterable: iterable :param iterable: A finite iterable. :type k: int :param k: Number of partitions. :rtype: list :returns: List of lists of partition...
5f298cb56cbe58b125d06fcd9f42227d91e59af5
659,584
def set_name_from_dict(string, dictionary, key, leading, trailing): """Replaces the string with the value from a specified dictionary key, prepending and appending the leading/trailing text as applicable""" return "{}{}{}".format(leading, dictionary[key], ...
4641822ccca293b59a39f666fd715329d884c529
659,585
def checkfile(apifunc, fname): """ Checks whether the string can be found in a file """ if apifunc in open(fname).read(): #print("; " + apifunc + " found in " + fname) return True return False
fc00c9ba9dc9513c39bb9358c7c5c75d21f57707
659,586
def hourly_indicators(df, capacity): """ Compute the indicators based on the df profile >>> df = pd.Series([0.2, 0, 0, 1] , index=pd.date_range('2000', ... freq='h', periods=4)) >>> hourly_indicators(df, 1) (1.2, 2, 1.2) """ # there is no difference by using integration ...
a211fb9c1e3e0b1a0df33ea5f46102f26459e64b
659,587
def _llvm_get_rule_name( prefix_dict, name): """Returns a customized name of a rule. When the prefix matches a key from 'prefix_dict', the prefix will be replaced with the 'prefix_dict[key]' value. Args: prefix_dict: the dictionary of library name prefixes. name: r...
86d081374080317f4e67ebceee7e49a4aedd76df
659,589
def toStringArray(name, a, width = 0): """ Returns an array (any sequence of floats, really) as a string. """ string = name + ": " cnt = 0 for i in a: string += "%4.2f " % i if width > 0 and (cnt + 1) % width == 0: string += '\n' cnt += 1 return string
870b6cb1c9ee306a7e1360f43c8a681d95a15dbc
659,591
def darpaNodeNet(node_id): """Return IP subnet of radio node on DARPA's network.""" return '192.168.{:d}.0'.format(node_id+100)
b0d0b5c2271f48b908a62850fbfbfcb514d1ccd1
659,593
import argparse import os def preprocess_args(args: argparse.Namespace) -> argparse.Namespace: """Preprocess arguments parsed by argparse. Specifically, this function disambiguates the relative paths supplied for :attr:`args.image_dir` and :attr:`args.thumb_dir` and converts them into absolute paths....
843c1dfc5a5de1d24fbfef1b1feb948d9a2d554a
659,594
import pickle def load_cluster_proposals(proposal_file): """ :param proposal_file: cluster proposal_file: :return: cluster proposals """ with open(proposal_file, 'rb') as f: data = pickle.load(f) print('load the cluster proposals done') return data
0376dfa70b7180fa0ec40334a8c14a549f31f7b0
659,595
def add_elisions(_ipa): """ Add alternative pronunciations: those that have elided syllables """ replace={} # -OWER # e.g. tower, hour, bower, etc replace['aʊ.ɛː']='aʊr' # -INOUS # e.g. ominous, etc replace['ə.nəs']='nəs' # -EROUS # e.g. ponderous, adventurous replace['ɛː.əs']='rəs' # -IA- # e.g. pl...
6b7188e9a18bded52ecc4792843c6bb75847b40b
659,596
from sympy.stats.stochastic_process_types import StochasticProcess def sample_stochastic_process(process): """ This function is used to sample from stochastic process. Parameters ========== process: StochasticProcess Process used to extract the samples. It must be an instance of ...
600f3f7a4eba48075966cbf28b83bf1bfc564339
659,597
def Get_All_Currency(dog): """ 获取bigone中所有的币种信息 :return: List Currency """ List_Currency=[] All_Currency_Infos = r=dog.get_accounts() for All_Currency_Info in All_Currency_Infos: List_Currency.append(All_Currency_Info['account_type']) return List_Currency
0340e40a095f32a646ab6830797fc0789f381a7c
659,598
def dthandler(obj): """ если на входе datetime, то преобразует в ИСО формат дату """ if hasattr(obj, 'isoformat'): return obj.isoformat() else: raise TypeError("Unserializable object {} of type {}".format(obj, type(obj)))
88d366952df905dc6a9fb2cf519da6a4f51f6cff
659,599
import os import glob def find_csvs(residue_string): """ Returns a list of CSVs with the specified central residue. :param residue_string: 3-letter abbreviation of the residue :return: list of csv paths """ root = os.path.abspath(os.sep) csv_directory = os.path.join(root, "home", "khs26",...
bc843b4dbf2f95644169c5aa8ed1ba08032c5237
659,600
def make_title(passage_name, process=True, line_end=''): """Make a valid page header from a name""" passage_name = passage_name.lower() if process else passage_name return f':: {passage_name}{line_end}'
c148285fc49a32bf612f32eeb98671aaf4c1ab8a
659,601
def venv(c): """ Runs a command in a virtualenv (which has been specified using the virtualenv context manager """ return c.prefix("source {}/bin/activate".format(c.config.bgtools.VENV_DIR))
3ef82180e55b6de7e92bde6fc501ba81b8c54321
659,602
def challenge(authentication, realm): """Constructs the string to be sent in the WWW-Authenticate header""" return u"{0} realm=\"{1}\"".format(authentication, realm)
18b5e4f5f142fa3d6311b9a9af59bc910e38c999
659,603
def timesteps(paths): """Return the total number of timesteps in a list of trajectories""" return sum(len(path.rewards) for path in paths)
dcbe20ccb04efdaba786e171d02fc91ebe87867d
659,604
def get_string_pattern(lst, pattern): """ Returns the string of the list based on the pattern :param pattern: :return: """ for i in lst: if pattern in i: return i return False
bdf996061a5c24eb1e01463002da8e2e87ee2281
659,605
def flag_to_list(flagval, flagtype): """Convert a string of comma-separated tf flags to a list of values.""" if flagtype == 'int': return [int(_) for _ in flagval.split(',') if _] elif flagtype == 'float': return [float(_) for _ in flagval.split(',') if _] elif flagtype == 'str': ...
7c9376d17d47d6220c32690240652a3c4b52d6a5
659,606
def get_open_pull_requests(repo=None, base=None): """ retrieve open pull requests from specified repository :param repo: :param base: :return github.PaginatedList.PaginatedList """ if not repo: raise ValueError("you must provide repo") if not base: raise ValueError("yo...
da25581c6e1abf00c67c9461232b63bf83b305e5
659,607
def visualise_path(map_list: list[str], solution_path: list) -> str: """ Create a visual representation of the path, line by line. Inserts path char "O" into the map str. """ for point in solution_path: map_list[point.y] = map_list[point.y][:point.x] + "O" + map_list[point.y][point.x + 1:] retur...
44d3955f41a93803a766759d730b2d2c17f83ca5
659,608
def is_prolog_functor(json_term): """ True if json_term is Prolog JSON representing a Prolog functor (i.e. a term with zero or more arguments). See `swiplserver.prologserver` for documentation on the Prolog JSON format. """ return ( isinstance(json_term, dict) and "functor" in json_term and "ar...
b3435672520b2be45e2194a016f73b987d3e1dc6
659,609
def get_cmd_param(command, input): """return word after command if input starts with command, otherwise return None""" cl = command.lower() il = input.lower() n1 = len(command) n2 = len(input) if n1 > n2 or not il.startswith(cl): return None # it is not command return input[n1:].lstrip()
06f79d115cec1be0421e4ca63cdc74fb147c82f5
659,610