content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def l2s(x): """ [1,2,3,4,5,6,7,8] -> '1,2,...,7,8' """ if len(x)>5: x = x[:2] + ['...'] + x[-2:] y = [str(z) for z in x] # convert to list of strings, eg if list of int y = ",".join(y) return y
a7d0d5147912c6d671ee3475591d7207066a0a1a
632,891
def count_word_occurrence_in_string(text, word): """ Counts how often word appears in text. Example: if text is "one two one two three four" and word is "one", then this function returns 2 """ words = text.split() return words.count(word)
0a0b27b2f28c8b939423276e2509480462a7702f
632,892
def reformat_dict_f(dic, mapping): """ switch keys with key values (unique identifier) """ return {k: dic[v] for k, v in mapping.items()}
89ea0b4b7aa217c9e53c8a674ab584a1f2aedec4
632,893
def ed(duration, alignment=None, offset=None): """Constructs an explicit-duration spec dictionary.""" result = {} if duration is not None: result['duration'] = duration if alignment is not None: result['alignment'] = alignment if offset is not None: result['offset'] = of...
03afe53b839ed2c8c49c4aa72a0cee5fa15add93
632,894
import codecs def get_populations(): """ 都道府県の人口情報を取得する """ populations = {} all_population = 0 with codecs.open("population.txt", encoding='utf-8') as f: l = f.readline() while l: elems = l.split(',') populations[elems[3]] = dict( region = int(e...
402fd1d47752869c8182db23ad62478c6553380a
632,896
import ipaddress import re def host_valid(host): """Return True if hostname or IP address is valid.""" try: if ipaddress.ip_address(host).version == (4 or 6): return True except ValueError: disallowed = re.compile(r"[^a-zA-Z\d\-]") return all(x and not disallowed.search...
60591d9bfd5b095ed947abaaee18fbc891d4d47c
632,897
def get_av_fmts(): """ get_audio_video_fmts - returns the audio and video formats supported by the system Returns ------- supported_fmts : list, all formats supported by vid2cleantxt """ audio_fmt = [".wav", ".mp3", ".m4a", ".flac"] video_fmt = [".mp4", ".mov", ".avi", ".mkv", ".ogg", "...
4e83e5ac4272e5e1566bb3f981238396d4469adf
632,898
def multiproduct(seq=(), start=1): """ Return the product of a sequence of factors with multiplicities, times the value of the parameter ``start``. The input may be a sequence of (factor, exponent) pairs or a dict of such pairs. >>> multiproduct({3:7, 2:5}, 4) # = 3**7 * 2**5 * 4 279936...
b1f40f1251e521e773f29355161f7c8b5c804b29
632,899
def make_comment(content: str) -> str: """Return a consistently formatted comment from the given `content` string. All comments (except for "##", "#!", "#:", '#'", "#%%") should have a single space between the hash sign and the content. If `content` didn't start with a hash sign, one is provided. ...
1c83a1180493de6eca6c100d2e4d661a5e10e48f
632,900
def get_alphabet(number): """ Helper function to figure out alphabet of a particular number Remember: * ASCII for lower case 'a' = 97 * chr(num) returns ASCII character for a number e.g. chr(65) ==> 'A' """ return chr(number + 96)
dac98249de4b819d317922a0d390f1d84c3f338f
632,901
from typing import Dict import os def token_to_index(path: str) -> Dict[str, int]: """Reads in a newline-separated file of tokenizer entries. Parameters ---------- path : str Path to a vocabulary file. Returns ------- w2i : Dict[str, int] Dictionary mapping a token string...
b3ff01ee2a9e6cc044e691cb0ad06462b0276442
632,902
def make_doc1_url(court_id, pacer_doc_id, skip_attachment_page): """Make a doc1 URL. If skip_attachment_page is True, we replace the fourth digit with a 1 instead of a zero, which bypasses the attachment page. """ if skip_attachment_page and pacer_doc_id[3] == '0': # If the fourth digit is ...
ed1d37573632dfdafc3cd43255223e9e4fa474c6
632,903
from typing import Tuple from bs4 import BeautifulSoup def _parse_igd_profile(profile_xml: bytes) -> Tuple[str, str]: """ Traverse the profile xml DOM looking for either WANIPConnection or WANPPPConnection and return the value found as well as the 'controlURL'. """ doc = BeautifulSoup(profile_xml,...
339fe2608ee81a1f9779818d52921b7471fbb42f
632,904
from typing import Type from pydantic import BaseModel # noqa: E0611 def _resolve_schema_name(model: Type[BaseModel]) -> str: """ Hacky function to determine a schema name based on the model type. This should be updated to something more robust in the future. :param model: The model that will be use...
43f1b7e6a1f6a99239fb5aafef229addce8023dc
632,905
from typing import Pattern from typing import List def exclusive_match(pattern: Pattern, pattern_list: List[Pattern], text: str) -> bool: """ return True if there is just one match to `pattern` return False for ambiguous matches or no match """ if not pattern.match(text): return False ...
f1b71105dc00ff7e6bdb1f5f8182969ad4880b8f
632,906
import inspect from typing import Dict from typing import List def parse_method_signature( signature: inspect.Signature, param_dict: Dict[str, str] ) -> List[List[str]]: """Combines Signature with the contents of a param_dict to create rows for a parameter table. Args: signature: the output from ...
91e333a6ac37e938fdadadb7d47f312d3c43edb3
632,907
def part_one(password_list): """Count the number of passwords that meet their accompanying criteria. In this case, a password must have a specified character occur between a minimum and maximum number of times. :param password_list: A list of tuples from parse_input :return: int """ valid_p...
864c41e786512f64a21d5522c7db5e6168366d9e
632,908
def create_stack( cfn_client, template_path, stack_name, params={}, capabilities=[], timeout=300, interval=30, ): """ Creates a cloudformation stack from a cloudformation template """ with open(template_path) as file: body = file.read() stack_params = [ ...
80608a4a04e70701bbc5c1628a4300b69aec7486
632,909
import random import string def letter(random=random, *args, **kwargs): """ Return a letter! >>> mock_random.seed(0) >>> letter(random=mock_random) 'a' >>> letter(random=mock_random) 'b' >>> letter(random=mock_random, capitalize=True) 'C' """ return random.choice(string.a...
22ffff88c32d34b1fb5afcb6bc87ed8ac1be9c9a
632,910
def get_list_as_str(list_to_convert): """Convert list into comma separated string, with each element enclosed in single quotes""" return ", ".join(["'{}'".format(list_item) for list_item in list_to_convert])
040ef0887e19a134c3ade513a880870cc4d50c5c
632,912
def create_log_inspection_rule(api, configuration, api_version, api_exception, name, path, pattern, group): """ Creates a basic log inspection rule that monitors a log file for errors. :param api: The Deep Security API modules. :param configuration: Configuration object to pass to the api client. :para...
19a82f84986b2c2a5c61e3438f1ff09dbcc6d47e
632,913
def flatten(children, sidx, lidx): """ Helper function used in Visitor to flatten and filter lists of lists """ ret = [children[sidx]] rest = children[lidx] if not isinstance(rest, list): rest = [rest] ret.extend(list(filter(bool, rest))) return ret
cafeeeca2c7d3b08cd68547814415b8024e6be08
632,914
from typing import Union from typing import NoReturn def _get_file_str(file: int) -> Union[str, NoReturn]: """Convert a given integer to a file letter on a chessboard.""" file_dict = { # Used for int to str lookup for files 0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h' } return file_dict[...
6c057a780792b26551825be72aa1553a2b80497d
632,915
def vars_to_dic(vars): """ Converts list of tf variables to a dictionary where the var names are the keys Args: vars: list of variables Returns: dic """ return dict((var.name.split(":")[0], i) for i, var in enumerate(vars))
0b74ac80c7d1b0018a7e5f1fe21596ef19fae2be
632,917
def all_routes(cities, i=0): """Return all possible routes, where cities[i:] have been permuted. Args: cities (list of string): The cities that make up each route. i (int, optional): The starting index of the subarray of cities to be permuted. Returns: list...
28a2616f1696f554f703eef7a3a059637a3b03b4
632,918
def _strip_h5(value: str) -> str: """ remove trailing .h5, if present """ if value.endswith(".h5"): value = value[:-3] return value
163d4b9f5d05ae0165cfb7d3b1e0fdbc7b3ca2a6
632,919
import torch def invariant_loss(x, y, symmetry): """ Finds permutation invariant loss, for fixed set of allowed permutations. Computes picking minimal loss under all permutations. Uses L2 loss. :param x: Input of shape (..., d) :param y: Output of shape (..., d) :param symmetry: Symmetry ...
7cbcbb2ba49757d940bbaf5bc9f5668c00a74b9d
632,920
def numerical_gradient(score, R, eps=1e-8): """ Calculate numerical gradient of scoring function with respect to rotation matrix """ num = R * 0 val = score(R) for i in range(3): for j in range(3): R[i,j] += eps num[i,j] = (score(R)-val) / eps R[...
d08f09c42f07238448d0a3a7ec6961e8d368dab2
632,921
import argparse def arg_parse(): """ Parse arguments to the detect module """ parser = argparse.ArgumentParser(description="Navigation Module Video Demo Detection") parser.add_argument("--fps", dest = "fps", help = "What fps was the video shot in", default=15, type=int) parser.add_argument("--width", dest = "w...
11d537ce26910cbbf6d4270be89376ab1252c934
632,922
def unique_edge_sizes(H): """A function that returns the unique edge sizes. Parameters ---------- H : Hypergraph object The hypergraph of interest Returns ------- list() The unique edge sizes """ return list({len(H.edges.members(edge)) for edge in H.edges})
cfa1bcca6f2e55f9986e1f81a23ab9d7c94fb464
632,925
def is_valid_str(s: str) -> bool: """ Check if the input string is not empty. :param s: Input string. :return: True if the string is not empty. """ if s is None: return False if not isinstance(s, str): return False if len(s) <= 0: return False return True
01dc8056d9e152cab4261a47c108b50853340f6e
632,926
def sem_to_minor(version): """ Returns a minor release part of the semantic version @param version: semantic version in format x.x.x @return: minor release in format x.x """ return ".".join(version.split(".")[:2])
da3399c4eae24cd3344035de7223766e266b4822
632,927
import re def generate_owner_candidate(event): """ Generate alternative owner list from a given row of events dataframe """ owner_candidates = [] owner_candidates.append(event['owner']) owner_alternative = event['owner'].replace('Department of ', '') owner_alternative = owner_alternative.r...
af58b7fc6afcf0c2bd2d385d30c57b87cd0456b2
632,928
import functools import numpy def set_random_seed(minval, maxval, name='seed'): """Decorator to parameterize tests with seed for random. Args: minval(int): Minimum value of seed. maxval(int): Maximum value of seed. name(str): Argument name to which the specified seed is passed. ...
7a8697364ac7841b0cf315559aaf9700382744ce
632,929
def longest_increasing_sub_seq(arr): """ Ask the data type and corner cases. Interviewer says as below. - arr is not empty - all element is INT Let dp[i] denote the length of the longest increasing sequence ending at i. Search arr[j] < arr[i] where j in range(i). If not exist such j: d...
30d32ef129a8a17c5743c82ec699d3e518bb5357
632,930
def _grid_location_equals(xarr,grid_location=None): """Return True when the xarr grid_location attribute is grid_location Parameters ---------- xarr : xarray.DataArray xarray dataarray which attributes should be tested. grid_location : str string describing the grid location : eg 'u'...
f5d849e5553ce61ecf2af3c60288c852a838ed8b
632,931
import logging def makeRecord(self, name, level, fn, lno, msg, args, exc_info, # noqa: N802 func=None, extra=None, sinfo=None): """ A factory method which can be overridden in subclasses to create specialized LogRecords. """ rv = logging.LogRecord(name, level, fn, lno, msg, args, e...
7ec82058a3b4efd2d8db0a4c070fcab1695ba80b
632,932
def set_chain(base, key_chain, value): """Sets a value in a chain of nested dictionaries. """ if base is None: base = {} cur = base n = len(key_chain) for i, key in enumerate(key_chain): if i + 1 < n: if key not in cur: cur[key] = {} cur = ...
420e279c963524af2895055783b59167569a9951
632,933
def multiply_sequences(seq1: list, seq2: list): """ A function to multiply two sequences and return the result seq1: A list of integers seq2: A list of integers returns: seq1 * seq2 as a list """ if len(seq1) == len(seq2): return [x * y for x, y in zip(seq1, seq2)] elif len(seq1)...
6106cd1585f101cb9c2507bb03b705043096bc5b
632,934
def reprojection(gdf, tgt_crs): """Reproject in given the GeoDataFrame. Args: gdf (geopandas.GeoDataFrame): GeoDataFrame of reprojection target. tgt_crs (int): EPSG code of target crs. Returns: geopandas.GeoDataFrame: Reprojected GeoDataFrame. """ gdf = gdf.to_crs(tgt_crs) ...
f84f465d3272e5f87e5ea1d9232ba63ee15b6cba
632,935
from typing import Any def coerce_value(val: str) -> Any: """Try to coerce to a more specific type.""" # Try to coerce it to a more specific type, # otherwise just make it a string. try: v: Any = int(val) except ValueError: try: v = float(val) except ValueError:...
5db47ccab5ff300587ff034b276a1fa96d038b10
632,936
import requests from bs4 import BeautifulSoup import re def get_page_text() -> str: """Gets raw API text and removes extraneous characters""" # Get raw HTML from webpage page = requests.get('https://api.nasa.gov/planetary/apod' '?api_key=DEMO_KEY') # Parse raw HTML into a Beaut...
0488909236a7cf98f0c9ecc1cbeb60f190a7dcb9
632,937
def render_index(): """return text message to localhost:5000""" return "AAT Reconciliation Service is running on this port!"
9fcf87ba3e6e02e86efc3503ffdaad01202bec85
632,938
def dojo_dist(options): """ Plot the distribution of the deltafactor and of the relative error for the GBRV fcc/bcc tests. """ fig = options.pseudos.plot_dfgbrv_dist() return 0
c1ea3e066546143975cb8371b6642c7334c87929
632,939
from typing import List from typing import Dict from typing import Any def extract_all_dict_values(list_of_dicts: List[Dict]) -> List[Any]: """Extract list of dicts values into list.""" all_options: List = [] for option in list_of_dicts: all_options.extend(option.values()) return all_options
5bc6ffbaf9c728c0fdeafb7685994f9f794bbd92
632,940
import torch def fix_K_camera(K, img_size=137): """Fix camera projection matrix. This changes a camera projection matrix that maps to [0, img_size] x [0, img_size] to one that maps to [-1, 1] x [-1, 1]. Args: K (np.ndarray): Camera projection matrix. img_size (float): Size of im...
96993d3625fb4f2952327b695e9f7e971473d23b
632,941
def extract_and_validate_element(structure,error_message_prefix=""): """ Extract the element tested from a structure, and check the structure is correct. :param pw_calc: a pw calculation :param error_message_prefix: string to be prepended to the error message if it occurs. :return: the ...
25223789f2481d0867bb42a49fce2da23843f1a6
632,942
import os def last_mtime(files, prefix=None): """ Find the last modified time for a given list of files. """ mtime = None if files: if prefix: _files = [os.path.join(prefix, f) for f in files] else: _files = files # NOTE: If the file doesn't exist ...
ca725ded7f671640f55b301a5493f5fb3b28c59d
632,943
def get_bit(n: int, i: int) -> int: """ Description: Récupère le i-ème bit de n. Paramètres: n: {int} -- Le nombre à traiter i: {int} -- L'index du bit à récupérer Retourne: {int} -- 0 ou 1 Exemple: >>> get_bit(2, 0) 0 >>> get_bit(2, 1...
a51e3205757201a3dcaf5b8b234f48e9fc4741d9
632,945
import os import csv def write_csv(fieldnames, rows, directory, filename): """ Funkcija v csv datoteko podano s parametroma "directory"/"filename" zapiše vrednosti v parametru "rows" pripadajoče ključem podanim v "fieldnames" """ os.makedirs(directory, exist_ok=True) path = os.path.join(direct...
1454a35bb0a623ae61dcee7abfdeeb1573ccd482
632,947
import socket def unbracket_ipv6(address): """Remove a bracket around addresses if it is valid IPv6 Return it unchanged if it is a hostname or IPv4 address. """ if '[' in address and ']' in address: s = address[address.find("[") + 1:address.find("]")] try: socket.inet_pton...
bb8b902f89fbcbb8088fb264287ac18295ad4df0
632,948
def _output_name(src, suffix = ""): """Cleans up the given file name, and replaces the .arcs extension.""" # For references to files in other build targets, extract the filename: # //src/wasm/tests:manifest.arcs -> manifest.arcs if src.startswith("//"): src = src.split(":")[1] return src....
9c93edeb69afe05d0133ae30a7a2cda5e0bd3f9a
632,949
def _rowToBoxDict(row): """ Converts a row from a csv to a dictionary """ box_dict={} box_dict['x'] = row.x box_dict['y'] = row.y # Support both row formats for detect versus truth try: box_dict['w'] = row.width box_dict['h'] = row.height box_dict['species'] = row.species...
9b80201d810f3798c7ba0113b6e51c656ca95599
632,950
import re def extract_version_changelog(changelog, version): """Extract the changelog for a particular version from the entire changelog.""" escaped_version = re.escape(version) pattern = rf"""(?m:^)# Data Hub API {escaped_version} \([0-9-]+\) (?P<content>.*?) (# Data Hub API|$)""" match = re.search...
b59990e6095014a7ea7b4f1ed09eb06f4141e0f4
632,951
def _create_indice(chip): """Account for missing indices (Duo and PrixPowr) and create them. Even if these indices do not actually exist, we still need one for relational data purposes. """ if not chip['game'] == 'bn4': # Nothing to do here. return chip['indice'] indice = ...
8c07ec1022a47ab59a80cc359715fedb320eb170
632,952
import math def get_dxy(region: tuple): """ Get the grid spacing size that will be used to open a grd file Note: h5py will crash when opening grd with less than 2^14 gridpoints, so keep dx and dy small enough relative to domain Parameters ---------- region : (min lon, max lon, min lat, ma...
ad89aa3975803fb5e50dd213d2a53d260437a98b
632,953
def allow_origin_tween_factory(handler, registry): """Allow cross origin XHR requests """ def allow_origin_tween(request): settings = request.registry.settings request_origin = request.headers.get('origin') def is_origin_allowed(origin): allowed_origins = ( ...
52c211fcfb17d9ce56e21903a6eada68390f3cb4
632,954
def same_output_shape(input_shape, options=None): """Shape identity function. (for eg RELU)""" return input_shape
bd794b7bbe4a65351f83ce5ea34aba61a1cdb14e
632,955
def prefix_set(dictionary): """ :param dictionary: the provided dictionary (set) of words :return: all possible letters combinations of words (set) """ prefixes = set(word[:i] for word in dictionary for i in range(1, len(word)+1)) return prefixes
ae82334d5df9a0a07d69d698e15e5bb39ef84dcb
632,956
from typing import Dict import os import json import subprocess import shlex def _merge_daemon_config(config_update: Dict) -> Dict: """merge the given configuration update with the existing configuration in /etc/docker/daemon.json """ config = {} if os.path.exists("/etc/docker/daemon.json"): ...
c36a2732cc9ec768534821fe30ed7ef080929576
632,957
def extractDatSignerParts(dat, method="igo"): """ Parses and returns did index keystr from signer field value of dat as tuple (did, index, keystr) raises ValueError if fails parsing """ # get signer key from read data. assumes that resource is valid try: did, index = dat["signer"].rs...
7cf1e4f2e49f1d5d752ec377955d479e7d52820d
632,958
from pathlib import Path def get_name(path): """Gets the name of the dynophore trajectory without the .pml extension Args: path (str): File path to the dynophore trajectory Returns: str: dynophore_pml """ file = Path(path).stem return file
bef9912cc39702070d160839a9abd102c709deea
632,959
import torch def select_embs(embs, pred_cands, M): """Select the embeddings for the predicted indices. Args: embs: embedding tensor (M x K x H) pred_cands: indices into the K candidates to select (M) M: M Returns: selected embedding (M x H) """ return embs[torch.arange(M)...
9ac40cb87652bf1662be212845bfc4291ad99004
632,960
def read_rst(testdata, parse_rst): """A fixture that automates the loading of test rst files and parsing them into a doctree.""" def load(path): rst = testdata(path).decode("utf8") return parse_rst(rst) return load
11337989ec800207a62fd517d7071c7bd3db4a8f
632,961
def get_uid_warning(uid: str) -> str: """ Returns the templated message for the warning of existing `UID`, while creating a `Student` """ uid_href = f"/students/{uid}/#:~:text={uid}" msg = f"Student with UID <a class=\"alert-link text-secondary font-weight-medium text-decoration-none\"\ ...
a701b6d42ca78e93121903251d5887155fb73835
632,963
def cdf_TPL(x, a, beta, b): """ Cumulative function for truncated power law. pdf(x) = (beta-1)/(a*(1-c^(beta-1))) * (a/x)^beta for a <= x <= b """ F = (1-(a/x)**(beta-1))/(1-(a/b)**(beta-1)) return F
15b735608b5cdb9f72843e4cbe1405c6b26c78c6
632,964
def check_bipartite(graph): """Checks if a given graph is bipartite, that is, if it can be partitioned into two sets of nodes, such that there are no edges between nodes within each set, only edges between nodes on different sides. graph -- adjacency list representation of the graph """ colors...
eb48750b794d9a38fb9664e608bb4bba697262b9
632,968
from datetime import datetime def as_datetime(dct): """ Decode datetime objects from JSON dictionary. """ if dct.get('__class__', '') == 'Date' and 'isoformat' in dct: isoformat = dct['isoformat'][:19] return datetime.strptime(isoformat, '%Y-%m-%dT%H:%M:%S') return dct
368091de485d3743f5b407b7e9da9d9ce136e2a5
632,969
def remove_special_chars(text: str): """ Removes the special characters. :param text: text to be modified :return: modified data """ filtered = text.strip().replace('\'', '').replace('"', '').replace('”', '')\ .replace('–', '').replace('“', '').replace('!', '.').replace(...
d31ada108615416191a2b6e8307d775c119c600e
632,970
import sympy def proper_simplify(expr): """ Combine trig and normal simplification for sympy expression.""" return sympy.simplify(sympy.trigsimp(expr))
d4d3aa07b4f86c01730e6471fc21b33b4234d7f5
632,973
def get_pod_selector(pod): """ Returns: The string representing the labelSelector to select pods of this general type. """ labels = pod['metadata'].get('labels', {}) # We don't use the 'pod-template-hash' label because we want to schedule # our new pods onto the node they're curr...
fb897de70a949cea6ff86b2569decbe5d573da22
632,974
def multiplica(x, y, z=None): """Soma x, y, z Multiplica x, y, z o programador por omitir a variavel z caso não tenha necessidade de usa-la """ if z: return x * y else: return x * y * z
ea85b99c569d51822c142978e246d1089aaa34dc
632,976
def example_filter_yaroslavl_region(item): """ Всегда разрешает импорт записи :param item: :return item or None: """ if item.regioncode == '76': return item
55b5f928b88af9a483541028d78eddb89124232c
632,977
def temporal_filtering(data, param_epoched_data, param_l_freq, param_h_freq, param_picks_by_channel_types_or_names, param_filter_length, param_picks_by_channel_indices, param_l_trans_bandwidth, param_h_trans_bandwidth, param_n_jobs, param_method, par...
0dcfeff18cff4f32f8a31bca2059a6c3ee3a7dd0
632,978
def passes_luhn_check(value): """ The Luhn check against the value which can be an array of digits, numeric string or a positive integer. Example credit card numbers can be found here: https://www.paypal.com/en_US/vhelp/paypalmanager_help/credit_card_numbers.htm :author: Alexander Berezhn...
78e2d2707e98b81585fab55c2f8ae1271da5b932
632,980
import re def clean_text(entry_text): """Summary dayOne adds images and other objects with the following annotation: ![](dayone-moment.objectName) We add images in separate step, so we just remove them all Args: entry_text (TYPE): Description Returns: str...
c832f9f8bdbed60b4ce55cee5a61e4e0dcea4625
632,981
from typing import Dict import json def error_response(text: str = '', status_code: int = 400, content_type: str = 'text/html; charset=utf-8') -> Dict: """ Creates an error response with parameterizable values. :param text: Optional explanatory error text :type text: str :param status_code: Respo...
226285e5897c13c40d01ba36bd8d668218979845
632,982
import os def get_package_list(prefix): """Get packages from an anaconda installation """ packages = [] # Get the (set of canonical names) of linked packages in prefix meta_dir = os.path.join(prefix, "conda-meta") pkg_list = set(fn[:-5] for fn in os.listdir(meta_dir) if fn.endswith(".json")) ...
d2b13a922bbcfb339286a1f13a5f642f65439712
632,983
def get_severity_detail(severity_detail): """ Retrieve details of severity related fields. :param severity_detail: severity details from response :return: severity detail :rtype: dict """ return { 'Combined': severity_detail.get('combined', ''), 'Overridden': severity_detail...
6b6f144815689070667cbf5beec2ea670b422360
632,984
def appendExternalUsers(personDf, appointmentParticipantsDf, emailParticipantsDf, sqlContext): """ This method create MailParticipants dataframe for CDM :param personDf: Person dataframe :type personDf: object :param appointmentParticipantsDf: AppointmentParticipants dataframe :type appointment...
627ec080c62f6eeaf4a9e4654e6cd499bd051e28
632,985
def dirstats(path): """Get stats for the specified directory. Parameters ---------- path : Path Directory to calculate stats of. Returns ------- num_files : int Number of files under the directory (recursive). total_size : int Total size in bytes of all files un...
480ca90ed0d705c046a1fa53e4a4f868cb0bcd88
632,987
from typing import Dict def to_affiliations_list(dict_: Dict): """Convert affiliation dict into a list. :param dict_: affiliation dict. :return: affiliation list. """ l_ = [] for k, v in dict_.items(): v["members"] = list(v["members"]) v["members"].sort() if "count" i...
6c377cb3c682ee2bd5d304bb3321c005029afe43
632,988
def get_lawyer_id(obj): """ Returns string representing an lawyer object. Returns obj.organization if it exists, else returns concatenated obj.name_first + '|' + obj.name_last """ if obj.organization: return obj.organization try: return obj.name_first + '|' + obj.name_last ex...
32c55b001cf06e3b22e889ff079ccbcb834a27d5
632,989
import argparse def parse_arguments(): """ Parse arguments for copy number calling pipeline inputs generation :return: argparse.ArgumentParser object """ parser = argparse.ArgumentParser() parser.add_argument( "-o", "--output_file_name", help="Filename for yaml file t...
020f3bde307aa34d8461f337530bd83b9e1f92f5
632,990
def ontstop_vb(t, y, solver): """ ontstop function to stop solver when tstop is found """ return 1
fa2c1e4296b97c16c375564300e8bb30ca69287d
632,991
def rosenbrock(x): """Rosenbrock test fitness function""" n = len(x) if n < 2: raise ValueError('dimension must be greater than one') return -sum(100 * (x[i+1] - x[i]**2)**2 + (1 - x[i])**2 for i in range(n-1))
3ffa6019c597bf6215015a8a0de444bfa17b410b
632,992
def model_name_to_rest(name): """Gets a name of a :mod:`atomx.models` and transforms it in the resource name for the atomx api. E.g.:: >>> assert model_name_to_rest('ConversionPixels') == 'conversion-pixels' >>> assert model_name_to_rest('OperatingSystem') == 'operating-system' >>> ...
95e54361caf0d5a5a537cc80e146dcf63bebc242
632,993
import random import string def return_random_string(length): """Returns random ascii string""" def rand_str_func(n): return ''.join([random.choice(string.ascii_lowercase) for i in range(n)]) rand_str = rand_str_func(length) return rand_str
c068e76d755d93fcd7271011162d4082997f1451
632,994
def geometricSeries(*, u_1: int, r: int, n: int) -> int: """Compute geometric series up to 'n', given initial value 'u_1' and common ratio 'r'.""" return (u_1 * n) if r == 1 else (u_1 * (u_1 ** n - 1) / (r - 1))
3739e460a61bc7bf2bd3d089176bd482a7f095e6
632,995
def _audience_condition_deserializer(obj_dict): """ Deserializer defining how dict objects need to be decoded for audience conditions. Args: obj_dict: Dict representing one audience condition. Returns: List consisting of condition key with corresponding value, type and match. """ return [ ...
e875cb939340bba1f83174a9f06bd862ce78d89b
632,996
def _use_ssl(addr): """Decide if SSL should be used for the given server address.""" if isinstance(addr, str): return addr.endswith(':993') return len(addr) == 2 and addr[1] == 993
3b3fc9fc73f5740678822ea27df04359421bf294
632,997
def get_security_groups(elb, sg_group, interfaces): """ Retrieve Load Balancer data associated with the network interface. Parameters ---------- elb : dict The response from Boto3 describe load balancers function. sg_group : dict The security group id associated with the network int...
ecade569165c883c1c46515dada0186bf88d6abb
632,998
import re import os def find_files(files, regex): """Find files for processing. Parameters ---------- files : iterable of `str` The files or directories from which the headers are to be read. regex : `str` Regular expression string used to filter files when a directory is ...
5c10927049ac0e3e2df8da21ff70dc1247373284
633,000
def create_vocab(data): """ Creating a corpus of all the tokens used """ tokenized_corpus = [] # Let us put the tokenized corpus in a list for sentence in data: tokenized_sentence = [] for token in sentence.split(' '): # simplest split is tokenized_sentence.append(t...
6646397cc075e60846b38ff8fb70f4067e78eadd
633,001
import requests def check_all_datasets(latitude, longitude, tilt, azimuth = 180): """This function checks all solar resource datasets, and generates a dataframe for each dataset. Returned parameters are collected and returned in a dictionary. The dictionary has keys that are the names of the solar resourc...
401bfe6eee18f590cb5026636b5312ba87c76d01
633,002
def sbr(data, weights): """Stolen Base Runs (SBR) SBR = runSB * SB + runCS * CS :param data: DataFrame or Series of player, team, or league totals :param weights: DataFrame or Series of linear weights :returns: Series of SBR values """ return weights["lw_sb"] * data["sb"] + weights["lw_cs"]...
f577dfa2955802a7cb7177f06f508d7902cbc60d
633,003
import json def already_run(db, configuration): """Checks whether the given configuration is already present in the database""" configuration = configuration.copy() configuration['threads'] = configuration.get('threads', 1) configuration['params']['threads'] = configuration.get('threads', 1) confi...
632deee051e789ed0cdb418ff23ff683db101522
633,004
def remove_vibrots(vibrot, modes): """ Removes specified modes from anharmonic constant matrix INPUTS: xmat - anharmonic constant matrix modes - the modes to delete from the matrix (with 1 being the first mode) OUTPUTS: xmat - anharmonic constant matrix with columns and rows deleted for sp...
64d37dd1713d533396ba511ad57a87f29d4de109
633,005
def does_entry_exist(conn, tweet_id): """ Check weather entry with exact tweet_id already exists :param conn: DB connection :param tweet_id: tweet_id to check :return: True if story already in db, else False """ cur = conn.cursor() cur.execute("SELECT * FROM tweets WHERE tweet_id=?", (tweet_...
e14af8997cdf69df5b02f67baa90904e76316c6f
633,006
import math from operator import mod def i4_uniform(a, b, seed): """Returns a scaled pseudorandom I4 scaled to be uniformly distributed between a and b. Seed is a non-zero integer.""" if seed == 0: print('I4_UNIFORM - Fatal error!') print(' Input SEED = 0!') seed = math.floor(seed) ...
5a8b49158a88d14ebe96e8691b1086e578d6b48c
633,007