content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def load_file_as_list(file_path: str) -> list: """ Loads the file at a specificed path, returns an error otherwise :param file_path (str): The path to the file you want to load :return _file a file of the contents of the file """ _file = "" try: with open(file_path, "r") as ...
5d1c3f87c4108c9f5d6d843c7fbcdc1e127629b4
658,563
import inspect def _has_kwarg_or_kwargs(f, kwarg): """Checks if the function has the provided kwarg or **kwargs.""" # For gin wrapped functions, we need to consider the wrapped function. if hasattr(f, "__wrapped__"): f = f.__wrapped__ (args, _, kwargs, _, _, _, _) = inspect.getfullargspec(f) ...
1f1b1e3698ac9d06ee8afe8255344190c793e258
658,564
def get_tes_status(tes, buffer_low, buffer_high): """ Returns tes status: 1 - No further power input allowed 2 - Only thermal input of efficient devices (e.g. CHP, HP) allowed 3 - All devices can provide energy Parameters ---------- tes : object Thermal energy storage object of ...
7f02dc42f818095b5cebc0d1985b50ed1e1e2ccc
658,566
def extract_encoder_model(model): """ Extract the encoder from the original Sequence to Sequence Model. Returns a keras model object that has one input (body of issue) and one output (encoding of issue, which is the last hidden state). Input: ----- model: keras model object Returns: ...
f3afdff230f1d8fb795c122bbe5abb8c42b90843
658,567
def slider_command_to_str(arguments): """ Convert arguments for slider and arrowbox command into comment string for config file. :param arguments: slider arguments :return: Formatted string for config file. """ return '; '.join(arguments)
36f10271d5fb8f6c7477b71eb515fb4194b5ce4f
658,572
def factorial(n): """Computes factorial of n.""" if n == 0: return 1 else: recurse = factorial(n-1) result = n * recurse return result
16894444b052095b255574aa1ab355e12fa37ef4
658,573
import torch import math def log_poisson_loss(targets, log_input, compute_full_loss=False): """Computes log Poisson loss given `log_input`. FOLLOWS TF IMPLEMENTATION Gives the log-likelihood loss between the prediction and the target under the assumption that the target has a Poisson distribution. ...
aebf9b09f921feac836bba1b56d4243915a5ca18
658,574
def receiver(signal): """ A decorator for connecting receivers to events. Example: @receiver(on_move) def signal_receiver(source_path, destination_path): ... """ def _decorator(func): signal.connect(func) return func return _decorator
478e62178a756bdc8cdfcdf050103b2ab4db3b0b
658,581
def define_options(enable=[], disable=[]): """ Define the options for the subscribed events. Valid options: - CRfile: file created - CRdir: directory created - MDfile: file modified - MDdir: directory modified - MVfile: file moved - MVdir: directory moved ...
a0b35008bebe70d3ec7b964122e24746ee89d1cc
658,583
def safeindex(v, s): """Safe index for v in s, returns -1 if v is not in s""" if v not in s: return -1 return s.index(v)
849583010a50971b68aeb2d97053e3e1c94ec5fb
658,585
def rot13_decode(decvalue): """ ROT13 decode the specified value. Example Format: Uryyb Jbeyq """ return(decvalue.decode("rot13"))
dcf9625f329ee19a5138adf0b909a17f686ce41e
658,587
def get_image_url(status): """ Get image url from tweet status Parameters ---------- status: Tweet Tweet status that mentions img2palette Returns ------ image_url: str Image url """ if "media" not in status["entities"]: raise ValueError("No phot...
86479c8f58b749439440568fbaed1a1439a0ac34
658,589
def is_full_section(section): """Is this section affected by "config.py full" and friends?""" return section.endswith('support') or section.endswith('modules')
bf11103b876432ac1d6eefc6884bf81647c8ca41
658,590
from typing import List def delete_items(keys: List[str], s3_bucket): """Delete the specified keys from the provided S3 bucket and return the S3 response.""" delete_request = { 'Objects': [{'Key': key} for key in keys] } print(f'Deleting keys {keys} from bucket {s3_bucket.name}') return s...
0f4b3c1227c29acad9105514da9391fe7a6f5b77
658,594
from operator import add from functools import reduce def sum_node_list(node_list): """Custom sum function in order to avoid create redundant nodes in Python sum implementation.""" return reduce(add, node_list)
3be1d07051301a245a7691102bf2bd6926a23d64
658,596
def translate_task(contest: str, contest_no: int, task: str) -> str: """ Atcoderは第N回目コンテストのNの値によって、 URLに含まれるタスク名がアルファベット(a, b, c, d)表される場合と 数字(1, 2, 3, 4)で表される場合がある 数字だった場合は、タスク名(A, B, C, D)をアルファベットの小文字に変換、 アルファベットだった場合は小文字に変換する Parameters ---------- contest : str コンテスト名. AB...
8394c3d0a26d9d698efc9d5383e74c5dd6f109f6
658,599
import struct def read_bin_fragment(struct_def, fileh, offset=0, data=None, byte_padding=None): """It reads a chunk of a binary file. You have to provide the struct, a file object, the offset (where to start reading). Also you can provide an optional dict that will be populated with the extracted...
76f060f1c1a638c5131ae5ab376edd9fbe2905e5
658,600
import six def scale_result(result, scaler): """Return scaled result. Args: result (dict): Result. scaler (number): Factor by which results need to be scaled. Returns: dict: Scaled result. """ scaled_result = {} for key, val in six.iteritems(result): scaled_r...
d7a8001b617d516d71a2526207937bf31351737e
658,601
def cross(o, a, b): """Cross-product for vectors o-a and o-b """ xo, yo = o xa, ya = a xb, yb = b return (xa - xo)*(yb - yo) - (ya - yo)*(xb - xo)
188f06c8f034eb6017bfc8c619d11d1f97451e41
658,603
import re def findall(string, substring): """ Find the index of all occurences of a substring in a string. @arg string: @type string: string @arg substring: @type substring: string @returns: List of indices. @rtype: list[int] """ occurences = [] for i in re.finditer(subs...
b6a60ec42813d7018a64078fb94802a10858ec1d
658,604
def set_kwargs_from_dflt(passed: dict, dflt: dict) -> dict: """Updates ++passed++ dictionary to add any missing keys and assign corresponding default values, with missing keys and default values as defined by ++dflt++""" for key, val in dflt.items(): passed.setdefault(key, val) return pass...
3c0555c3276a20adbbc08f1a398605c6e6d37bd9
658,608
import math def ph_from_hydroxide(concentration): """Returns the pH from the hydroxide ion concentration.""" return 14 + math.log(concentration)
8e92bc5f438ded444c78ec988d2e4e9fe78114fb
658,609
def dont_linkify_urls(attrs, new=False): """Prevent file extensions to convert to links. This is a callback function used by bleach.linkify(). Prevent strings ending with substrings in `file_exts` to be converted to links unless it starts with http or https. """ file_exts = ('.py', '.md', '.sh'...
e0ab3b0a004a2f6a3adca9ca24f0c33c6fc34d3a
658,610
import itertools import functools def dict_combinations(*dict_list_lists): """Given a list of lists of dictionaries return the list of all possible dictionaries resulting from the unions of sampling a dictionary from each list. Basically given a list of lists of dictionaries, returns all the dict...
d8e6f2df24b91d142023ee42b315e388ee9bcfb2
658,611
def check_if_odd(sum: int = 36) -> int: """ Check if the last digit in the sum is even or odd. If even return 0. If odd then floor division by 10 is used to remove the last number. Process continues until sum becomes 0 because no more numbers. >>> check_if_odd(36) 0 >>> check_if_odd(33) ...
1157a64fe94fd253224a5564ff0dd5c900b845a7
658,613
def OUTPUT(out): """Get dictionary serialization for an output object. Parameters ---------- out: vizier.viztrail.module.output.OutputObject Object in module output stream Returns ------- dict """ return {'type': out.type, 'value': out.value}
d3e452c3c45bf848a71e5c6dc158fd0318469b7d
658,614
from typing import Dict from typing import Any import json def load_model_data(filename: str) -> Dict[Any, Any]: """ Loads some model_data that was generated by the model. :param filename: The name of the model_data file to open. :return: The JSON model_data, loaded as a `dict`. ...
9dfc1b79af9bc5c074d13b24c649b320f909b132
658,617
def _leisure_test(norw): """Tests if a node or way is a leisure place""" return 'leisure' in norw.tags
81ab60140f7146a0777abbec482e9fc73597b652
658,620
def sanitize_properties(properties): """ Ensures we don't pass any invalid values (e.g. nulls) to hubspot_timestamp Args: properties (dict): the dict of properties to be sanitized Returns: dict: the sanitized dict """ return { key: value if valu...
3cb806e23a665258989e34369d3d343ade01349e
658,622
def _parse_conll_identifier( value: str, line: int, field: str, *, non_zero=False ) -> int: """Parse a CoNLL token identifier, raise the appropriate exception if it is invalid. Just propagate the exception if `value` does not parse to an integer. If `non_zero` is truthy, raise an exception if `va...
c5f1d186cbc07de931a412e314de22e4dfb46fe6
658,624
def _process_line(line): """Escape string literals and strip newline characters.""" if not isinstance(line, str): raise TypeError("Routine lines should be strings.") if line.endswith('\n'): line = line[:-1] return line
2368aeb49ae4cb70386332d6965273235a554604
658,628
def HasSeparator(line): """To tell if a separator ends in line""" if line[-1] == '\n': return True return False
7acc31565504a57949425c5dec6a1c189940d0f8
658,629
def get_set_sizes(df): """ get sizes of training and test sets based on size of dataset. testing set: 10% of training set :return: training_set_size, testing_set_size """ data_set_size = len(df.index) training_set_size = data_set_size * 0.9 testing_set_size = data_set_size * 0.1 r...
e07495f651814e32743cecd42d23b9f7dd187a74
658,633
import logging def get_logger(name): """ Return a multiprocess safe logger. :param str name: Name of the logger. :return: A multiprocess safe logger. :rtype: :py:class:`logging.Logger`. """ return logging.getLogger(name)
a5143cc3c4929f8a9c889f055b3b01d8fed2865e
658,635
import re def ask_yes_no_question(question): """ Asks the user to answer the given question with yes or no. Yes, Y, No and N are accepted as valid responses (case insensitive). :param question: the question to be answered :type question: str :return: the user's answer :rtype: bool """ ...
a3a2e537e259afcbe032fba73e03036b3c281e90
658,636
import requests def _wiki_request(**params): """ Make a request to the Wikipedia API using the given search parameters. Returns a parsed dict of the JSON response. """ api_url = "http://en.wikipedia.org/w/api.php" params['format'] = "json" params['action'] = "query" headers = { 'User-Agent': "wikipedia/0....
92378392e3898c96f4518d5803f1d3dc5dc1d76d
658,641
def HTMLColorToRGB(colorstring): """ convert #RRGGBB to an (R, G, B) tuple """ colorstring = colorstring.strip() if colorstring[0] == '#': colorstring = colorstring[1:] if len(colorstring) != 6: raise ValueError, "input #%s is not in #RRGGBB format" % colorstring r, g, b = colorstring[:2], colorstring[2:4], colo...
baa81f68696164744419eb5e478ad9f1eea46783
658,644
def calc_distance(mol, atom1, atom2): """ Calculates the distance between two atoms on a given molecule. Args: mol (RDKit Mol): The molecule containing the two atoms. atom1 (int): The index of the first atom on the molecule. atom2 (int): The index if the second atom on the molecule....
355a4e1ae29ef0a9425d4b9b5af731f454d4bbc9
658,649
import re import glob def get_ergowear_trial_files(ergowear_trial_path): """Find all files of an ergowear trial inside a directory. Args: ergowear_trial_path(str): path to the trial directory containing ergowear files. Returns: (list[str]): list with all ergowear trial paths ...
ff67f5b1e357c341cd6e74ffe4b52f1ee131ea4e
658,653
import pickle def load_data(in_file): """load data from file Parameters ---------- in_file: str input file path Returns ------- data: loaded data """ with open(in_file, 'rb') as f: data = pickle.load(f) return data
f6dec6b0a3eb8ed606d59223c64dd841e9369df8
658,655
def is_logged_in(session): """Return whether user is logged into session `session`""" return 'user' in session
cb167a756ba2324afce81fc285043efcd0369ae4
658,656
def addListsByValue(a, b): """ returns a new array containing the sums of the two array arguments (c[0] = a[0 + b[0], etc.) """ c = [] for x, y in zip(a, b): c.append(x + y) return c
16b47a5cdf2c7d91a0d788cb3684f2194384121d
658,657
def get_wait_for_acknowledgement_of(response_modifier): """ Gets the `wait_for_acknowledgement` value of the given response modifier. Parameters ---------- wait_for_acknowledgement : `None`, ``ResponseModifier`` The respective response modifier if any, Returns ------- w...
e1c1fa2115a6bffae50237cf051d9e01fe6d7838
658,660
def clamp_bbox(bbox, shape): """ Clamp a bounding box to the dimensions of an array Parameters ---------- bbox: ndarray([i1, i2, j1, j2]) A bounding box shape: tuple Dimensions to which to clamp """ [i1, i2, j1, j2] = bbox j1 = max(0, int(j1)) i1 = max(0, int(i1))...
d50391a17882c4070a8780d2ad745545741329d2
658,662
import re def sanitise_username(username): """ Sanitise a username for use in a keypair name. """ return re.sub("[^a-zA-Z0-9]+", "-", username)
be3fa6b9140bc5ef0707f25cd784d9cca682f990
658,663
def read_config(in_name): """ Read a fromage config file. Parameters ---------- in_name : str Name of the file to read Returns ------- settings : dict A dictionary with the keywords and the user inputs as strings """ with open(in_name, "r") as data: line...
c71913e91027e737a18b1ee9e43cad19e27efed6
658,664
import re def trim_data_file_name(name): """"Remove date in name for easier tracking in the repo.""" return re.sub(r"(.*DOH COVID Data Drop_ \d{8} - )", r"", name)
24bdf26923e9b09c944fe1615f51c93b6488a1c6
658,671
def alwaysTrue( x ): """This function always returns True - its used for multiple value selection function to accept all other values""" return True
b5f925b9444c2b14759788872adad99366a65371
658,674
def index(request): """ Simple Hello IgglePigglePartyPants """ return 'Hello IgglePigglePartyPants!'
8a6f95cb0f2663cd21b20277362d2101f37d7c85
658,676
def str2float(str_val, err_val=None): """ Convert a string to a float value, returning an error value if an error occurs. If no error value is provided then an exception is thrown. :param str_val: string variable containing float value. :param err_val: value to be returned if error occurs. If N...
e4eeda0335b47fd1eeda9e3c49349975a8e1744b
658,681
def reverseComplement(dna_seq): """ Returns the reverse complement of the DNA sequence. """ tmpseq = dna_seq.upper(); revcomp = '' for nucleotide in tmpseq: if nucleotide == 'A': revcomp += 'T' elif nucleotide == 'T': revcomp += 'A' elif nucleotide...
a9d28d6c44204492ee1dcf6e314aacfc260cec39
658,688
def non_empty(title: str, value: str, join_with: str = " -> ", newline=True) -> str: """ Return a one-line formatted string of "title -> value" but only if value is a non-empty string. Otherwise return an empty string >>> non_empty(title="title", value="value") 'title -> value\\n' >>> non_empty...
fa7b2c332d72acf1f8b2196152504448b574d384
658,690
import logging def build_and_check_sets_experiments(all_vars): """ Description: First we create a variable called 'setExps', which is a dict that goes from set name to a list of experiments belonging to that set (set is equivalent to 'lane'). We then double check that ...
11ff41cee7bd654d85ed8cbc189f41213bc0ae8b
658,698
def prob_mass_green_from_ndvi(ndvi, old_min=0.3, old_max=0.9): """ Calculate probability mass for greenness from NDVI values :param ndvi: :param old_min: :param old_max: :return: """ if ndvi < old_min: return 0 elif ndvi >= old_max: return 1 else: new_max ...
cba7ac7679d79d8b6d997c63fe7f9a406a00f023
658,700
def identify_meshes(dir_): """List meshes and identify the challenge/track in a directory tree.""" meshes_track1 = list(dir_.glob("**/*_normalized.npz")) meshes_track2 = list(dir_.glob("**/fusion_textured.npz")) meshes_challenge2 = list(dir_.glob("**/model_*.obj")) if meshes_track1: meshes =...
6bbfbe5acc8222a8c8e0c44b24b2cdbf756179fe
658,701
async def trigger_mot_unique(message): """Règle d'IA : réaction à un mot unique (le répète). Args: message (~discord.Message): message auquel réagir. Returns: - ``True`` -- si le message correspond et qu'une réponse a été envoyée - ``False`` -- sinon """ if len(me...
b5492465fc1bd78c94ad566f1868b39ed257165c
658,706
import codecs def read_file(filename): """Read a file and return the text content.""" inputfile = codecs.open(filename, "r", "utf-8") data = inputfile.read() inputfile.close() return data
4d2debe4f6d3d93f9a1e26775d48e5930c7075e6
658,715
import csv import json def file_to_dict_list(filepath): """Accept a path to a CSV, TSV or JSON file and return a dictionary list""" if '.tsv' in filepath: reader = csv.DictReader(open(filepath), dialect='excel-tab') elif '.csv' in filepath: reader = csv.DictReader(open(filepath)) elif ...
73189d8237a2b7071f6735079e723260aaecb4eb
658,718
from pathlib import Path def getMountPoint (path): """ Return mount point of path """ path = Path (path).resolve () while True: if path.is_mount (): return path path = path.parent
4349edfe16ddffee94e90458387286207ae8839c
658,719
import textwrap def hex_to_rgb(value): """ Convert color`s value in hex format to RGB format. >>> hex_to_rgb('fff') (255, 255, 255) >>> hex_to_rgb('ffffff') (255, 255, 255) >>> hex_to_rgb('#EBF442') (235, 244, 66) >>> hex_to_rgb('#000000') (0, 0, 0) >>> hex_to_rgb('#000') ...
f749f97230f86c5190c1c3c0ed42cd9a6bdd954f
658,720
def map_range(x, X_min, X_max, Y_min, Y_max): """ Linear mapping between two ranges of values """ X_range = X_max - X_min Y_range = Y_max - Y_min XY_ratio = X_range / Y_range y = ((x - X_min) / XY_ratio + Y_min) // 1 return int(y)
34eaac1753b96bd823526f23ba55cb4d70902217
658,721
def simple_interest_fv(P, r, t): """The future value of a simple interest product consists of the initial deposit, called the principal and denoted by P, plus all the interest earned since the money was deposited in the account Parameters ---------- P: float Principal, initial deposit. ...
b883f8cf2fd07f19a906fd279f3e6ab27dc76a72
658,722
def list_tables(conn): """List all tables in a SQLite database Args: conn: An open connection from a SQLite database Returns: list: List of table names found in the database """ cur = conn.cursor() cur.execute("SELECT name FROM sqlite_master") return [i[0] for i in cur.fetc...
941f1f92d5a421eca2e874e5575a27b68f875483
658,723
def sum_multiples(limit): """Sums all multiples of 3 and 5 under `limit` Args: limit (int): The limit that the sums will be calculated up to Returns: int : The sum of all multiples of 3 and 5 up to `limit` """ return sum(x for x in range(limit) if x % 3 == 0 or x % 5 == 0)
5dfe9b98e660bf97841e3b2b5c7e8e24972f2f20
658,724
def get_filename_from_path(text): """Get the filename from a piece of text. Find the last '/' and returns the words after that. """ return text[text.rindex('/') + 1:]
cc378520912b64338152ac6ad49cb8fa9a967e53
658,726
import six def ensure_unicode_string(value: str) -> str: """Ensure the value is a string, and return it as unicode.""" if not isinstance(value, six.string_types): raise TypeError("Expected string value, got: {}".format(value)) return six.text_type(value)
ec391f0ff73c586cc524e0b144ac7d798d4e1ef2
658,727
def mask_tensor(tensor, mask): """Mask the provided tensor Args: tensor - the torch-tensor to mask mask - binary coefficient-masking tensor. Has the same type and shape as `tensor` Returns: tensor = tensor * mask ;where * is the element-wise multiplication operator """ ass...
fb2c404acf68b7b32444ded391e09472cc75fb75
658,728
import hashlib def hash_url(url): """Returns a sha256 hash of the given URL.""" h = hashlib.sha256() h.update(url.encode('ascii', errors='ignore')) return h.hexdigest()
ee6f208efbb58fc9ab9649c5ac6f4da161435cd8
658,733
def bin(number, prefix="0b"): """ Converts a long value to its binary representation. :param number: Long value. :param prefix: The prefix to use for the bitstring. Default "0b" to mimic Python builtin ``bin()``. :returns: Bit string. """ if number is None: raise TypeError("'%...
bef65a7958804a596d090a840d3a47ce175e6528
658,734
import random def bernoulli_trial(p): """베르누이 확률 변수 1 또는 0를 확률 p의 따라서 리턴""" x = random.random() # random(): 0이상 1미만의 난수 리턴 return 1 if x < p else 0
cdad5c17040e8d2bff4f4bf42acc79afe5c5d27c
658,735
def session_num_pageviews(session): """Number of pageviews in session.""" return len([r for r in session if 'is_pageview' in r and r['is_pageview'] == 'true'])
3a894c621cb76a8865d4753a3f9925a2cd54d8de
658,736
def as_int(tokens): """ Converts the token to int if possible. """ return int(tokens[0]) if tokens else None
390d22b72f072e43cd2934c5dda001e0f5d3d434
658,737
import mpmath def cdf(x, mu=0, sigma=1): """ Normal distribution cumulative distribution function. """ # Defined here for consistency, but this is just mpmath.ncdf return mpmath.ncdf(x, mu, sigma)
8a1019ac75edd07db57c937298b3e00bcea387df
658,743
def swizzle(pixels, width, height, blockW=4, blockH=4): """Swizzle pixels into format used by game. pixels: buffer of pixels, which should be an np.array of at least 2 dimensions. width, height: size of buffer. blockW, blockH: swizzle block size, which depends on pixel format. Returns a li...
0941abc72bbe9f78f0a341641a86533e4227bd95
658,744
def safeadd(*values): """ Adds all parameters passed to this function. Parameters which are None are ignored. If all parameters are None, the function will return None as well. """ values = [v for v in values if v is not None] return sum(values) if values else None
4cfefbfa5ba7754efee813a3daddb3f4d908f990
658,746
def apply_fn_over_range(fn, start_time, end_time, arglist): """Apply a given function per second quanta over a time range. Args: fn: The function to apply start_time: The starting time of the whole duration end_time: The ending time of the whole duration arglist: Additional argument list Returns...
2aeb2809ce1096c4121a07244181097ac099ab71
658,747
def delimit(items): """ Delimit the iterable of strings """ return '; '.join(i for i in items)
771a435b3771fbf2bcdad54cae9f707102756d13
658,749
def get_scale(W, H, scale): """ Computes the scales for bird-eye view image Parameters ---------- W : int Polygon ROI width H : int Polygon ROI height scale: list [height, width] """ dis_w = int(scale[1]) dis_h = int(scale[0]) ret...
66d83aa29f14a77e614ce4effd331f04a52e8acb
658,752
import torch def gram(m: torch.Tensor) -> torch.Tensor: """ Return the Gram matrix of `m` Args: m (tensor): a matrix of dim 2 Returns: The Gram matrix """ g = torch.einsum('ik,jk->ij', m, m) / m.shape[1] return g
6e0482c08df9fa525e965a9662dc35ec3bdfdcd5
658,757
def find_lowest(tem, l): """ :param tem:int, the temperature that user entered. :param l:int, the lowest temperature so far. This function finds the lowest temperature. """ min = l if tem < l: return tem return l
af27f6ab91bf58c2d201195671cdb5aa74f99b97
658,758
def find_sol(c, ws, vs, memo): """ Finds an optimal solution for the given instance of the knapsack problem with weight capacity c, item weights ws, and item values vs, provided maximum total value for subproblems are memoized in memo. """ sol = [] for n in reversed(range(len(ws))): ...
d66aeac659cb7ec6fc54d52e6e32066faaebda37
658,764
def _masked_idx(mask, indices): """Return index expression for given indices, only if mask is also true there. Parameters: mask: True/False mask indices: indices into array, of shape (n, mask.ndim) Returns: idx: numpy index expression for selected indices idx_mask: mask of s...
ad92a03f08f4778f570a0dc88263a2e243e4c175
658,765
def GMLreverser(pointlist): """Reverses the order of the points, i.e. the normal of the ring.""" revlist = pointlist[::-1] return revlist
b09da94e21b2162f722c6fc9b05cfb0e100c14c8
658,768
def natMult3and5(limit): """Find the sum of all the multiples of 3 or 5 below 'limit'""" sum = 0 for i in range(limit): if i % 5 == 0 or i % 3 == 0: sum += i return sum
64eb21299b4c270a3c0d80beb3f710c0ebc1e256
658,770
import functools import operator def compute_check(msg): """ Compute the check value for a message AUCTUS messages use a check byte which is simply the XOR of all the values of the message. """ if len(msg) == 0: return 0 return functools.reduce(operator.xor, msg)
1dec5ac53abaa406760d3a0005cdde01953ef68e
658,774
def trivium_annexum_numerordinatio_locali( trivium: str) -> str: """trivium_annexum_numerordinatio_locali Args: trivium (str): /Path to file/@eng-Latn de_codex (str): /Numerordinatio/@eng-Latn Returns: str: numerordinatio_locali Exemplōrum gratiā (et Python doctest, id...
4bbc96b86edd6caf95a2161c0577866eb049c0e7
658,775
from typing import List from typing import Dict def can_sum(target_sum: int, nums: List, memo: Dict = {}) -> bool: """ :param target_sum: non negative target sum :param nums: List of non negative numbers :param memo: memoization i.e. hash map to store intermediate computation results :return: Bool...
70a1aa3ca8c6bb5229d3b379bed36ed885396493
658,780
import requests def create_private_contribution(username="",password=""): """ Create a private contribution on earthref.org/MagIC. Parameters ---------- username : str personal username for MagIC password : str password for username Returns --------- response: API...
c2bfd5a74fdabf782ccef0bd4b1e145512ed38b3
658,781
def _get_bbox(gdf): """Get tuple bounding box (total bounds) from GeoDataFrame""" xmin, ymin, xmax, ymax = gdf.total_bounds return (xmin, ymin, xmax, ymax)
1a472d73f0d9fbeefe7e3e07f38cd1fd211e7eae
658,782
def parse_dnsstamp_address(address, default_port=None): """ Parses an address from a DNS stamp according to the specification: - unwraps IPv6 addresses from the enclosing brackets - separates address string into IP(v4/v6) address and port number, if specified in the stamp address """ ...
23326fb77ecdc7348e24a01befddc58bf99af0c2
658,784
def mod_family_accession(family_accession): """Reduces family accession to everything prior to '.'.""" return family_accession[:family_accession.index('.')]
ec033cd33fccd8fbd7a0c4407d706ca32fb87fb2
658,789
from typing import Callable def is_hiqed(fun: Callable, fun_name: str) -> bool: """check if this function has been registered in HiQ system The function could be one of: full_qualified_name="<method 'read' of '_io.TextIOWrapper' objects>", fun_name='read' full_qualified_name='<function main...
752de13eb1cb305b0741ed9cd23576a5b9126226
658,791
def unique(seq): """Remove duplicate elements from seq. Assumes hashable elements. Ex: unique([1, 2, 3, 2, 1]) ==> [1, 2, 3] # order may vary""" return list(set(seq))
41e7fd05f0b6a709af8e09c468f99c0bd081dfb3
658,792
def join_base_url_and_query_string(base_url: str, query_string: str) -> str: """Joins a query string to a base URL. Parameters ---------- base_url: str The URL to which the query string is to be attached to. query_string: str A valid query string. Returns ------- str ...
c1c0dcd67fa32bc71134807ad66874aacd51c00d
658,793
def get_empirical_tput(tbs, ttime): """ Returns the empirical throughput :param tbs: total bytes sent for each flow as a dict :param ttime: total time for a session for each flow as a dict :return: a dict type containing all flow ids with their emp throughputs """ etput = {} for l in tbs...
30b627bb90735761f7a0b01162b5d2af1984786e
658,794
import re def xml_get_tag(xml, tag, parent_tag=None, multi_line=False): """ Returns the tag data for the first instance of the named tag, or for all instances if multi is true. If a parent tag is specified, then that will be required before the tag. """ expr_str = '[<:]' + tag + '.*?>(?P<matched_t...
c8c527f34a45f4e27e36d47ef8d356366483ac61
658,795
import re def remove_from_polymer(polymer, unit): """Remove all occurrences of unit, regardless of polarity from polymer.""" regex = f'{unit}' return re.sub(regex, '', polymer, flags=re.IGNORECASE)
ec86903e000ef2eedd3d7c31550bd1645dc05886
658,802
def greatest_increase_or_decrease_in_profits(change_in_profits_and_losses_list, increase_or_decrease, key_1, key_2): """Determine the greatest increase or decrease in profits (date and amount) over the entire period. Args: change_in_profits_and_losses_list (dict): Changes in profits and losses containi...
f14ddec35f506778f3f72a03029118152a862134
658,804
def test_model(model, test_data): """ Run predictions. Args: model: Trained model. test_data: Test dataset. Returns: List of NumPy arrays containing predictions. """ return model.predict(test_data.dataset.data, num_iteration=model.best_iteration)
537683be363800389bdd1fd0e741e83f2f8a0ff2
658,806
def userspec_from_params(user, password): """Given username and password, return a dict containing them.""" return dict( username=user, password=password, )
af3e761ee2774d36e3e4f4f13ae5736ec39e6c2f
658,807