content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def removeDuplicatesFromListOfDicts(list_of_dicts, key): """ remove duplicates from a list of dicts based on key, returns the list in the format it arrived. only checks key. Does not check anything else. """ ulist = [] newlist = [] dupecount = 0 for line in list_of_dicts: if...
63bd7fb0814843ad4d75fe7900a4e046ebd38ff7
629,328
import inspect def method_name(caller_depth=0): """ Returns the name of the caller method. """ # Note: inspect.stack()[0][3] would return the name of this method. return inspect.stack()[caller_depth+1][3]
f90997a9e31a1de16edc7c87adf643a013965ee1
629,329
import math def nth_root(n: float, p: float) -> float: """Calculate nth root while handling negative numbers.""" if p == 0: # pragma: no cover return float('inf') if n == 0: # Can't do anything with zero return 0 return math.copysign(abs(n) ** (p ** -1), n)
feba6a402e29417ca5d5cd35ea2f09cdb4b23027
629,330
def get_version(): """ Returns DEV as version. Just a placeholder while building the web docker image, will be overwritten by mounted docker volume. :return: the version identifier """ return 'DEV'
fa3654b3ce62617c9b69c8459b6aea4596adb126
629,331
import logging import yaml import sys def retrieve_assemblies_dict(yaml_path): """Retrieve dict of genomic assemblies to create test sets from. :param yaml_path: Path to yaml file, keyed by NCBI:txid and valued by genomic assemblies Return dict, keyed by NCBI:txid and valued by list genomic assemblies""...
486013fff04c8d4fb563451181abfc2a9b9937ba
629,332
def _is_earlier(t1, t2): """Compares two timestamps.""" if t1['secs'] > t2['secs']: return False elif t1['secs'] < t2['secs']: return True elif t1['nsecs'] < t2['nsecs']: return True return False
d726384c72dd8e702a4251346b3e6b8a339d597c
629,333
def eq_tokens(token_sequence1: str, token_sequence2: str) -> bool: """Returns True if bothe token sequences contain the same tokens, no matter in what order:: >>> eq_tokens('red thin stroked', 'stroked red thin') True >>> eq_tokens('red thin', 'thin blue') False """ retu...
06e51bf34e063ae8d3b9724f054764b61a043d01
629,334
from typing import List from typing import Tuple from typing import Any def simple_producer(key, value) -> List[Tuple[Any, Any]]: """simple_producer A function that returns the key,value passed in for production via "KafkaProducerOperator" :param key: the key for the message :type key: Any :param val...
1c04821f7db789c73be4533f60206e5196ab98d4
629,335
import os def get_default_path(): """Function to construct default path to OutputData folder This function constructs the default path to the OutputData folder """ home_path = os.path.expanduser('~') teaser_default_path = os.path.join(home_path, 'TEASEROutput') # directory = os.path.dirnam...
2ce1a563276d6fcf30acb718dbc023d4e48f20a3
629,336
import torch def process_data(file_name, tokenizer, max_size=None): """Reads the line of a file and segments the lines using the tokenizer Args: file_name (str): Full file path tokenizer (:obj:`WMT16Tokenizer`): The tokenizer to use max_size (Optional[int]): The maximum size of result...
19244f25bec78786badea778f149e8991e9a318a
629,337
def get_out_dir(request): """ Get the temporary output directory for writing files to """ return request.fspath.join("..") + "/tmp"
e178e91434c04bd97d7c0fbdc0d0ea379d525059
629,339
def string_to_bytes(string): """ Convert a string to NULL-terminated ASCII string. """ return bytearray(string, encoding='ascii') + b'\x00'
0c66ba9f9364cc02e74473450e785b887a6f5cec
629,340
def getFrameWithCheckSum(frame): """Check if a frame is valid.""" datas = frame.encode("ascii") computed_checksum = (sum(datas) & 0x3F) + 0x20 return (frame + " " + chr(computed_checksum) + "\n").encode("ascii")
5182921330500d6442f5db7cd3922629eabeb360
629,341
def lock_fn_timeout(old_fn): """ Decorator for a function which needs a lock for shared encode/decode operations """ def new_fn(self, *args, **kw): self.lock.lock(spin=0, timeout=5) self.lock_acquired = True try: r = old_fn(self, *args, **kw) finally: ...
d31c02968e9a1d5f0a17160c63fec21effa75a88
629,342
import torch def batch_jacobian(h1, h2): """Get batch-wise jacobians of h2 with respect to h1. Both must have size (b, ?), and output will be of size (b, |h1|, |h2|) Assuming computation graph has no dependence of h2[i,...] on h1[j,...] unless i==j. This allows us to pass a lot of vectorization over ...
57becdd42f858eb492e97c6fd9ffc2ab537a4819
629,343
def _cache_run_stop(run_stop, run_stop_cache): """Cache a RunStop document Parameters ---------- run_stop : dict raw pymongo dictionary. This is expected to have an entry `_id` with the ObjectId used by mongo. run_stop_cache : dict Dict[str, Document] Returns ----...
07aae4e43a0e089d34a60326f0ed3525d9f62b01
629,345
def dbl_linear(n): """Return number from dbl_linear list at index.""" u = [1] en = n while en > 0: u.extend([u[0] * 2 + 1, u[0] * 3 + 1]) u.pop(0) u = sorted(list(set(u)))[:n + 1] en -= 1 return u[0]
a04da01526be64749b7c526958fdea9c22675375
629,346
import os def get_cwd(): """ What directory should we cd to before running eslint? """ cwd = os.environ.get('TM_PROJECT_DIRECTORY', None) if not cwd: cwd = os.environ.get('TM_DIRECTORY', None) return cwd
bd60315f7fe41b5c5a6f767fa5134d616e49120b
629,347
def isupper(char): """ Indicates if the char is upper """ if len(char) == 1: if ord(char) >= 0x41 and ord(char) <= 0x5A: return True return False
f780c984bb940e3081091fcface6350367f68794
629,348
def isheader(string): """ Check if a string looks like a star header line. Args: string (str): line of a star file Returns: true if the line looks like a star file header lines false if the line is expected to be a star file data line. """ try: string = string.de...
1f8a9ff2ec7ee24818c0f7bbfcd90ed5bf74fbf8
629,349
def tuple_setter(tensor, idx_tuple, val): """ Sets a tensor element while indexing by a tuple""" tensor_ = tensor for el in idx_tuple[:-1]: tensor_ = tensor_[el] tensor_[idx_tuple[-1]] = val return tensor
269826fe5757b63214d4cca7e37a25a1eb2ba454
629,351
import operator def divide_rounded(input_dict, total, dp=2): """Divides quantities into a specified total, rounding to a specified number of d.p. while ensuring that the sum of the quantities equals the specified total. We do all maths having multiplied by 10^dp to reduce rounding issues (whole n...
c7a6bc70e3e20886393d682b45a7756089d8499a
629,352
def is_ask_help(text: str) -> bool: """ A utility method to tell if the input text is asking for help. """ sample_phrases = [ "help", "help me", "i need help", "i'm lost", "i am lost" ] text = text.strip() return any(text == phrase for phrase in sample_phrases)
994ac984c69b77c869f0f28c5ee77a082e76c909
629,353
def get_methods(callback): """ Return a list of the valid HTTP methods for this endpoint. """ if hasattr(callback, 'actions'): return [method.upper() for method in callback.actions.keys()] return [ method for method in callback.cls().allowed_methods if method not in ('OPTION...
a55e624c20d8540ded61414683af518dd3e83a9d
629,354
def to_bit_array(byte): """Gets 8 bits from a byte.""" arr = [] curr = byte for i in range(8): arr.append(curr % 2) curr = curr // 2 return list(reversed(arr))
fc9f07cc1aa5d15072729952d3577836811f8d1e
629,355
import re def parse_item_info(text): """ Parse item info (from clipboard, as obtained by pressing Ctrl+C hovering an item in-game). """ m = re.findall(r'^Rarity: (\w+)\r?\n(.+?)\r?\n(.+?)\r?\n', text) if not m: return {} info = {'name': m[0][1], 'rarity': m[0][0], 'type': m[0][2]} ...
b9287b877692e0d241160d38588696f5f3ba957f
629,356
def abweichung(value, lit): """Returns diveation of an experimental value from a literature value.""" return '{:.3f}'.format((lit - value.nominal_value) / lit * 100) + "%"
2f8e911d570015083f5610c14c339415921f7ffe
629,357
def minus(first, second): """The difference of two numbers""" return first - second
3ef4b455558a91a5831ac8cc9067055ab09942c3
629,359
import math def _find_poles(damping, freq): """Find roots of equation s^2+2hws+w^2=0 Parameters ---------- damping: float Damping constant. freq: float Angular frequency. """ real = -damping*freq imaginary = freq * math.sqrt(1 - damping*damping) return real, imag...
53be0f5e645163395f2ab9ec167e500adab6f8da
629,360
def generate_stripe_description(opportunity) -> str: """ Our current code populates the Description field of recurring donations and opportunities when those are created. Those descriptions get passed on to Stripe when the card is charged. But we have at least two cases where the Description field c...
086ac9ebe100404a6b79e6b412cafa4e52a272e7
629,361
import torch def compute_output_gradient_times_vec_intermediate_with_beta( relu_network, beta, z0): """ Similar to compute_output_gradient_times_vec_intermediate(), but the value of beta (the activation of the ReLU unit is given) """ num_linear_layers = int((len(relu_network) + 1) / 2) ...
82d5c4825db6a68a0f813b3d914e119f64d7df63
629,364
def is_connective(char): """ Is the given character a logical connective (one of the pretty printed ones) :param char: :return: """ return char in [u"¬", u"∧", u"∨", u"→", u"↔"]
acbf36e2e450569153ef0c5d57ab7a016880c2b2
629,365
def pot_harmonic(x, x0, k): """ pot_harmonic(x, x0, k) Returns harmonic potential from displacememt of x away from x0 """ return k * (x - x0)**2
9b2ad50b848baf2b4354d8820f5e7f0ae9cee39f
629,366
def int_to_mac(integer): """ Converts a an integer into a mac address, with `:` notation. Arguments --------- integer: int Returns ------- str """ first = "{:012x}".format(integer)[::2] second = "{:012x}".format(integer)[1::2] return ':'.join(a + b for a, b in ...
d4374e56a20ce444070679ff4830630302a8ccdd
629,367
import string def noun_to_verb(sentence: str, index: int) -> str: """ :param sentence: str that uses the word in sentence :param index: index of the word to remove and transform :return: str word that changes the extracted adjective to a verb. A function takes a `sentence` using the vocabu...
35984fd232e95c3afcefcfc5ef123e3bb50951fd
629,368
import typing import hashlib def _hash_value(value: typing.Any = "") -> bytes: """Hashes a value using the sqlalchemy API.""" if isinstance(value, str) and value == "": return b"" return hashlib.sha256(repr(value).encode()).digest()
e1f4dfa79a185d02ce9390f5513d7c6d728b016a
629,370
def oct_to_ubin(oct_str, num_bits): """ Method converts hex string (ndarray) to binary string. """ format_str = '0{}b'.format(num_bits) return format(int(oct_str, 8), format_str)
eea4f6e716aa87493bfb7b618b8f0bf2b12cdbee
629,371
def coord_2_id(x, y): """Give the pinID from the x,y coordinate.""" return (34 - y) * 34 + x
e02c03f0761ea7adfb6d50332ded3b0a82c2b016
629,372
from typing import Dict from typing import Any from typing import Mapping import itertools def is_cleanly_mergable(*dicts: Dict[Any, Any]) -> bool: """Check that nothing will be overwritten when dictionaries are merged using `deep_merge`. Examples: >>> is_cleanly_mergable({"a": 1}, {"b": 2}, {"c": 3...
1f666a79952c4a667ff3d27c92b1dae816c33ed6
629,373
import logging def getLogger ( name = 'ostap' , format = '' , level = 1 , stream = None ) : """Get the proper logger >>> logger1 = getLogger ( 'LOGGER1' ) >>> logger2 = getLogger ( 'LOGGER2' , level = logging...
e062448821e26974a469a4bd9b91dac91f111a6b
629,374
def emission_probability(symbol, word, emission_probabilities, symbol_counts): """ Takes a symbol, a word, a nested dictionary of emission probabilities, and a dictionary of symbol counts and returns the emission probability for that symbol and word If the word has not been encountered in the traini...
df41ef4bbb01e993416c8e5e581e44b2a5292fa3
629,375
def parse_to_multiple_percentages(value, fields): """ Handles QC with multiple percentage values like 25% - 23% - 27% - 25% """ split_value = [float(i.strip(" %")) for i in value.split("-")] values = dict(zip(fields, split_value)) return values
71dcb15b2d60c44b21322b71635c7c1137d91762
629,376
def py_edit_distance(s, t): """ Pure-Python edit distance """ m = len(s) n = len(t) costs = list(range(m + 1)) for j in range(1, n + 1): prev = costs[0] costs[0] += 1 for i in range(1, m + 1): c = min( prev + int(s[i-1] != t[j-1]), ...
af6f1475da179a91aa987dff52ea2ad0d8265569
629,377
def _make_qa_class(type_class, mode_class, p_name, p_description, p_software): """Create and return a new class to represent a QA metric""" class QA(type_class, mode_class): name = p_name __doc__ = p_description software = p_software QA.__name__ = p_name return QA
e37f36a5bce075e9572e34437bc13525886219bf
629,378
import re def __highlight_fuzzy_string(target: str, search_value: str) -> str: """ Highlight every existence of target in the search_value with the <em> tag. This <em> tag can be replaces with any other tag. :param target: the haystack to search in :param search_value: the needle to search for ta...
46b1d6d8d02a920faa4338be62311d3b62af960f
629,379
def get_right_of_equals(line): """ Returns the text to the right of an equals. DESCRIPTION: Get the text to the right of an equals sign. KEYWORD ARGUMENTS: line (str): the line to search. RETURNS: str: the text to the right of an equals sign. """ tmpline = line.split(...
a324b6288bb4a493fae3d81746d4aed12b48ce98
629,380
import requests import time from typing import List def get_price(id_: str, unitList: List[str], verbose: bool = False) -> dict: """ Fetch price from CoinGecko API """ while True: r = requests.get('https://api.coingecko.com/api/v3/simple/price', ...
5ddf08e24e2f9d0d53e088cc205f48a7fc424628
629,381
def rseq(t, y, en, l): """Radial Schrödinger equation as system of 1st order ODEs.""" y1, y2 = y y1d = y2 f = l * (l + 1) / (t ** 2) - 2 * (en + 1 / t) y2d = f * y1 return [y1d, y2d]
7955990bafbd85d784b3ca8ed036f2848de8b652
629,382
def validate_store_data(data): """ Parameters ---------- data: dict data from stored dcc.Store component Returns ---------- data_in: bool Determine if there is dataframe data in the data diction """ if data and 'df' in data and data['df'] is not None...
9f574473382c648d5e8228c2807c41608f252182
629,383
def url_file_name(url: str) -> str: """ Extract file name from url (last part of the url). :param url: URL to extract file name from. :return: File name. """ return url.split('/')[-1] if len(url) > 0 else ''
38ea970f26f439119ad8bb8312ff9e393bf7e431
629,384
import numpy def gauss2d(par,varcov,n=10000): """ Calculates random numbers drawn from the multinormal distribution in two dimensions. Computes also the probability associated with each number that can be used to computed confidence levels. Arguments: - par : array or list with structure [par0, par1, par2, ...] wi...
dc85c909e5b3599d65efaca3543646dcb1b61526
629,385
def _add_box_and_whiskers(canvas, quantiles, limits): """Add a box and whiskers to the canvas""" for jj in range(5): canvas[quantiles[jj], limits[0] + 1 : limits[2]] = 20 canvas[quantiles[0] + 1 : quantiles[1], limits[1]] = 22 canvas[quantiles[3] + 1 : quantiles[4], limits[1]] = 22 canvas[...
5032a40edad1d99c4818e9c1e020375312c6797c
629,389
def convert_kicad_coor(edif_pt): """ KiCAD schematic coordinates are 10 times EDIF Y axis is flipped """ scale = 10 return [edif_pt[0] * scale, -edif_pt[1] * scale]
ee4b5e5d2aa5a50fac73cd1d4a5e4ce604ea5711
629,390
import argparse import sys import os def default_argument_parser(): """ Create a parser with some common arguments used by fastreid users. Returns: argparse.ArgumentParser: """ parser = argparse.ArgumentParser(description="fastreid Training") parser.add_argument("--config-file", defaul...
c7a63e48bc482bacca6d390705088781bb4d2484
629,391
def quotePath(path): """quote overlap of solr reserved characters and those allowed in zope ids (see OFS.ObjectManager.bad_id)""" if path.endswith("/"): path = path[:-1] for reserved in "/-~()": path = path.replace(reserved, "\\%s" % reserved) return '"%s"' % path
57d7201e12840ae5a5a730d6a2e1057931a9df04
629,392
def fake_request(*responses): """ Creates a request function that returns the supplied responses, one at a time. Making a new request after the last response has been returned results in a StopIteration error. """ iterator = (response for response in responses) def request(method, url, **kwargs...
e5a9a190129587f0c76fcabddfaca487fab3bd0c
629,393
def rovarspraket(english): """Translates input to rovarspraket""" for low, upper in zip("bcdfghjklmnpqrstvwxyz", "BCDFGHJKLMNPQRSTVWXYZ"): english = f"{upper}o{low}".join(f"{low}o{low}".join(english.split(low)).split(upper)) return english
7d234968c1edd1461b64359697d8d4fef592fcec
629,394
def delete_outliers(selected): """ Parameters ---------- selected : dataframe Returns ------- None. 96320 Rovaniemi teollisuusalue 70210 Kuopio sairala-alue 06850 Neste Kulloo terminaali 01720 Petikko suuri kauppa-alue 00290 Meilahden sairaala-alue 01530 Helsi...
6ae9c3c0e0c24606101245a140a5a2c8ec6df3c5
629,395
import re def iscrcard(value): """ Return whether or not given value is a credit card. If the value is a credit card, this function returns ``True``, otherwise ``False``. Examples:: >>> iscrcard('375556917985515') True >>> iscrcard('5398228707871528') False :par...
d77e6f15255f57e83a295f875c02ea6a7643d37c
629,396
def compute_scale_factor(height, size): """ Compute gallery conversion scale factor as a percentage. """ landscape = True source_width = size[0] source_height = size[1] if source_width < source_height: landscape = False if landscape: return height/source_height * 100 ...
18fb5f160c893d685248d88059814da50064e369
629,397
from typing import List import torch def jagged_fixed_odeint(f, x, t_span: List, solver): """ Solves ``n_segments'' jagged IVPs in parallel with fixed-step methods. Each sub-IVP can vary in number of solution steps and step sizes Returns: A list of `len(t_span)' containing solutions of each IVP compute...
f2c3711f079008a14349f0a3b84802c8e8525224
629,398
def utc_time(source): """Convert source bytes to UTC time as (H, M, S) triple HHMMSS.000 >>> utc_time(b'123456.000') (12, 34, 56.0) """ if source: return int(source[:2]), int(source[2:4]), float(source[4:]) return None, None, None
97d651d615262d19df84eda71085e54d0b39cb19
629,400
import re def quoted_split(string_to_split, preserve_quotations=False): """ Function to split string into list of words but preserves quoted sub strings. found here: https://stackoverflow.com/a/51560564 Parameters ---------- string_to_split : string the string to split preser...
c57eeb0c4118955baf8a3233c5e3c295063535b4
629,403
def is_usb_serial(device, args=None): """Checks device to see if its a USB Serial device. The caller already filters on the subsystem being 'tty'. If serial_num or vendor is provided, then it will further check to see if the serial number and vendor of the device also matches. """ prop = devic...
b1cbda05807107180e736963b62df5ea77e52d98
629,404
def segment_length(curve, start, end, start_point, end_point, error, min_depth, depth): """Recursively approximates the length by straight lines""" mid = (start + end) / 2 mid_point = curve.point(mid) length = abs(end_point - start_point) first_half = abs(mid_point - start_point) second_half = a...
521391bd0d818c33f927a687913d9812350b8168
629,405
import logging import os def du(path): """ Perform a "du" on a path, getting the disk usage. Args: path (str): The path to analyze Returns: int: bytes used """ logging.info('du of %s', path) total = 0 for root,dirs,files in os.walk(path): for d in list(dirs): ...
d20e4ec76af1688cc2818c2506725371e2a40461
629,406
def index(): """Test server status""" return 'It works'
2ee39b1c354752c08b7bc87c88bd686edd8e66f9
629,407
def fb_match_summary(pageSoup): """ Extracts events (goals, bookings, and substitutions) from match summary for a given match Parameters: pageSoup (html document): bs4 object of a match Returns: list: events """ # Find events object summary = pageSoup.find('div', {'id' : ...
5e1a797718ed0a151fe6b4bf56110a1207363f6a
629,408
def latency(latency_50th_ms, latency_99th_ms, latency_999th_ms): """Helper method to ensure uniform representation of latency data""" return { "latency_50th_ms": latency_50th_ms, "latency_99th_ms": latency_99th_ms, "latency_999th_ms": latency_999th_ms }
7fda5e207eba75de3ce56de02c5f11d6d7a5dc49
629,409
def splitdate(date_str=None, level=1): """Split a date string :param date_str: The ISO date string YYYY-DD-MM[ HH:MM:SS.UUU] :param level: A value between 1 & 3 determining which part to remove - date parts removed are replaced with '1' :return: """ return ('-'.join(date_str.split...
f2b9f93c0390199338cf995168f3f45161388f69
629,410
def get_highest_priority_reachable(Sr): """ Sr: The remaining unconsidered part of the original solution Return: the highest priority rule which is also reachable, i.e. that is to say it is in table 1. Or None if no rules are reachable. """ reachable = [r for r in Sr if r.tab...
0db461c71b79f10f0e239fd6c48658c0d1fdfc2e
629,411
import re def parse_line(line): """ This function is needed to parse one-liner from the controller and extract the information we need :param line: a one line of output from "show ap database long" command :return: object, representing AP and it's key values, like MAC-address or given name """ ...
d0193154d2306c305a4a5f058ec388c16b84dced
629,412
def emc(values: list) -> float: """ Fraction of empty cells """ if len(values) == 0: return 0.0 empty_cells_count = sum([ 1 for v in values if len(v.strip()) == 0 ]) return empty_cells_count / len(values)
5cd78f65ba1b536ad6efdddf29be0981ad3a8b45
629,413
def create_search_group(recordset = None, field = None, values = None, criteria_operator = "EqualTo"): """ Create a Coalesce search group/filter object (the value of "group" in a `Coalesce search request object <https://github.com/InCadence/coalesce/wiki/REST-API#search-query-dat...
b55e37f2df255b19e8e12566031cf7f784ff094b
629,414
import re def _strip_namespace_from_pnx_string(pnx_string): """ The original pnx record contains namespaces, which cause problems for ElementTree, so we must strip them """ pnx_string_without_namespace = re.sub(' xmlns="[^"]+"', '', pnx_string) # , count=2) return(pnx_string_without_namespace)
d89830815ffa90b4d1369098b5a28eb9a5a82d0d
629,415
def calc_fp_fn(actual, predicted, sensitive, unprotected_vals, positive_pred): """ Returns False positive and false negative for protected and unprotected group. """ unprotected_negative = 0.0 protected_positive = 0.0 protected_negative = 0.0 fp_protected = 0.0 fp_unprotected = 0.0 f...
37a96ac017c3e644010a6dfea22d475dff750616
629,416
import yaml import os def get_environment(base_dir): """ Parse the environment variables from .env """ temp_env_var = yaml.load(""" github: username: token: public_dir: public extensions_dir: extensions domain: https://domain.com/extensions s...
70b360b720adfcbd3da5f8922f48abf094400e36
629,417
import binascii import os def generate_secret_key(): """Generate a flask secret key. Returns: str: Return a secret key. """ return binascii.hexlify(os.urandom(24))
0f3dfcf510ca36c456699fb297c5339c0172d45f
629,418
def __is_org(string: str) -> bool: """ Return if a given string is an org directive :param string: String to check for org. :return: True if org. """ return string.startswith("org ")
7d6300a7e582c1d9cdacb648cfc1f4ff969c3be1
629,419
def empty_fld_dict(names): """creates a dictionary with expected field names initialized to none """ return {_f:None for _f in names}
996fbb41cb792b2a2fc2e8dded3420a841600431
629,420
def dict_to_dot_str(d, parent_key='digraph D', indent='', base_indent=''): """Dict will be converted into DOT like the followings: 1) Value string will not be double-quotted in DOT. - make sure to escape double-quotes in a string with special characters (e.g. whitespace, # and ;) ...
5e7ef5ab91f5cd5e25737b52dbd1f9861726497c
629,421
def context(): """Fixture to return a valid context as known from a cookiecutter.json.""" return { 'cookiecutter': { 'email': 'raphael@hackebrot.de', 'full_name': 'Raphael Pierzina', 'github_username': 'hackebrot', 'version': '0.1.0', } }
c32da7d6cbd520ca5c66cb1412b443e5377ee29c
629,422
def optlist_to_dict(optlist, opt_sep=',', kv_sep='=', strip_quotes=False): """Parse an option list into a dictionary. Takes a list of options separated by ``opt_sep`` and places them into a dictionary with the default value of ``True``. If ``kv_sep`` option is specified then key/value options ``key=va...
ad554763610d1f4cc95faefabb9218477a5f80ce
629,424
def unwrap_string(s): """A utility function that converts a "'string'" to a "string" """ s = s.replace("'", "") return s
62fd829604123cb53a40f8d496fe8082f406b9d1
629,425
def is_even(n: int) -> bool: # suggested solution """ Check if a given number is even Using modulo 2, and checking if the remainder is zero """ return n % 2 == 0
e49e3a5bfbf565071d363f6eadcd8604bc0cdfe3
629,426
import torch def calc_total_loss(flow, data): """ Compute total loss of model on data. Parameters ---------- flow : nflows.flows.Flow Normalising flow, instance of Flow object from nflows.flows, generated from e.g. load_flow() or setup_MAF(). data : torch.Tensor, shape (N, n_d...
38b21d43c7fdf023a8f1e2f8382c575219c3f4f7
629,427
import copy def sum_var(cpt, var): """ cpt: (Variables, Dict((True, False)=>Probability)) var: Variable """ sum_cpt = copy.deepcopy(cpt) if var in sum_cpt[0]: pos = sum_cpt[0].index(var) sum_cpt[0].remove(var) oldProbTable = sum_cpt[1] sum_cpt[1] = {} f...
f7a9599f5e074d570f40ca78b34a1f70fa9f5df1
629,428
import os import sys def script_name_no_ext() -> str: """ :return: Name of the Python script currently running, without the .py extension. """ script_name = os.path.basename(sys.argv[0]) last_dot_idx = script_name.rfind('.') if last_dot_idx >= 0: script_name = script_name[:last_dot_idx...
3fb8967c873202d49a70423b40df54bbb6c4a032
629,430
def to_bool(s: str) -> bool: """Return bool converted from string. bool() from the standard library convert all non-empty strings to True. """ return s.lower() in ['true', 't', 'y', 'yes'] if s is not None else False
d8ee5b28aef071654af3c5fee2fe232c8bbd3df4
629,431
def titlecase(string: str): """Safely recast a string to title case""" try: return string.title() except AttributeError: return string
eb13947c6f59069a6a3ab4b42d77931e3f5bc740
629,432
import json def dumps_tree(tree, duplicate_action = 'list', **kwargs): """ Dumps a Tree as json.dumps. First converts to_python using duplicate_action. Additional kwargs are sent to json.dumps. """ obj = tree.to_python(duplicate_action = duplicate_action) return json.dumps(obj, **kwargs)
3419ef28cce2c77605ec9fedca173dcbc7ed6b8b
629,433
def _get_indices(topology, residue_name): """ Get the indices of a unique residue in an OpenMM Topology Parameters ---------- topology : openmm.app.Topology Topology to search from. residue_name : str Name of the residue to get the indices for. """ residues = [] for ...
396a888c92a1b002bdaf7fd757577cda13824ea5
629,435
def remove_unwanted_content(domain, soup_object): """Remove unwanted content collected from non-standard websites""" if domain == "bleepingcomputer": # Remove unwanted content from soup object soup_object.find("div", {"class": "cz-related-article-wrapp"}).decompose() return soup_object
66b6064b467d301a9565d7d5ee5dc76a30498d66
629,436
import pickle def load_model(): """ Load trained model :return: """ with open('classifier.p', 'rb') as fp: data = pickle.load(fp) return data['model'], data['scaler']
1cf3cd2f5c1cc775280c74bc774f9f642c4c7c48
629,437
def construct_select_original_bericht_query(bericht_uri): """ Construct a SPARQL query for selecting the first message in a conversation :param bericht_uri: URI of a bericht in a conversation :returns: string containing SPARQL query """ q = """ PREFIX schema: <http://schema.org/> ...
66be0a019b4bb64c7a3d4a96866a2a695981d9b6
629,438
import subprocess def deletePorts(startingPort, numberofUsers, numberoftheVM): """ deletes ports """ firstport = startingPort + (numberoftheVM * numberofUsers) lastport = firstport + numberofUsers - 1 if numberofUsers == 1: ports = str(firstport) else: ports = str(firstpo...
d9a875287f3818ba02deca024f04881795ab4420
629,439
def look_spots(i_df, first_lat, last_lat, first_lon, last_lon): """ @param: id_f. @param: first_lat. @param: first_lon. @param: last_lon. @retun: i_df_spots. A Pandas Dataframe p """ i_df_spots = i_df[i_df['lat'] > first_lat] i_df_spots = i_df_spots[last_lat > i_df_spots['lat']] ...
b6f9c3c8010dd509efe39a7689b83701ca677425
629,440
def crack_ecb_encryptor(encryptor, block_size, secret_string_length, start_block): """This cracks ECB""" def block_getter(byte_str: bytes, block: int) -> bytes: return byte_str[block * block_size:(1 + block) * block_size] known_bytes = bytearray() # Create n cipher texts with 15-0 zeros prepend...
92051589382222301d4b62a57354a80fb098ffb6
629,441
def is_fq_local_branch(ref): """Return True if a Git reference is a fully qualified local branch. Return False otherwise. Usage example: >>> is_fq_local_branch("refs/heads/master") True >>> is_fq_local_branch("refs/remotes/origin/master") False >>> is_fq_local_bra...
455e8bc4897155292bb36f359db46952d8d74f95
629,442
import csv from typing import OrderedDict def load_tab_delimited_csv(filepath): """ loads a tab delimted csv as a list of ordered dictionaries """ data = [] with open(filepath) as file: reader = csv.reader(file, delimiter="\t") header = [] for csv_row in reader: ...
7a04ebc88b4f661af2bc64404ceab0ee311078d1
629,444