content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def form_screenshot(tiles01, tiles2, attrs, palette): """ tiles01 -- list of 16-byte plane 0 and 1 tiles2 -- list of 8-byte plane 2 attrs -- attribute bitmap palette -- [c4, c5, c6], [c7, c8, c9] """ c4to6 = bytes(palette[0]) + bytes(3) c7to9 = bytes(palette[1]) if len(palette) > 1 else b'' c7to9 = c7t...
a7408b7b1037a37624c84707b1c783a6e2536dad
645,728
def interpolate(v1, v2, delta): """Interpolates between 2 arrays of vectors (shape = N,3) by the specified delta (0.0 <= delta <= 1.0). :param numpy.array v1: an Nd array with the final dimension being size 3. (a vector) :param numpy.array v2: an Nd array with the final dimension being ...
fcc0f18e9231c829f56162ce4f5c49565cfd5505
645,729
def convert_spaces(file_name): """Return file_name with all spaces replaced with "-".""" return file_name.replace(" ", "-")
78253cb1167b0f350b136fb62f665839dad7cc0e
645,730
def allowed_file(file_name_list: list) -> bool: """Return True if file extension of all passed file names is allowed""" allowed_extensions = {'png', 'jpg', 'jpeg', 'gif'} for file_name in file_name_list: if not file_name: return False if file_name.split('.')[-1].lower() not in al...
c517a9b33f4a35f3a19c341b90233b5091951e37
645,732
def parkes_error_zone_detailed(act, pred, diabetes_type): """ This function outputs the Parkes Error Grid region (encoded as integer) for a combination of actual and predicted value for type 1 and type 2 diabetic patients Based on the article 'Technical Aspects of the Parkes Error Grid': https:...
081e40ff960f02f0cd977b31cabbc8fadaa56bdb
645,733
import sys def calc_limits(data, dist=None, padding=0.25): """Calculate a suitable range for a histogram Returns: tuple of (min, max) """ dmin = sys.float_info.max if dist is None else dist.get('min', sys.float_info.max) dmax = s...
78de0a0c294f6f3dfdd0abd077ae9a5a43e98aa3
645,734
def synched_method(f): """ Synchronized method decorator. Like synchronized() decorator, except synched_method assumes that the first argument of the function is an instance containing a Lock object, and this lock is used for synchronization. """ def newFunction(self,*args,**kw): se...
af72c3397dd96095b2f3b7da1ffdf464673c2c10
645,736
def get_project(directory): """ Get the project in the given directory. Figure out the project name, and return a dictionary with the project name, the readable project path, the absolute project path, and a unique ID. """ namefile = directory.expanduser() / '.idea' / '.name' try: n...
b98914dd06eb69026d2e238a4d03fc4830350fea
645,737
from typing import Union from typing import Iterable import torch from typing import Tuple def recursive_to_device( iterable: Union[Iterable, torch.Tensor], device: Union[str, torch.device], ) -> Iterable: """Recursively puts an Iterable of (Iterable of (...)) tensors on the given device :param iter...
f64bd8d4976308215ce4a0eb3842db4e39abddea
645,738
def _get_actor_name(message): """Returns actor name by parsing incoming message. """ return str(message).split('(')[0]
55615e7593a14f8ab50f8ddbaabe659f0095a900
645,739
def format_timedelta(td): """ Format a timedelta Args: td (datetime.timedelta): A timedelta Returns: str: A string which represents the timedelta Examples: >>> import datetime >>> td = datetime.timedelta(days=3) >>> format_timedelta(td) '3 days' ...
c8bb60b05f4264966f51d347722599abe5bd3134
645,740
def get_bucket_name(gem_group, barcode, num_buckets): """ gem_group - integer barcode - barcode sequence num_buckets - desired number of buckets for gem group """ # NOTE: Python modulo returns non-negative numbers here, which we want return str(gem_group) + '-' + str(hash(barcode) % num_buc...
a33454150d024e99c99997ee92c57988e1311830
645,741
def key_from_string(key): """ Returns hex array from a string """ return [int(key[i:i + 2], 16) for i in range(0, len(key), 2)]
9949597daaf09eae391f56ff7d8364b583eedf6b
645,742
import argparse def parse_args(): """Parse arguments from the command line.""" parser = argparse.ArgumentParser("Cubic Testing in simulator.") parser.add_argument('--save-dir', type=str, default="", help="direcotry to testing results.") parser.add_argument('--delay', type=float...
9c4e20cffe03e4121e152e54fa35577cbb304f4f
645,743
import os def get_all_files(path, file_selector=lambda filepath: True, dir_selector=lambda dirpath: True, result=None): """ 遍历文件 :param path: 遍历目录 :param file_selector: 文件选择器 :param dir_selector: 文件夹选择器 :param result: 结果集 :return: 文件列表 """ result = [] if result is None else result...
d2c241b7252ac94a80b048520eebd146f587cda2
645,745
def combine_status_info(obj, status_info, attrs, separator='\n= {attr} ='): """ Combine status information from the given attributes. Parameters ---------- obj : OphydObj The parent ophyd object. status_info : dict The status information dictionary. attrs : sequence of str...
efc333e5f7083ed034db8bdb4b295ac99d84a849
645,746
def get_saturation(rgb): """Returns the saturation (hsl format) of a given rgb color :param rgb: rgb tuple or list :return: saturation """ c_max = max(rgb) / 255 c_min = min(rgb) / 255 d = c_max - c_min return 0 if d == 0 else d / (1 - abs(c_max + c_min - 1))
a5784ae01316a0d9d924f2144f22d842c6fbb229
645,747
def _get_segmentation_strategy(segmentation): """Get the baci string for a geometry pair strategy.""" if segmentation: return 'segmentation' else: return 'gauss_point_projection_without_boundary_segmentation'
267a10a7237b2d42f1988ad9e35eddc7febbe789
645,748
def selection_sort(array): """ Selection sort algorithm for sorting an array of ints. Returns sorted array. Running time = O(n2) to O(n2) """ A = array.copy() n = len(array) # Loop over the first to penultimate elements in array for i in range(0, n - 1): # Find smallest eleme...
a4ec5f4d3b073c6175db57ff23dc6a2fa413a1e4
645,749
def rgb_formatter(value): """ Formats iterable of 3 containing rgb values into CSS-valid output """ if n:= len(value) != 3: raise NotImplemented(f"Expected iterable with 3 items, got {n}") return f"rgb({value[0]}, {value[1]}, {value[2]})"
74990d05b53b4e09af4e5c99c667901469f0903c
645,750
import math def generalized_logistic_curve(t, a, k, b, eta, q, c=1): """See https://en.wikipedia.org/wiki/Generalised_logistic_function.""" return a + (k - a) / math.pow((c + q * math.exp(-b * t)), 1.0 / eta)
a01606ab053077a16072e0a6ed93613bb3f8d8c7
645,751
def custom_fields(minimal_fields): """A `fields` list with the three custom fields used by `custom_settings`""" return minimal_fields + [ {"id": "customfield_001", "name": "Team"}, {"id": "customfield_002", "name": "Size"}, {"id": "customfield_003", "name": "Releases"}, ]
3a11d5b0df77f82f587d97d4c8fcb5f90dec6c0b
645,752
def myair_request(req): """ Set to IP or hostname of myair controler """ myairaddress = "ac.home.internal" myairdic = { "login": "http://{1}/login?password=password", "status": "http://{1}/getSystemData", "power": "http://{1}/setSystemData?airconOnOff={2}", "settemp": "http:/...
81ddffa5c8dc604124dc7311192f3c76fdc1228a
645,753
def sort_by_inclusion(array: list) -> list: """ Сортировка простым включением. Суть: массив делится на две части - отсортированную и неотсортированную. На каждом шаге берется очередной элемент из неотсортированной части и "включается" в отсортированную часть массива. Максимальная временная сложност...
296a222d0a24b3fc85d1b6da6aec3e42358dc912
645,754
def quadFit(x, a, b, c): """ Quadratic fit function. """ return a*x*x + b*x +c
d7a14fe1fad30b5fa7782bbc6b96592979afac95
645,755
from datetime import datetime def to_timestamp(ts): """ Return a date/time in UTC from a timestamp """ return datetime.utcfromtimestamp(ts/1000.0)
e8c6c6b262d6d8b05dc936e3cdc1adab1ba4ccc7
645,756
def get_line_data(line, separator=None): """Converts a line scraped from a web page into a list. Parameters: - line, a line scraped (read) from a web page. The type is <class 'bytes'>. - separator (optional, default value None). If set, becomes the optional separator argument to th...
0b49108042e270ee3d0bda60cc75507dbfc8f60e
645,757
import os import sys def get_workdir(): """ get_workdir() -> workdir: [str] Returns the current workdir. """ return os.path.realpath(os.path.dirname(sys.argv[0]))
20f41074d41124cee8f37651890f0f51e1913ec9
645,758
from typing import Optional def cognito_user_id(event: dict) -> Optional[str]: """ Returns the User ID (sub) from cognito or None """ try: return event["requestContext"]["authorizer"]["claims"]["sub"] except (TypeError, KeyError): return None
4e1216ea0cfa4e21be03a8e95da14ce6c13888a9
645,759
import glob import os import logging import sys def find_vasprun_files(): """Search for vasprun files from the current directory. The precedence order for file locations is: 1. First search for folders named: 'split-0*' 2. Else, look in the current directory. The split folder names should a...
010e28f6b3afb233d3b99ee4a2175e6eedc23d5b
645,761
def nsec_to_usec_round(DatetimeNanos) -> int: """Round nanoseconds to microseconds Timestamp in zipkin spans is int of microseconds. See: https://zipkin.io/pages/instrumenting.html """ inttimestamp = DatetimeNanos.timestamp() * 1e9 return int((inttimestamp + 500) // 10 ** 3)
054fb56d733988a90ac8945e9bf1b733fb1a0572
645,762
def my_max(*values): """kappa:ignore""" return max(values)
828a9dfaedfdedc389a28ddc314d2dec777756b3
645,763
def _parse_seq_body(line): """ Ex: {()YVPFARKYRPKFFREVIGQEAPVRILKALNcknpskgepcgereiDRGVFPDVRA-LKLLDQASVYGE()}* MENINNI{()----------FKLILVGDGKFFSSSGEIIFNIWDTKFGGLRDGYYRLTYKNEDDM()}* Or: {(HY)ELPWVEKYR... The sequence fragments in parentheses represent N- or C-terminal flanking regions...
eae35cf5145e63e288815478f7d3a772a047ef11
645,764
def describe_selection(selection): """Create a human-readable description of the given selection Parameters ---------- selection: FileSelectionFile Returns ------- str """ return ( f"Selection containing {len(selection.selected_paths)} files:\n" f"Description: {se...
25c5ddc34d5f4d530022932b2940af420f385d40
645,765
import hashlib def part1(secret: str) -> int: """part1 solver""" number = 1 while True: key = secret + str(number) md5 = hashlib.md5(key.encode()).hexdigest() if md5.startswith('00000'): return number number += 1
10f257d0ac8e7a017ea3bdecae029f184dbfc098
645,766
import tempfile import atexit import shutil import os def filesystem_auth_info(auth_info): """Takes the `auth_info` given as PEM content, write the PEM content to temporary files, and returns an `auth_info` given as PEM files.""" auth_info_dir = tempfile.mkdtemp() atexit.register(lambda: shutil.rmtree(auth_in...
51a39d7944d814b694f7dfe189d7c64ed3bee46a
645,767
def check_complexity(check_bytes: bytes, complexity: int) -> bool: """Check the complexity of a bystream to see if it has the proper amount of leading 0 bits Args: bytes: byte stream to check for complexity bits complexity: number of leading bits that must be 0 in order to pass complexity Re...
79d227a59c288cd2b8c39c73f568bd3e5c430038
645,768
def ancestor(node_in_left, node, default_ancestor): """ The function ANCESTOR returns the left one of the greatest distinct ancestors of vil and its right neighbor. """ if node_in_left.ancestor in node.parentPointer.children: # if the ancestor is a sibling of the node return node_in...
1c2c903af21778a39a775bfb40647da4fbae12f4
645,769
def remove_new_lines_in_paragraph(article): """When we publish articles to dev.to sometimes the paragraphs don't look very good. So we will remove all new lines from paragraphs before we publish them. This means we don't have to have very long lines in the document making it easier to edit. Some elemen...
6f2123bebe966b4e3b03a0c4473628985b883f3f
645,770
def delta_percent(decimals=1): """A delta formatter to display the delta as a float with a given number of decimals. Args: decimals: The number of decimals to display. Returns: A delta formatter function (f(a,b)) returning (b-a)/a displayed as a percentage. """ return (lambda a, b...
a8c04264ab6f6289fce8642822254afb8155054a
645,771
def key_values_to_tags(dicts): """ Converts the list of key:value strings (example ["mykey:myValue", ...]) into a list of AWS tag dicts (example: [{'Key': 'mykey', 'Value': 'myValue'}, ...] """ return [{'Key': tag_key_value[0], 'Value': tag_key_value[1]} for tag_key_value in [key_value_o...
795f1b40ebfb5d7eb2aae14d52509ebed52a9650
645,772
import re def remove_url(text): """ Remove urls in the string Parameters ---------- text : str Returns ------- text: str """ return re.sub(r'http\S+', ' ', text)
592e83b68ffbf9a42ad591f17c7723310d60296d
645,773
def fixed(b1, b2): """ XORs two given sets of bytes, of equal length, together. """ # Ensure that byte arrays are of equal length. if len(b1) != len(b2): raise Exception('Byte arrays are not of equal length.') # XOR byte arrays together and return. return bytearray([x ^ y for x, y i...
60860b055f0db8c4c4bfe34afd75ddaf319dcd59
645,774
def assert_(condition, message=None, *args, val=None): # pylint: disable=keyword-arg-before-vararg """ Return `value` if the `condition` is satisfied and raise an `AssertionError` with the specified `message` and `args` if not. """ if message: assert condition, message % args else: ...
e3a24b51c5cce487610786739d16c88ccb1da1e3
645,775
import sys def mask_sequence(sequence, coverages, subs, mincov): """Mask positions with low or no coverage in the input FASTA.""" masked_seqs = {} for accession, vals in coverages.items(): bases = [] coverage = vals['positions'] for i, cov in enumerate(coverage): i...
011533621b495a3536413c98253e8bc555a50b9b
645,776
import warnings def _enquire_check_deprec_args(reverse, kwargs, methodname): """Check the keyword arguments to one of the enquire set_sort_* methods. """ if reverse is not None: if 'ascending' in kwargs: raise TypeError('Only one of "reverse" and "ascending" may be specified') ...
6762d27cf120f45fdb9b0c4d17443c6d99823105
645,778
def coerce_to_list(data, key): """ Returns the value of the ``key`` key in the ``data`` mapping. If the value is a string, wraps it in an array. """ item = data.get(key, []) if isinstance(item, str): return [item] return item
00cf50d81f7a7513deb4593d3a236639353079af
645,779
import struct def writeRegisterRequestValue(data): """Return the value to be written in a writeRegisterRequest Packet.""" packet = struct.unpack('>H', data[10:]) return packet[0]
f21cc8bd9407aa758d18fd1a095c619a7030fd1f
645,780
def media_saltos_lista(saltos): """Receba uma lista com os saltos de um atleta e calcule a média dos seus saltos. """ return round((saltos[0] + saltos[1] + saltos[2] + saltos[3] + saltos[-1]) / 5, 2)
0a5e14b55dfa79e015a11c0c08edcfea00385619
645,782
def dict_to_r_vec(d): """Convert a skylark dict to a named character vector for R.""" return ", ".join([k + "=" + v for k, v in d.items()])
59458064faa2341411b4fdd9168752a326e9c66b
645,783
def bbox_r(width, height, *xyxy): """" Calculates the relative bounding box from absolute pixel values. """ bbox_left = min([xyxy[0].item(), xyxy[2].item()]) bbox_top = min([xyxy[1].item(), xyxy[3].item()]) bbox_w = abs(xyxy[0].item() - xyxy[2].item()) bbox_h = abs(xyxy[1].item() - xyxy[3].item()) ...
60ec222a3d94c8f7061d3523b4a39683df8dd48b
645,784
def find_any(words, case_sens = False): """Tests if any of the given words occurs in the given string. This filter is case INsensitive by default. """ if not case_sens: used_words = [w.lower() for w in words] else: used_words = words def apply_to(s): if not case...
f94b168fcfe025ce961de59ef03151ee05bb8921
645,785
def parse_consts(u_consts): """ Unicorn "consts" is a python module consisting of a variable definition for each known entity. We repack it here as a dict for performance. """ consts = {} for name in dir(u_consts): if name.startswith('UC_'): consts[name] = getattr(u_consts, n...
5763910b07819e69d65e8d32ebf16c95337ff78e
645,786
def is_iterable(obj): """ Check if the object is iterable. """ has_iter = hasattr(obj, "__iter__") has_get_item = hasattr(obj, "__getitem__") return has_iter or has_get_item
92a8c6c4203f00b0ed535bb6a4688d07d33e5f8b
645,787
import numpy as np from typing import Any def is_numerical_scalar(n: Any) -> bool: """ Check if the argument is a numerical scalar that is writeable to TensorBoard. There are two cases of numpy "scalars". The first is a true numpy scalar, and the second is an array scalar that has 0 dimensions. Both ...
f81002b9fa922533968da07b5c50e9e8d25d8f4e
645,788
def _decode_ctrl(key): """ Convert control codes ("\x01" - "\x1A") into ascii representation C-x """ assert len(key) == 1 if key == '\n': return 'RET' code = ord(key) if not 0 < code <= 0x1A: # Not control code return key letter = code + ord('a') - 1 return ("...
cd30c728903dae557f1eeef30bd73caae2da718a
645,789
def start_gamma2_imp(model, lval: str, rval: str): """ Calculate starting value for parameter in data given data in model. For Imputer -- just copies values from original model. Parameters ---------- model : Model Imputer instance. lval : str L-value name. rval : str ...
80c1949be96498437708b544ed87c6f31c142070
645,790
def get_yes_no_input(question_text): """ :return True/False as answer to the passed yes-no question""" confirm = "" while confirm.lower() not in ["y", "n"]: confirm = input(f"{question_text} [y/n]: ") return confirm.lower() == 'y'
a56ff8f98f8072fbc5ccb25673e940df8fb2b548
645,791
def usage(progname): """ print program usage """ print(("Usage: %s /path/to/tables " "/path/to/generated output[_amalgamation.cpp]") % progname) return 1
1da5da77c98f8d0a1b84961caec1de7041e0cf5d
645,792
def _handle_tekton_custom_task(custom_task: dict, workflow: dict): """ Separate custom task's workflow from the main workflow, return a tuple result of custom task cr definitions and a new workflow Args: custom_task: dictionary with custom_task infomation, the format should be as below: { ...
eaba33fb61f79e2c9e4c27290f42502200ca40da
645,793
def agent_portrayal(agent): """ Properties of the agent visualization. """ portrayal = {"Shape": "circle", "Color": f"rgb({140-(agent.speed*3.6)},{50+(agent.speed*3.6)},0)", "Filled": "true", "r": 4} return portrayal
0053c055266f632a56b414b30d098d5c4396d246
645,795
def sortname(f, dropExtension=False) : """Partial url to sort by, which strips out the filename if the filename is index.html. Keyword arguments: f - Filename with path dropExtension - true to drop extensions of .html from the filename when sorting """ if len(f) >= 11 and f[-11:] == "/index...
3176c05367de78bba998de6f0bf657d3312e7970
645,796
from typing import Dict from typing import List def get_place_list(tweet_place: Dict) -> List: """Extract place from tweet metadata.""" pattrs = [ "id", "url", "place_type", "name", "full_name", "country_code", "country", ] if tweet_place: ...
fc926f1cc8977fc8c8a299b23b4e3deb9539be7a
645,797
def get_comp_corp_url(code): """ Parameter - code[str] : the company code corresponding data Return - url[str] """ url = 'https://comp.fnguide.com/SVO2/ASP/SVD_Corp.asp?pGB=1&'\ 'gicode=A' + code + '&cID=&MenuYn=Y&ReportGB=&NewMenuID=Y&stkGb=701' return url
c49e89e75b123770434fcf563631c505bb915dd9
645,798
def args(*args, **kwargs): """Decorator which adds the given args and kwargs to the args list of the desired func's __dict__. """ def _decorator(func): func.__dict__.setdefault('args', []).insert(0, (args, kwargs)) return func return _decorator
8fd04f26cf1bb4021584c0b347d7f1e1bd71d3d7
645,799
import os import yaml def read_config_developer_file(cfg_file=None): """Read the developer's configuration file.""" if cfg_file is None: cfg_file = os.path.join( os.path.dirname(__file__), 'config-developer.yml', ) with open(cfg_file, 'r') as file: cfg = ya...
b5a8a0ef2e01b8fcf0c567640b9e921e8c435bf0
645,800
import copy def delta(a, b): """Find all keys and values in b not in a""" d = {} for k in b: if k not in a: d[k] = copy.deepcopy(b[k]) elif isinstance(a[k], dict): if isinstance(b[k], dict): dd = delta(a[k], b[k]) if dd != {}: ...
ac53342d5973687800e510d9262ef6d4ae71a755
645,801
def stringfromtime(t, accuracy=4): """ :param t : Time in seconds :returns : Formatted string """ m, s = divmod(t, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) components = [] if d > 0: components.append(f"{int(d)} day" + ("s" if d != 1 else "")) if h > 0: compo...
83e5bca6be984946c7b94aa122284e56e33f412b
645,802
from pathlib import Path from typing import Dict from typing import Any import json def read_json_file(json_file: Path) -> Dict[Any, Any]: """Parse the application JSON file into native dict :param json_file (Path): JSON file to parse""" with open(json_file, 'r') as f: return json.load(f)
cae03c07969adca8329afe55cc7940ba8d959ec3
645,803
from enum import Enum from typing import Dict from typing import Any def enum_to_dict_fn(e: Enum) -> Dict[str, Any]: """ Converts an ``Enum`` to a ``dict``. """ return { 'name': e.name }
13205618bedfb25a5912ec5bb29aacb0e12a53f5
645,804
def cada(graph, partition): """Algorithm proposed by Hellig et al. 2019. A Community-Aware Approach for Identifying Node Anomalies in Complex Networks Parameters: graph - A directed graph representing the network partition - A dictionary containing for each node_id to which community it belo...
b792e25524584fc804080df43b60717a5df13a67
645,806
def blksLeftStakeWindow(height, netParams): """ Return the number of blocks until the next stake difficulty change. Args: height (int): Block height to find remaining blocks from. netParams (module): The network parameters. Returns: int: The number of blocks left in the current...
b0dcfc6747aec4a7c9e580a24dda80a32b9e5f03
645,807
def _normalize_columns(columns: list[str]) -> list[str]: """Normalize column names.""" new_columns = [ "".join([substr.capitalize() for substr in col.split("_")]) for col in columns ] return new_columns
26e2f7922612d883de51a9164c819a31161eba81
645,808
import json def _parse_callout_ffdc(version: int, data: memoryview) -> str: """ Parser for callout list FFDC. """ # The data in this section is simply a string representation of JSON data. # When the JSON data is written to the section, it will include a null # character at the end because it...
6d69caff37cd28b6da596670503924dcb85adb18
645,809
import torch def numpy2tensor(x): """Transter type numpy.ndarray to type torch.Tensor and change the precision to float Write in function so that can be used in functional programming :param x: The numpy data to be transformed :type x: numpy.ndarray :return: The torch data after transformatio...
38212f1f124f73fd1a26030d31348ae714824e9f
645,810
import ctypes def qwidget_winid_to_hwnd(id): """ Convert the winid for a qtwidget to a HWND :param id: qtwidget winid to convert :returns: window handle """ # Setup arguments and return types ctypes.pythonapi.PyCObject_AsVoidPtr.restype = ctypes.c_void_p ctypes.pythonapi.PyCObject_AsVo...
e1053ec7f570e9af1f2454880238a5daa6886e78
645,811
from typing import Counter def sort(sequence, values): """ Sort using the counting sort algorithm. sequence -- the sequence to sort values -- all the possible values of elements in the sequence (values must be in sorted order) Returns a list with the given sequence's elemen...
611dd6339751b0969a6e42c3c5521d0b17d9a64f
645,812
def abstract(soup): """ Find the article abstract and format it """ abstract_soup = [] # Strip out the object-id so we only have the text try: abstract_soup = soup.find_all("abstract") except(IndexError): # No abstract found pass # Find the desired abstract node, <abstract> abstract_node = None for ta...
542bf303e6a8e10bc529116e4e34042db6f53d96
645,813
def always(_): """Predicate function that returns ``True`` always. :param _: Argument :returns: ``True``. """ return True
2754168d1ae203864d457552dd1aa4eab5dca51b
645,814
def sanitize_page_number(page): """A helper function for cleanup a ``page`` argument. Cast a string to integer and check that the final value is positive. If the value is not valid returns 1. """ if isinstance(page, str) and page.isdigit(): page = int(page) if isinstance(page, int) and (...
9dd98ce4461cd3e2883c93f5f6bb9469cbff4678
645,815
import re def read_and_prep_file(filename): """Read contents of a file,remove html tags Args: filename(str): a filename with full path to be loaded Returns: text(str): a string containing all words We read in all lines in a file, join into one long string, remove all html, turn any character that isnt...
c8ae164c6dbea04c5d056f76b8bc71bce3d12fed
645,816
def startpoint(xyz): """ First point of the track Parameters ------------- xyz : array, shape(N,3) Track. Returns --------- sp : array, shape(3,) First track point. Examples ---------- >>> from dipy.tracking.metrics import startpoint >>> import numpy as np ...
3ff5a917e7c3947a80c7be56eb4a80a41d245f11
645,817
def key_sort(data): """ sort by dict key and return sorted list :param data: dict to sort :type data: dict :return: sorted list of k,v tuple :rtype: list """ return [(k, data[k]) for k in sorted(data.keys())]
cfcab10805dcd7d8a69115ef3fbe51225f0c4d28
645,818
import re def diff_pip(cur: list, need: list): """ :param cur: 当前环境 :param need: 所需依赖 :return: (不满足,满足但版本旧) """ pack_part = "(.*)[>|=]=.*" v_part = "[>|=]=(.*)" cur_store = {} dissatisfy = [] version_less = [] for i in cur: i = i.replace(" ", "") if "=" i...
4535544e8b7339bd042ee7e34ed49f9811a3fe39
645,819
def sort_words_case_insensitively(words): """Sort the provided word list ignoring case, one twist: numbers have to appear after letters!""" char = [c for c in words if not c[0].isnumeric()] num = [n for n in words if n[0].isnumeric()] sorted_words = sorted(char, key = lambda word: word.lower()) +...
d1cea948f3b00149f24cd569c7018791a2071511
645,820
import argparse def get_parser(): """Create and return a parser (argparse.ArgumentParser instance) for main() to use""" parser = argparse.ArgumentParser(description='Common User Passwords Profiler') group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-i', '--interactive'...
89ea471a03460908a4b00a5fe917585c5367e3c7
645,821
def extract_line(text_list, keyword, vname, col): """Takes a list of text and for every line containing the keyword, creates a dictionary where vname is key and the word at col is the value. Used for extracting one value from output file. """ dictionary = {} for line in text_list: if keyword in line: diction...
dccb2c94f5b24d555d317e62e4b362e66fe5cc5c
645,823
from typing import Dict from typing import List from typing import Any import os import glob import json def project_abis(project_dir: str) -> Dict[str, List[Dict[str, Any]]]: """ Load all ABIs for project contracts and return then in a dictionary keyed by contract name. Inputs: - project_dir P...
2623985afea5df228116d9063f8c208e378aa888
645,824
import argparse import pathlib def parse_argc(): """ Parse and return command line arguments. """ parser = argparse.ArgumentParser() parser.add_argument( "catalog", type=str, help="Input catalog." ) parser.add_argument( "network", type=str, ...
18a61f10146d0864a60b0034cb2b282870aab24e
645,825
from typing import List def _parse_celex_row(line: str) -> List[str]: """Parses a single line of CELEX.""" return line.rstrip().split("\\")
90fedf49ce6fc7c03bdd4832dc579cfcc071d862
645,827
def update_event_visibility(review): """ Update event's `is_published` flag according to review :param review: EventReview object :return: event review updated object """ review.event.is_published = False if review.is_approved: review.event.is_published = True review.event.save...
42c38cfed7c62b1ac7cbfc9d526139265bf856ea
645,828
def count_visible_characters_of_the_pyramid(characters): """Return the count of all characters, that are visible from outside the pyramid.""" return -1 if not characters else (len(characters)*2-1)**2
35d42bcc4dd92c24c874f2af378fcada0e564105
645,830
import os def check_db(): """Check to see if a database exists""" return os.path.isfile(os.environ['DBPATH'])
0770d0895f3173bc1ed09296ee680befd8522bae
645,831
import subprocess def get_executable_path(executable): """Return the path to the executable Parameters ---------- executable: str name of the executable """ try: path = subprocess.check_output(["which", "%s" % (executable)]) path = path.decode("utf-8") except Excep...
df8da0e5cea1aef550b8eab994f082aef765bff2
645,832
import hashlib import uuid def make_tid(): """Return a new random string""" return hashlib.md5(str(uuid.uuid4()).encode()).hexdigest()[:8]
499dcbeaaa9c4eaee782a66892c273ea0a1cf15f
645,833
def hierarchical_merge(dicts): """Merge a list of dictionaries. Parameters ---------- dicts: List[Dict] Dicts are given in order of precedence from lowest to highest. I.e if dicts[0] and dicts[1] have a shared key, the output dict will contain the value from dicts[1]. Retur...
f708b72667ad7495d8bcb9282028e4ea18c4720b
645,834
import requests import logging import time def send_api_request(method, url, status_code=None, nb_retry=5, wait_time=10, **kwargs): """Constructs and sends a :class:`Request <Request>`. :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``,...
167707c157394c0ddb9485da965ee564317a8000
645,836
def wrapper(func, *args, **kwargs): """ 一个装饰器,用来把有参数的函数转换为没有参数的函数 :param func: func :param args: list :param kwargs: dict :return: func """ def wrapped(): return func(*args, **kwargs) return wrapped
87867b15401d637fc8b020e2a51a59547885519f
645,837
def check_if_all_tss_are_bad(tss): """ Check if all time series in a list are not good. 'Not good' means that a time series is None or all np.nan """ def bad(ts): return True if ts is None else ts.isnull().all() return all([bad(ts) for ts in tss])
a8113b13f08b6df1273213d3a938d7b687443576
645,838
def get_item(context, item): """Return the item instance of type item.""" item_instance = context.get("reports") if item == "reports" else context.get(f"report/{context.uuid['report']}") if item != "reports": item_instance = [ report for report in item_instance["reports"] if report["repo...
bbcebefccb0f8eea2798e6300fbf8a4068ef7a06
645,839