content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def partition_node(node): """Split a host:port string into (host, int(port)) pair.""" host = node port = 27017 idx = node.rfind(':') if idx != -1: host, port = node[:idx], int(node[idx + 1:]) if host.startswith('['): host = host[1:-1] return host, port
6730f44dfbecf819fa394f165efdf2e1faf51bc8
636,166
def checkPointInside( data_point, df_rules, numerical_cols, categorical_cols, check_opposite=True ): """ 1 for the hypercubes where it's inside, 0 for when not. It checks differently whether its for scenarios where the rules are independent according to the different combination of categorical varia...
50957564a7bf21d63c6ef7d26b1bbd393d8daf94
636,167
def get_anchor_sizes(): """ Defines and returns the anchor sizes Returns: (list): anchor_sizes """ anchor_sizes = [ [0.04, 0.056], [0.08, 0.11], [0.16, 0.22], [0.32, 0.45], [0.64, 0.72], ] return anchor_sizes
3c322430895cee0539a2783813454ebb2ad28082
636,168
def indented(contentstring, indent=-1): """ Return indented content. indent >= 0 prefixes content with newline + 2 * indent spaces. indent < 0 returns content unchanged Docstrings: >>> indented("foo bar", -1) 'foo bar' >>> indented("foo bar", 0) '\\nfoo bar' >>> indented("foo ...
7f772df69457355711f4743651f93553ebed8b1e
636,169
def copy_code_from_file(file_name): """读取file_name中COPY到ENDCOPY间的部分""" with open(file_name, 'r') as f: text = f.read() i_start = text.find('# COPY #') i_end = text.find('# ENDCOPY #') return text[i_start: i_end]
e2c525886701ce3eb928b1cd28cd5c7ab00bf9c9
636,170
import pandas as pd import numpy as np import logging def add_layout(df, layout_path, chem_path, chem_plate): """Add_layout function updates DataFrame containing measurements with descriptors columns taken from plate layout excel file. Sheet names in the layout file are translated to column names in the updat...
8125659f6600b3774f8cbc3a0f5f80c287ee8fef
636,171
def pn(phases, ind): """Get index from a feature in a list of features.""" return [phase[ind] for phase in phases if isinstance(phase, list)]
4a8187b0ee944a18f12bd4d738e0a76937875193
636,172
def count_lines(filename): """ Count the number of lines in filename. :param str filename: Path to the filename. :return: The number of lines in the file. :rtype: int """ lines = 0 buf_size = 1024 * 1024 with open(filename, 'rb') as fd: read_f = fd.read # loop optimization...
b5555fb94777682503c94eacf14a7a216b94448b
636,173
def gll(N): """ Returns GLL (Gauss Lobato Legendre module with collocation points and weights) """ # Initialization of integration weights and collocation points # [xi, weights] = gll(N) # Values taken from Diploma Thesis Bernhard Schuberth if N == 2: xi = [-1.0, 0.0, 1.0] ...
cffd27f12cf72827d68949bc45497c6afa3d5753
636,174
def bpm_from_beatspace(btsp): """ Convert a beatspace to a BPM Provided as convenience; the operation is the same as bpm_to_beatspace. :param btsp: beatspace to convert :return: beatspace converted to BPM """ return 60000.0 / btsp
4be4397a2a63b7cade8aa9b9e9843a811c41dda0
636,175
import numpy def differentiation_matrix(n, a, b, order, deriv): """ Usage: x, D = differentiation_matrix(n, a, b, order, deriv) Utility to compute differentiation matrix of specified order of accuracy and derivative order, over an interval [a,b]. Inputs: n = number of intervals to use ...
f2c5611e2314ce6c01e69ad0afe482007f51e8bc
636,176
def is_list(a): """Check if argument is a list""" return isinstance(a, list)
3f0a7ee7f5ff02fa2949938e7c0269bff069e472
636,177
def loop(event_loop): """ 生成loop """ return event_loop
9b298dc6e4fa502addfcf53e996d047d9d4e5522
636,178
import random def draw_random(hand, deck, mn=17): """Draws random cards until the mx is reached, default=17 for dealer. For a player this is gonna be the dealers result """ total = sum(hand) ace_count = 0 temp_deck = deck.copy() while total < mn: deal = random.choice(temp_deck) ...
0ad6e501692b18a95c710c18b605d6e909ae0260
636,179
def conflict_annotation(expt, loc): """ Returns conflict rate of an experiment as a string percentage. Only does this if the experiment is EPaxos, as MPaxos has no conflict rate. """ if expt.is_epaxos(): conflict_rate = '{}%'.format(round(expt.conflict_rate(loc)*100, 1)) return confl...
620939565f5bac3bb278c74cb085d85faba2bdbc
636,180
def unpack3(var, struct_var, buff): """ Create an unpack call on the ``struct.Struct`` object with the name ``struct_var``. :param var: variable the stores the result of unpack call, ``str`` :param str struct_var: name of the struct variable used to unpack ``buff`` :param buff: buffer that the ...
64af84415b6ea6a97bab0797ad5e44923d457fcb
636,181
def format_str(unformatted_str): """ Formats the output into a multi column list, output1 | output2 | output3 """ output = [] for word in enumerate(unformatted_str): if word != '': output.append(word[1]) return output
6262071a93e6d151e240a1288487e972194b6101
636,182
import torch def mulaw_encode(x, quantization_channels, scale_to_int=True): """Adapted from torchaudio https://pytorch.org/audio/functional.html mu_law_encoding Args: x (Tensor): Input tensor, float-valued waveforms in (-1, 1) quantization_channels (int): Number of channels scale_to_i...
76677853d2aea08999d977b7105e25093f6b9fa5
636,184
def if_key_exists(key, dictionary): """ Returns if key exists, if not return 0, used for stats """ if key in dictionary: return dictionary[key] return 0
f151f3d89d9ca1cff400d2f8cb6205744f7919df
636,185
import torch def bbox_intersection(bboxes1, bboxes2, aligned=False): """ Compute the intersections among bounding boxes. Args: bboxes1 (:obj:`nn.Tensor[N, 4]`): Bounding boxes to be computed. They are expected to be in ``(x1, y1, x2, y2)`` format. bboxes2 (:obj:`nn.Tensor[M, 4...
f7473e948a95093ee30881474737ba164e49280c
636,186
def address( name=False, addressLine1=False, addressLine2=False, addressLine3=False, phone=False, email=False, twitterHandle=False): """ *Get The HTML5 address element* **Key Arguments:** - ``name`` -- name of person - ``addressLine1``...
f94ecb7a604a57020cb8a60928511cad76a57e42
636,187
import torch def l1_registered_loss(y_true, y_pred, y_mask, HR_SIZE): """ Modified l1 loss to take into account pixel shifts """ y_true = y_true[:,0,:,:] y_pred = y_pred[:,0,:,:] y_mask = y_mask[:,0,:,:] y_shape = y_true.size() border = 3 max_pixels_shifts = 2*border size_ima...
18288c9799856a9f24835ec5b6da80d6a115dde5
636,188
from pathlib import Path def _get_file_contents(file_path: Path) -> str: """ Helper function to get README contents """ with open(file_path, encoding="utf-8") as file: return file.read()
b62bafc433ad019fa9f103afef84a3ca4096b421
636,191
def cost(beta, **kwargs): """ Calculates the quadratic cost, with an optional regularization beta: Model Parameters return: Cost """ x = kwargs['x'] y = kwargs['y'] reg = kwargs['reg'] lmda = kwargs['lmda'] model = kwargs['model'] # Calculate predicted y given parameters ...
4dc93c5db6b6bf8c6436b33688d25785c920d3be
636,192
def _format_name(m_name: str, sep: str = '_') -> str: """Formats name for url Parameters ---------- m_name : str Name of movie sep : str Word seperator to use '-' or '_' typically Returns ------- str movie name formatted for url insertion """ # enfo...
c1d2d5b24d27fa3828d16a85832cd8bbab4efb39
636,193
def get_shape(inputs): """Get shape.""" return inputs.get_shape().as_list()
ba06f605adbde06a7e2c5831460bbcc2b7d697b3
636,194
import time def isTimestampValid(inputStream): """ Verifies if the timestamp of the event received is within the current minute (on the server) @param timestamp timestamp of the event received (unix timestamp ) @param current_timestamp current timestamp of the server (unix timestamp) Returns boolean """ timest...
8afab8df1d159e73d868eee1fda602bfe367a5a3
636,197
def get_tricks_taken(active_players): """Determines how many tricks currently have been taken""" tricks_taken = 0 for player in active_players: tricks_taken += player.curr_round_tricks return tricks_taken
0a681d520a05aa7cbeccf3fd7a764381217165cb
636,198
def jira_global_tag_v2(task): """ For a global tag update request, get the dictionary of the jira issue that will be created or a string with an issue key if a comment should be added to an existing issue. The dictionary can be empty. Then the default is to create an unassigned Task issue in the BII pro...
137dfd4df96db6846abfaddb6ec26b97fd981273
636,200
import math def isPrime(someInt): """ return True if someInt is prime otherwise return False isPrime(24)=False isPrime(23)=True """ if someInt==2: return True for i in range(2,math.ceil(math.sqrt(someInt))+1): if someInt % i == 0: return False return True
e653d12da1a7581892d570efef1d0e3d847e2968
636,201
from typing import Optional def get_qname(uri: Optional[str], name: str) -> str: """ Returns an expanded QName from URI and local part. If any argument has boolean value `False` or if the name is already an expanded QName, returns the *name* argument. :param uri: namespace URI :param name: local ...
6c9e0cf3dff8d78f5ada5aa35135314cbfb41ad5
636,202
import re def get_converted_prices(prices): """Returns a list of converted to integer prices""" converted_prices = [] for x in range(0, len(prices)): pr = re.findall(r'\d+', prices[x].get_text()) fnl = "" for p in pr: fnl += p converted_prices.append(int(fnl)) ...
c45c1bf61022c7e4ac03b4ca0c30740b025fa624
636,203
def arrange_array_size(batch_size: int, array_size: tuple): """ Decide array size given batch size and array size [batch_size, height, width, channel]. :param batch_size: batch size :param array_size: array (img) size :return: final array size """ output = list(array_size) output.insert(...
8290aca4e72c742dc26b2b09c0cc33dd5a67c52b
636,204
def bam_is_processed_by_program(alignments, program='bamtagmultiome'): """Check if bam file has been processed by the supplied program This function checks if there is an entry available in the 'PG' block in header of the bam file where PN matches the program supplied. Args: alignments(pysam.A...
41b22392992728caa58740c51178dbdbbfb77247
636,205
def convert_define_to_arg(input_define): """ Convert from a #define to a command line arg. Parameters ---------- input_define : str String in the format of "#define variable value". Returns ------- output_str : str String in the format of "-Dvariable=value". """ ...
dd2085ae6ede8dd7df7edad09404ab1e3ee77da5
636,206
import argparse import sys def create_parser(): """Create CLI parser using argparse Returns: argparse.Namespace: args """ # Init parser parser = argparse.ArgumentParser( description="Optimize PDF(s) using Ghostscript. Overwrites original file(s).", ) # Add args parser...
3aceecd3d663b52dbf95039306d759a499e413ce
636,207
def get_subclasses(*args): """Gets the subclasses of the parameters. Parameters ---------- *args : :class:`type` The types to get the subclasses of. Returns ------- :class:`set` The subclasses of ``*args``. """ ret = set() for arg in args: tmp = set(ar...
9361c72656a1fb8c872d4aadfbe8483891573717
636,208
def field_to_ysv_column(field: Field) -> list: # type: ignore """Convert a Field instance to ysv column definition.""" return [ {'input': field.field} ]
d7d73da9cc5bd1fa9af8d2cd7728c9a67454dd3a
636,209
def grab_cite_data(template, supported_templates): """Check for supported templates and extract citation data""" template_name = str(template.name).lower().strip().capitalize() if template_name in supported_templates: data = { str(para.name).lower().strip(): str(para.value) ...
0b5a6b7caeeff41d4f3b9a6ddf54883146c12b8f
636,210
def with_self(method, network, args, kwargs): """Wraps a method with ``with network:``. This makes it easy to add methods to a network that create new Nengo objects. Instead of writing ``with self`` at the top of the method and indenting everything over, you can instead use this decorator. Example...
1433508ccc4290288d508fd7d7d82a9ca2f5620a
636,211
def select_bucket_region( custom_bucket, hook_region, cfngin_bucket_region, provider_region ): """Return the appropriate region to use when uploading functions. Select the appropriate region for the bucket where lambdas are uploaded in. Args: custom_bucket (Optional[str]): The custom bucket na...
40d77327dfd69a9363ef29c4f7c50c04a4c0cfee
636,212
from typing import Iterable from typing import List def basic_complete(text: str, line: str, begidx: int, endidx: int, match_against: Iterable) -> List[str]: """ Basic tab completion function that matches against a list of strings without considering line contents or cursor position. The args required by ...
d27052d1fc26095215f9f153a5a789d84c9e66d2
636,213
def create_formatted_links(): """Create list of tuples representing all year/month/variable combinations""" vars_list = [ "eastward_wind_at_10_metres", "northward_wind_at_10_metres", "eastward_wind_at_100_metres", "northward_wind_at_100_metres", "dew_point_temperature_at_...
a09c57a33d95b46e7f6196bc1becd33b6ec3aac9
636,214
def strtofloat(value): """ This is used to convert form inputs into floats. Heh.. why exactly is this a function? """ return float(value)
3d2064b6a01e29a94de0e3d17b3bef210ddd9c75
636,215
def get_subject_name_from_csv(full_subject_name): """This function gets subject name from csv Args: full_subject_name (str): Full subject name with format XXX_YYY_ZZZ Return: subject_name (str): Subject name """ full_subject_name_list = full_subject_name.split("_", 3) subject_n...
8a63dd724c840e23dc008b1ac416f61721876417
636,216
import hashlib def hash_string(string, salt=None): """Get MD5 hash from a string. Parameters ---------- string : str Some string. salt : str, False or None Optional salt added to the string for additional obfuscation. """ if salt is not None: string += salt ret...
4d3768aa56a97289d35878aa8ac32762f2efe481
636,217
import os def set_dir(path) -> str: """ 설정 디렉토리를 반환한다. 이때 설정 디렉토리가 없다면 생성 후 반환한다. """ lst = os.listdir(path) setting_dir = f"{path}/setting" if not "setting" in lst: os.mkdir(setting_dir) return setting_dir
7bd64dfc435b0ce939fd688974c45ae49148aed7
636,218
def generate_connection_string(account_name: str, account_key: str, protocol: str = 'https') -> str: """Generates the connection string for Microsoft Azure.""" connection_string = (f'DefaultEndpointsProtocol={protocol};' f'AccountN...
58479d78cfb6aec42bb5f22bec14ad2dedde6448
636,219
from typing import OrderedDict def parse_metadata(text): """parse yaml metadata on raster layers Parameters ---------- text: str text in yaml format Returns ------- OrderedDict: layer name: raster attribute number """ text = text.rstrip() metadata ...
b3e7e85b26451dd584f04c1e638b03f4b812b9a1
636,221
import io import zipfile def zip_dict(data, **kwargs): """ Zips a dictionary ``{ str: bytes }``. @param data dictionary @param kwargs see :epkg:`*py:zipfile:ZipFile` @return bytes """ if not isinstance(data, dict): raise TypeError("data must b...
b344c169c19da3cebeb97768f0f880068d7dd947
636,222
def invalid_br_vsby(v): """Checks if visibility is inconsistent with BR""" return not 0.6 < v < 6.1
8bf770d9a4ca6d1c1c95ab1c04e69464d91fcd10
636,223
def _read_code(message): """ Read the verification code from given email message Inputs :param message: <str> verification message sent Outputs :returns: <str> verification code that was sent """ # print("Message Recieved: '%s'" % message) code = message.content.split("...
dd8b323bf62e5be80af16c626bed3409149ca550
636,224
def system_address(accounts): """Address pretending to be the system address.""" return accounts[0]
933a6bd9de823f968ddd820fc5be49f3b326879b
636,225
import os import subprocess import glob def create_parity_files(file_path, redundancy=5): """ :raise: `ParchiveError` if creation of parity files fails """ try: stat = os.stat(file_path) if not stat.st_size: return [] except OSError as error: raise Exception('Co...
b814d6b47a63b7d286198fcf083cb1fa95d93732
636,227
def add_dummy_multiver(post, pkg_dir, config): """Add a dummy multiver=False value.""" return {'multiver': False}
abb8ac274c97e1d73b675b5736ba957914566d61
636,228
import argparse def _parse_args() -> argparse.Namespace: """ Parse the command line args """ parser = argparse.ArgumentParser(description='Orc8r run tool') # Config-only parser.add_argument( '--print', '-p', action='store_true', help="Only update COMPOSE_FILE line from the .en...
59ca50cb3b9cdffecec9c014427c7c24d9d2111b
636,229
def ParsingAddress(raw_location_list): """ A supporting function that parses the raw location info from Yelp Fusion API to make it more readable. Parameters ---------- raw_location_list : pandas.core.series.Series Required. A pd.Series of dictionaries containing address information in the JSO...
88cf27ed13b1bc9ad4b171827b7263e1d06e8067
636,230
def get_port_numbers(ports): """ Get all port number from response and make comma-separated string :param ports: Port portion from response. :return: Comma-separated port numbers. """ return ', '.join([str(port['number']) for port in ports])
3ebd1c2ac324c83f061b3306832941b845404c41
636,231
def provides_facts(): """ Returns a dictionary keyed on the facts provided by this module. The value of each key is the doc string describing the fact. """ return { "2RE": "A boolean indicating if the device has more than one " "Routing Engine installed.", "master": "On a sin...
338aeae206d4264cf791fb31702f0a6171bcd16a
636,232
def square2(value): """ Return the square of a value""" new_value = value ** 2 return new_value
ca170c3063b249fe3fb9983a1ff171c6174141c6
636,233
def extra_entry_points(): """Extra entry points to load the mock_module features.""" return { 'invenio_db.model': [ 'mock_module = mock_module.models', ], 'invenio_jsonschemas.schemas': [ 'mock_module = mock_module.jsonschemas', ], 'invenio_search....
a850ba765742866272583df22355eb6705ce5ad2
636,234
import pickle def restore_model(path_to_ckpt): """ Loads model from a ckpt file. """ with open(path_to_ckpt, 'rb') as fp: data = pickle.load(fp) return data['model']
ff66ed5caf2d296fae17abe38b14bf59c1c72698
636,237
def cast_element_ids_to_s(hash_element_ids, elements): """ Cast a hash of element ids to a string of element ids. :param hash_element_ids: node/relation/way ids :type hash_element_ids: hash :param elements: OSM element to search :type elements: array :returns: a string of node/relation/wa...
48fb92aa479dd8e2ae641744cc52adfbaa249caa
636,238
def remove_colons(hexstr): """Removes colons from a string""" return ''.join(hexstr.split(':'))
a4e870539f9c1a3cb86d4d92ff2e367f92a7125c
636,239
import copy def deep_merge_dict(dict_x, dict_y, path=None, local_overwrite=True, merge_only_exist=False, raise_exception=True): """ Recursively merges dict_y into dict_x. Args: dict_x: A dict. dict_y: A dict. path: local_overwrite: Whether to overwrite the ...
71dc0d75291cc8b83794b995f2cfb4d4d380f0a7
636,240
import sys def readline(message=""): """Gets a line of input from the user (stdin)""" sys.stdout.write(message) sys.stdout.flush() return sys.stdin.readline()
33fd85b348b5ada28da432023cb3742c1f8a4d77
636,241
from typing import List import re def string_to_numbers(num_string: str) -> List[float]: """Parse the SVG string representing a sequence of numbers into an array of floats. Parameters ---------- num_string : :class:`str` String representing a sequence of numbers, separated by commas, spaces, ...
07a51243a16a7f5db066f0ae13d0a9bd89189ffe
636,242
def get_from_address(service): """Get a test 'from' address. :param service: Instance of the stamps service. """ address = service.create_address() address.FullName = "Pickwick & Weller" address.Address1 = "300 Brannan St." address.Address2 = "Suite 405" address.City = "San Francisco" ...
bd76078aedb1c8a5160cae47d89dceac1ee798ee
636,243
def unescape_str(a_string: str, uri: bool = False) -> str: """Iterative parser for string escapes. """ out = '' while len(a_string) > 0: char = a_string[0] if char == '\\': # Backslash escape esc_c = a_string[1] if esc_c in ('u', 'U'): ...
3ae354ec17ef7cfb7cec94f313137af4b31f813a
636,244
import os import subprocess def variableSetup(rundir, tiltseriesnumber, prep): """ Sets up commonly used variables in other functions. """ tiltdirname="/tiltseries%04d" % (tiltseriesnumber) tiltdir=rundir+tiltdirname seriesnumber = "%04d" % tiltseriesnumber seriesname = 'series'+str(seriesnumber) tiltfilename...
86b287331d77114ccb486918e8ab2f9741310580
636,245
def datahash(*arrays): """Hash the data buffers of some arrays.""" hashstr = '' for arr in arrays: w = arr.flags.writeable arr.flags.writeable = False hashstr += '[{}{}]'.format(hash(bytes(arr)), arr.shape) arr.flags.writeable = w return hash(hashstr)
8190ba810365ac7e201a1be5542fea95785f4499
636,246
def constraint1(x): """ Some constraint to ensure that the probabilities sum to one. """ return x[1:].sum() - 1
26ce84ab1c40d55b02d7f15db09fd3c7d0ca1680
636,247
def get_input(prompt_msg): """ This method makes use of the raw_input() method in Python2 and input() method in Python 3. """ return input(prompt_msg)
47c753010ff4fc6c7a4e70ec47ff8808053d7c55
636,248
def merge_sorted_lists(list_left, list_right): """ Merge two sorted lists This is a linear operation O(len(list_right) + len(list_right)) :param left_list: list :param right_list: list :return merged list """ # Special case: one or both of lists are empty if len(list_left) == 0: ...
cc59d96d6f5854fa16b531d9238ddca48193f487
636,249
import re def bcl_scrub_name(name): """Modifies a sample name to be BCL2fastq compatible Parameters ---------- name : str the sample name Returns ------- str the sample name, formatted for bcl2fastq """ return(re.sub('[^0-9a-zA-Z\-\_]+', '_', name))
1e9f5bd95daaca720bf65aff58ff7af6177401f7
636,250
def get_model_configs(model_config, model): """ Get flattened model configurations Args: model_config - model configurations (Namespace) model - model keys and values (dict) """ if not hasattr(model_config, 'max_relative_length'): model_config.max_relative_length = -1 if ...
f7d21f9d697bf10b4a63a57641a40efca5082969
636,252
def groupIntersections(intersections: list, key: int) -> dict: """ Function to group horizontal or vertical intersections Groups horizontal or vertical intersections as a list into a dict by the given key Parameters: intersections (list): List of tuples representing intersection points key (int): Tu...
45f33715dc9917eb224376c2bedede1a8c49c48f
636,256
import re def _is_valid_servers(servers): """ """ valid = True regex_pattern = r"^(https?)://([a-z0-9\-._~%]+|\[[a-z0-9\-._~%°$&'()*+,;=:]+\])(:[0-9]+)?$" server_regex = re.compile(regex_pattern) if isinstance(servers, list): for server in servers: if isinstance(server, tup...
098aea01f4e7c7634ae759e5d2d152119d609d6c
636,257
def compare_binary_result_lists(D1, I1, D2, I2): """comparing result lists is difficult because there are many ties. Here we sort by (distance, index) pairs and ignore the largest distance of each result. Compatible result lists should pass this.""" assert D1.shape == I1.shape == D2.shape == I2.shape ...
4cebd77ba46e1d0ad3ea5bd18c3fcd0eeb2815eb
636,258
from unittest.mock import Mock def get_output_string(patch_obj: Mock) -> str: """Helper function to get text pathed to output.""" return patch_obj["output_path"].write.call_args[0][0].strip()
68aa506fc924117abe8453772d744c7564bc4b35
636,259
def remove_padding(im, pad=0): """ Function for removing padding from an image :param im: image or prob map to remove padding from :param pad: number of pixels of padding to remove :return: """ if pad == 0: return im else: return im[pad:-pad, pad:-pad]
c1f70c285cc6245b941923d554e8d2d1582d98b7
636,260
def join_path(base, *parts: str): """Creates urls from base path and additional parts.""" _parts = "/".join((_part.strip("/") for _part in parts)) # _parts = '/'.join(parts) if base.endswith("/"): url = base + _parts else: url = base + "/" + _parts return url
93b12548dd700981a5f8cfef659816b600c3a74e
636,261
import hashlib def get_md5_tmp(path): """ return the md5 sum of the path. if the path is a temporary directory, the md5 is prefixed with "tmp_" """ m = hashlib.md5() m.update(path) if path.__contains__("temp") or path.__contains__("tmp"): return "tmp_%r" % m.hexdigest() ...
af06e6415c72d4f102908510be70372bb3f76657
636,262
def main(argv): """Main entry point of the program""" print("This is a boilerplate") ## NOTE: indented using two tabs or 4 species return 0
f29a528faa1d59afba9d9e1a008644af3cf96d3b
636,264
import os def _environ(variables): """Copy ``os.environ`` and populate it with additional variables. Transforms the key name from ``some-key`` to ``SOME_KEY``. It will *not* replace keys already present in ``os.environ``. This means you can locally override whatever is in the runtime config. Ar...
e937e06f766e7a0df824755adcc5beb78215d3f1
636,265
def processPlace (place) : """Processes the selected location data from the xml element definition.""" struc = {} for part in place : struc [part.tag] = part.text return struc
11ccb033b9992acf0c1a88e0485d692e2e0e0de1
636,267
def parse_tags(tagset): """Convert the tagset as returned by AWS into a normal dict of {"tagkey": "tagvalue"}""" output = {} for tag in tagset: # aws is inconsistent with tags sometimes they use caps and sometimes not if 'Key' in tag: output[tag['Key']] = tag['Value'] if ...
d38b7243f24bb24b95f0e4de06b299747ce8acbf
636,268
def _get_team_together(postgame, de_data): """Get team together flag.""" if de_data is not None: return not de_data.random_positions if postgame is not None: return not postgame.random_positions return None
e4f6e013744516713c4464e30e8dab260669e8ff
636,270
def convert(vertical_lists): """rotate a given list of lists converts a list as if it was a matrix interchanges 'row' and 'columns' Args: vertical_lists: list of lists to be rotated Returns: list: list of lists contains the same elements as original except t...
58f5d6303045500f64c816f4534e3a77fbe73ff5
636,271
def pad_hexdigest(s, n): """Pad a hex string with leading zeroes Arguments: s (str): input hex string n (int): number of expected characters in hex string Returns: (str): hex string padded with leading zeroes, such that its length is n """ return "0" * (n - len(s)) + ...
8486eed39066269e59ede06ff5f8486b4506faa9
636,272
import glob import os def get_recursive_subdirectories(input_dir, ext): """List dirs recursively under input_dir. Args: input_dir (str): Directory to list children of. ext (str): Extension of files expected in this directory. Returns: (list): List of directory paths relative t...
1cab8eced69098cc73ed8c471670305ffff61d42
636,273
import json def catch_json_error(blob, filepath, **kwargs): """Wrapper to provide better error message for JSON reads""" try: parsed = json.loads(blob, **kwargs) except ValueError as e: raise ValueError("JSON error reading {}: {}!".format(filepath, ...
c630a4b886c2b6be9d3095c4ef3e8a1be84c1723
636,274
def is_oauth_configured(ta_tabs): """ Check if oauth is configured in globalConfig.json. Args: ta_tabs (list): List of tabs mentioned in globalConfig.json. Returns: bool: True if oauth is configured, False otherwise. """ for tab in ta_tabs: if tab["name"] == "account":...
c9ea6f06bb2aefcdfdc960b41155830f16f1a027
636,275
import os def get_full_module_from_day_file(day_file: str) -> str: """ Returns the full module for the given day file Example: adventofcode.year_2020.day_01 """ day_file = os.path.normpath(day_file) segments = day_file.split(os.sep) segments = ["adventofcode"] + segments[-2:] module = ...
3f3116bd08a0629c1ce5b169d175cbb9f8600230
636,277
def translate(curve): """ P.translate(numpy.ndarray) -> numpy.ndarray Take a three dimensional curve defined by a numpy ndarray and translate that curve so that the mean of each of spatial componenets lies at the origin. """ try: return curve - sum(curve)/curve.shape[0] exce...
d8734de5b7c2320e2a4e2c4c03c0a96936514f27
636,278
import re def _handle_char(str): """ takes a str of text represent a tweet and return text removed of repeated characters Arguments: arr: Series. array of tweets. Returns: a string removed of words removed of repeated characters ( e.g احببب: احب) """ # print(f'non: {arr}') # print...
1c687b23e84cc51ab770c12e4eaa41ac069b0765
636,280
def get_last_insert_id(dict_cursor): """ return the last inserted id by this client/connection. see also https://dev.mysql.com/doc/refman/5.7/en/mysql-insert-id.html """ dict_cursor.execute('select last_insert_id() as id') return dict_cursor.fetchone()['id']
e90c077c6b02f0ba4c649832583533e4951e8d1d
636,281
def filter_refgene_ensgene(var_df_per_chrom, variant_class, refgene, ensgene): """Filter for a refgene function, ensembl function or both.""" variant_class = "^" + variant_class if not refgene and not ensgene: print("Using RefGene for filtering") refgene = True ...
457c53f3c4cacea9b10e0be8328b98bbcc888a7a
636,282
def get_pdb_entry_id(block): """ Extracts the PDB entry information of a cif file and returns it as a string """ entry = block.getObj('entry') entry_id = entry.getValue('id') return entry_id
1422a3e12694e5ca8e7f53af51ed0e76f2b8766f
636,283
import math def _rint(num): """ This is how BNG/muparser does "rounding" """ return math.floor(num + 0.5)
b5c294c464a5deb77b50b09dc65e4fdf1d927336
636,284