content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def docstr_header2(title,fcnstr): """Definition of the header for all experiment models""" return f""" {title} The function takes a list or array of parameters and returns the calculated background model:: B = {fcnstr}(t,param) The built-in information on the model can be accessed via its attributes...
64796854f707787510800b319032932b6f7397d8
687,641
import numpy def carla_velocity_to_numpy_vector(carla_velocity): """ Convert a carla velocity to a numpy array Considers the conversion from left-handed system (unreal) to right-handed system (ROS) :param carla_velocity: the carla velocity :type carla_velocity: carla.Vector3D :return: a ...
26d87155feb76b33c57bef57e45583dd7d3753a4
687,642
import numpy def dchisq(psr, formbats=False, renormalize=True): """Return gradient of total chisq for the current timing solution, after removing noise-averaged mean residual, and ignoring deleted points.""" if formbats: psr.formbats() res, err = psr.residuals(removemean=False)[psr.deleted =...
2e0e52abbfef511c9219413a7ffe9866174538ab
687,644
def _build_message_subject(subject: str, client_name: str) -> str: """Подготавливает заголовок сообщения""" if client_name: client_name += "\n" if subject: subject += "\n" subject = f"<i><b>{client_name}{subject}</b></i>" return subject
1d00b72a280b80c7117983a4712af120f1972122
687,645
def legend_from_ee(ee_class_table): """Extract legend from an Earth Engine class table on the Earth Engine Data Catalog page such as https://developers.google.com/earth-engine/datasets/catalog/MODIS_051_MCD12Q1 Value Color Description 0 1c0dff Water 1 05450a Evergreen needleleaf forest 2 086a10...
6f61958a837bff89949717a7bfb70a0b27dade20
687,646
def _pseudo_alpha(rgb, opacity): """ Given an RGB value in [0, 1], return a new RGB value which blends in a certain amount of white to create a fake alpha effect. This allosws us to produce an alpha-like effect in EPS, which doesn't support transparency. """ return tuple((value * opacity - opa...
0326d306c8846b46a7b9225ee5b969ff88e4e47d
687,647
import os def FormatCell1(test_case, test_instance, metrics_file, log_file, plot_file, link_to_plots): """Outputs an HTML table entry for the first cell of the row. The row is filled if the metrics file exist. The first cell contains a link that for short tables points to a plot file inline, fo...
24db5ce1ab477539ebb6456ae68ac1ff50180726
687,648
def convert_gps_degress_to_minutes(lat, lon): """ Convert GPS in degrees to degrees, minutes, seconds as needed for the Exif :param lat: Latitude in degrees :param lon: Longitude in degrees :return: Latitude and longitude in degrees, minutes, seconds """ lat_positive = lat >= 0 lon_posit...
eab4f7735fb26a787edee618ea4c2e0c219fc1f0
687,649
import json def read_old_meta(): """ 读取旧的meta数据 """ with open("meta.json", "r") as fd: return json.load(fd)
e5592d19f7827686f1b13201349ad8f1eb487f61
687,650
def has_os_path_join(block_dets): """ path = os.path.join('a', 'b') os.path.join('a/', 'b') <value> <Call lineno="2" col_offset="7"> <func> <Attribute lineno="2" col_offset="7" type="str" attr="join"> <value> <Attribute lineno="2" col_offset="7" type="st...
3d6abe066e228bbdf2e2a9aabcf45f6e5fd59994
687,651
import requests def patch_request(base_request): """ Performs PATCH request for the class provided. :param: base_request: Class with which to make request. :type: BaseRequest :return: response :rtype: requests.Response """ (headers, _, _, _, service) = base_request.get_request_vars() ...
1e6eddddfc2108bdb89e5436ed2253b265920c8e
687,652
def get_intercept(coords, m): """Calculates the intercept of a line from coordinates and slope""" x, y = coords[0], coords[1] b = y - m * x return b
923bce5d5fd4ee8a11fa5ae12c2b2a82233bdd54
687,653
def lte(x, y): """Creates an SMTLIB less than or equal to statement formatted string Parameters ---------- x, y: float First and second numerical arguments to include in the expression """ return "(<= " + x + " " + y + ")"
96d51fb1d7a7f96f99c96b025ec4938e5ef19dea
687,654
def parse_none_results(result_dict): """ Replace `None` value in the `result_dict` to a string '-' """ for key, value_list in result_dict.items(): for i in range(len(value_list)): if value_list[i] is None: result_dict[key][i] = '-' return result_dict
d1212cd9aa5c4246edd5d218bcaeb18527434233
687,655
import math import struct def OSCBlob(next): """Convert a string into an OSC Blob, returning a (typetag, data) tuple.""" if type(next) == type(""): length = len(next) padded = math.ceil((len(next)) / 4.0) * 4 binary = struct.pack(">i%ds" % (padded), length, next) tag = ...
7e55c99a33534fa59879d8fe50ccda8989c9e9c8
687,656
def reverse_it(sentence): """ Returns the sentence with all the letters in reverse order. :param sentence: The sentence. :return: The reversed sentence. """ # Create an empty string that will store our new reversed string. new_sentence = "" # len() will return the length of a sequence,...
b06a100144190d9ab5c805cd843ddff6a0b09aa3
687,657
def Ic(stack): """ the I combinator. Unquotes the iterable by pushing its elements. >>> from operator import add >>> Stack([1,2,plus], Ic) Stack(3,) """ stack, x = stack.pop() return stack.push(*x)
33e96bc9f934d9f404b4e99bbaef2edfa845956a
687,658
def _split_env(env): """if handed a list, action="append" was used for -e """ envlist = [] if not isinstance(env, list): env = [env] for to_split in env: for single_env in to_split.split(","): # "remove True or", if not allowing multiple same runs, update tests if...
bfb80d0ac1b40884cc5badee14ba6035010f20f8
687,659
def schema(): """ :return: Schema of custom policy """ return { "$schema": "http://apicast.io/policy-v1/schema#manifest#", "name": "APIcast Example Policy", "summary": "This is just an example.", "description": "This policy is just an example how to write your custom poli...
9e62c46d38f1c703ef7ebfa1a8c212a4ad435612
687,660
def cCO3(H, DIC, Ks): """ Returns CO3 """ return DIC / (1 + H / Ks.K2 + H ** 2 / (Ks.K1 * Ks.K2))
ec8f1d84cd4155537129cad842625c0bb1f1db5c
687,661
from functools import reduce def _parseTokenList(tokenList): """ Given a list of tokens from a GLM, parse those into a tree data structure. """ def currentLeafAdd(keyF, value, treeF, guidStackF): # Helper function to add to the current leaf we're visiting. current = treeF for ...
85227475066d58fa885d0e5536b56bd6162ec9c4
687,662
import hashlib def getid(question): """ compute id. """ m = hashlib.md5() m.update(question.encode('utf8')) return m.hexdigest()
b599a2a9f3f7bbdb457408e11df1dfbdc978a4e0
687,663
import torch def rgb_to_hsv(img: torch.Tensor) -> torch.Tensor: """ RGB to HSV conversion function. :param img: Batch of RGB images [batch_size, 3, height, width] :return: Batch of HSV images [batch_size, 3, height, width] """ assert len(img.shape) == 4 and img.shape[1] == 3 eps = 1e-7 ...
cf6d956a039a273a8cb56bff285d4b8d076c0b50
687,664
def imagenet_mean_preprocess_image_tensor_fun(x): """ In: x - image tensor of size (#images, #channels, #dim1, #dim2) Out: image tensor x with subtracted imagenet mean """ y = x y[:,0,:,:] -= 103.939 y[:,1,:,:] -= 116.779 y[:,2,:,:] -= 123.68 return y
8bf058b4713683826bff304c50e3bdcfe05cde2b
687,665
def build_url(city_data, api_info): """Return a `request` compatible URL from api properties.""" # type: (Dict, Dict) -> str return "{}:{}{}".format( api_info["host"], str(api_info["port"]), api_info["path"].format( city=city_data["city"], state=city_data["state"]))
45a44b6c791711bcb801b30320f72b4f44fafb5c
687,666
def add_trailing_slash(s): """Add trailing slash. """ if not s.endswith('/'): s = s + '/' return(s)
6587568a758e31e591d0240a715fff8a12c5e30d
687,667
def _join_host_port(host, port): """Adapted golang's net.JoinHostPort""" template = "%s:%s" host_requires_bracketing = ':' in host or '%' in host if host_requires_bracketing: template = "[%s]:%s" return template % (host, port)
c650d76262914b6591621cc3e2210473f3f02290
687,668
import os def _normalize(obj): """Convert path(s) to platform's native format.""" if obj: if isinstance(obj, (tuple, list)): return [os.path.normpath(item) for item in obj] else: return os.path.normpath(obj) return None
ea24dacd883b6de3671bc829ae8848e61990362e
687,669
import torch def get_interior_points(N=10000, d=2): """ randomly sample N points from interior of [0,1]^d """ return torch.rand(N, d)
11b9b75735dd6251f590428018b779f2873b6eec
687,670
import argparse def parse_args(): """set and check parameters.""" parser = argparse.ArgumentParser(description="run mrc") parser.add_argument("--task_type", type=str, default="drcd", choices=["drcd", "cmrc"], help="Task type, default is drcd") parser.add_argument("--device_targ...
9bafa9ebfb7495a71261949abb205c0b1b50da5a
687,671
def calc_brightness(value: float, actual_brightness_value: int, max_brightness_value: int, function: str) -> int: """Calculate brightness value based on actual and maximal brightness. The function calculates a brightness value using the `function` string and the `value` as a percentage. If `function` is em...
6cd7f08569a7a841dc19238bb37e925fc99b9ec1
687,672
import requests def get_html(url): """ Get HTML document from GET request from URL :param url: str URL of request :return: str HTML document """ r = requests.get(url, headers={'User-Agent': 'Custom'}) r.encoding = r.apparent_encoding print(r) return r.text
709ba4e5e3f5f574c127bb868c2c14cf25ec83db
687,673
def mocked_open(mocker): """Mocking builtin open""" return mocker.patch("builtins.open")
1626c46f4d156b1f28a7bbb31f932ed82fa83bca
687,674
def lower_column(col): """ Return column from lower level tables if possible >>> metadata = sa.MetaData() >>> s = sa.Table('accounts', metadata, ... sa.Column('name', sa.String), ... sa.Column('amount', sa.Integer), ... sa.Column('id', sa.Integer, primary...
c204ab8dcf63abd50ff0213f1f72043b0102f43d
687,675
def homogeneous_composite_modulus(E, nu): """Returns elastic composite modulus for homogeneous system, i.e. both sides of fracture of same material.""" return 1.0 / (2.0 * (1.0 - nu**2) / E)
fe4912b7e67316978618063a3a484e60ce97fef6
687,676
def getEnumString(c, enum): """extract enum string given the enum integer from an enum-only class""" for s in c.__dict__.keys(): if c.__dict__[s] == enum: return s return "<UNKNOWN>"
9dbaefbac6bef0988b35aed1131ed7977466456e
687,677
import re def from_lower_camel_case(str_to_convert): """ This function will convert 'lowerCamelCase' to 'lower camel case' :param str_to_convert: string to convert :return: return converted string """ if type(str_to_convert) is not str: raise TypeError("The method only take str as its ...
05ab08d929c8d809512d5af4780026584c55f476
687,679
def tuple_replace(tup, *pairs): """Return a copy of a tuple with some elements replaced. :param tup: The tuple to be copied. :param pairs: Any number of (index, value) tuples where index is the index of the item to replace and value is the new value of the item. """ tuple_list = list(tup) ...
ec4c52d3257bd33b31a45e3d298aa934436efb4a
687,680
def compare_list(ground_truth, prediction): """compare list""" right_count = 0 min_len = len(ground_truth) if len(ground_truth)<len(prediction) else len(prediction) gap_count = len(ground_truth) - min_len for k in range(min_len): if str(ground_truth[k]) == str(prediction[k]): ri...
57b7162f8282646b6c407a4db775718605a47156
687,681
import os def about_info(package: str): """Fetch about info """ root = os.path.abspath(os.path.dirname(__file__)) with open( os.path.join(root, "src", package.replace("-", "/"), "about.py"), encoding="utf8", ) as f: about = {} exec(f.read(), about) return about
ec50d29005a4ccf837ea547295aa21c94f65ac64
687,682
import random import os def write_host_file(hostlist, path='/tmp', slots=1): """ write out a hostfile suitable for orterun """ unique = random.randint(1, 100000) if not os.path.exists(path): os.makedirs(path) hostfile = path + '/hostfile' + str(unique) if hostlist is None: raise...
dec58d655a5551ac47a714e31ccf98e285effb41
687,683
import json def encoded_difference(string: str) -> int: """ Calculate the difference in length between the given sample and an output string which encodes it with appropriate escape characters. """ return len(json.dumps(string)) - len(string)
1a27346768e12c7cb65527d42754b6a1ee212688
687,684
import re def separate_words(name): """Convenience function for inserting spaces into CamelCase names.""" return re.sub(r"(.)([A-Z])", r"\1 \2", name)
a2c2db19d9eddf94edd846f0752ca237cb99e441
687,685
def first_is_not(l, v): """ Return first item in list which is not the specified value. If all items are the specified value, return it. Parameters ---------- l : sequence The list of elements to be inspected. v : object The value not to be matched. Example: -------...
c514e22338060a71c46fd1cc39ae7f9f273de158
687,686
def default_str(str_, default_str): """Returns :attr:`str_` if it is not `None` or empty, otherwise returns :attr:`default_str`. Args: str_: A string. default_str: A string. Returns: Either :attr:`str_` or :attr:`default_str`. """ if str_ is not None and str_ != "": ...
c0277b5a91a26c0fdb01c98d0e91b3a9c7604285
687,687
def _get_morphometry_data_suffix_for_surface(surf): """ Determine FreeSurfer surface representation string. Determine the substring representing the given surface in a FreeSurfer output curv file. For FreeSurfer's default surface 'white', the surface is not represented in the output file name pattern. For ...
fcc9a4611bd056a7159d88e5b8706efa40e2ab67
687,688
def calcNextPosition(start, neighbours, distances): """ Finds the neighbour with minimum distance of the starting point and returns UP, DOWN, LEFT, RIGHT - action how to go there. """ minDist = 1500 nextNeighbour = start for jack in neighbours: if distances[jack[0]][jack[1]] < minDis...
1fa6a43811275f112d4d7ea013f2a4b9295a2349
687,689
import math def format_duration(seconds: float) -> str: """Formats duration in seconds into hours/minutes/seconds.""" if seconds < 60: return f'{seconds:.0f}s' elif seconds < 3600: minutes = math.floor(seconds / 60) seconds -= minutes * 60 return f'{minutes}m{seconds:.0f}s' else: hours = m...
0d14b1dcf389501c21ea1f14f0808b926a952c44
687,690
def bubble_sort(L): """(list) -> list Reorder the items in L from smallest to largest. >>> bubble_sort([6, 5, 4, 3, 7, 1, 2]) [1, 2, 3, 4, 5, 6, 7] """ # keep sorted section at end of list # repeated until all is sorted for _ in L: # traverse the list for i in range(len(...
aab05c6a8319cc0027717b2793daab5fe74a3a0c
687,691
def Version(): """ Return the Extron Library version string in the form of <major>.<minor>.<revision> """ return ''
5bb67ada2e05d82f89965514d5bb7a12789d7f16
687,692
def is_valid_address(address): """is_valid_rom_address""" if address == None: return False if type(address) == str: address = int(address, 16) if 0 <= address <= 2097152: return True else: return False
d262cf6dd619533de36914e6f977a5eac73467bd
687,693
def string_intersection(s1, s2): """ Create an empty string and check for new occurrence of character common to both string and appending it. Hence computing the new intersection string. :param s1: :param s2: :return: """ result = "" for i in s1: if i in s2 and i not in r...
c0288db5fc70843b38a117fc93db0f9d31e070a3
687,694
import multiprocessing def make_queue_pack(): """ Creates a "queue pack". This is the one object that connects between the Shell and the Console. The same queue_pack must be fed into both. See package documentation for more info. """ return [multiprocessing.Queue() for _ in range(4)]
dba3dabc45b4d192228883923e79a0ff48a86104
687,695
def name(): """Return the name of the ontology.""" return "SNOMEDCT"
5e46f8a34c5679ed4836a0ed8c291050c6be061d
687,696
import time def wait_for(condition, timeout_seconds=1.0, poll_interval_seconds=0.01): """ Timed out waiting for condition to be true """ end_time = time.time() + timeout_seconds while time.time() < end_time: if condition(): return True time.sleep(poll_interval_seconds) ...
649a3a712ad3e308898788c71b2c58a88c37ce44
687,697
def save_as(user): """ Returns a callback which saves the model as the user that you pass in """ def user_save(instance): instance.save(user) return user_save
e86e29369e2306eee3189b32db87457c13ace8b5
687,698
def get_test_count(test_data): """ Args: test_data: json of test data Returns: int: total test count """ return int(test_data.get("testsuites").get("testsuite").get("@tests"))
a65bb6bdccd789609b1ce25faf2740f1de6b1f78
687,699
def map_diameter(c: int) -> float: """ Compute the diameter """ return 1 / 3 * (c + 1) * (c - 1)
fb3f19478901f40b52af11c6d200f125d3716112
687,700
import argparse def parse_shell_args(args): """ Parse shell arguments for this script Args: args: Command line arguments passed through sys.argv[1:] Returns: Dictionary with configuration """ parser = argparse.ArgumentParser(description="Run experiments with the Dynamic DropC...
542214731f13a969080a598985793ecd070d7ba8
687,701
def substitute(a_function): """return a different function than the one supplied""" def new_function(*args, **kwargs): return "I'm not that other function" return new_function
6a33c5118354d9213911ca47367508e55ced878e
687,702
import os def expand_storage(store): """ A storage directory usually consists of 4 different subdirectories. This function returns their paths """ store = os.path.normpath(store) return { 'organize' : os.path.join(store, 'organize'), 'recorded' : os.path.join(store, 'recorded...
6a2ad2e7f088f9840035dc2091c630248c4a9a51
687,703
def as_dict_based_diff(di): """Converting to dict-based diff format for dicts for convenience. NB! Only one level, not recursive. This step will be unnecessary if we change the diff format to work this way always. """ return {e.key: e for e in di}
95f87350e64b2c485087c0560e59cad04d71764a
687,704
def label_set_match(object_labels, returned_labels): """Return True if at least one of the object labels is contained in at least one of the returned labels""" for o in object_labels: for r in returned_labels: if o.lower() in r.lower(): return True return False
86e0b1e73fb9c370fc8a25a89dca4476abd2f3b2
687,705
import math def entropy(target): """Data entropy.""" if not target: return 0 result = 0 for i in range(2): p = target.count(i) / len(target) if p: result -= p * math.log2(p) return result
297854401dade6e5c4c6337e76f27a8deb3f9feb
687,706
def remove_none_func_lines(lines): """Doc.""" new_lines = [] for line in lines: if line.startswith('#') and '.h' in line: new_lines.append(line) elif line.endswith(');') or line.endswith('{') or \ line.endswith('}') or line.endswith('};'): if '(' in li...
f598630fb763140873b24206de5bbb5899708c26
687,707
def bytelist_to_hex_string(bytelist): """ :param bytelist: list of byte values :return: String representation of the bytelist with each item as a byte value on the format 0xXX """ return '[' + ', '.join("0x%02X" % x for x in bytelist) + ']'
5627654f0cd160b3fdbbdbf738f60557399b2e0c
687,708
def _minimum_edit_distance(s1, s2): """ DP algorithm for minimum edit distance """ if len(s1) == 0: return len(s2) if len(s2) == 0: return len(s1) m = len(s1) n = len(s2) dp = [[0 for j in range(n+1)] for i in range(m+1)] for i in range(m+1): for j in rang...
988bf9a531ae3dce204ce36ac364ce422b8cfc7d
687,709
def chain_value(row, attribute_ids): """ Join all the values of attributes to get a identifier :param row: a row of the table, e.g. a list of attribute values :param attribute_ids: a set of attribute :return: a string consists of joint value """ result = [] for attribute_id in sorted(att...
22c303f9286ae46cc96eccb556178edd2e5d180e
687,710
def shared_data_volume_container_path(sdv, sdvkey): # type: (dict, str) -> str """Get shared data volume container path :param dict sdv: shared_data_volume configuration object :param str sdvkey: key to sdv :rtype: str :return: container path """ return sdv[sdvkey]['container_path']
e9a3455a71f6862039ab092ccc5ede46a58c71f4
687,711
def transform_feature_names(transformer, in_names=None): """Get feature names for transformer output as a function of input names. Used by :func:`explain_weights` when applied to a scikit-learn Pipeline, this ``singledispatch`` should be registered with custom name transformations for each class of tra...
e8032853f754c38ed8f36f98e70cb7794f659262
687,712
def isYes(string): """Returns True if the string represents a yes, False, if it represents no, and another string if it represents something else""" value = string.strip().lower() if value in ['yes', 'always', 'on', 'true']: return True if value in ['no', 'never', 'off', 'false', 'null']: ...
3c8d5e54daf02fe5add3202cb4d3d0942a43616e
687,715
def _add_new_line_if_none(s: str): """Since graphviz 0.18, need to have a newline in body lines. This util is there to address that, adding newlines to body lines when missing.""" if s and s[-1] != "\n": return s + "\n" return s
aed3582be53cf403601a125cebc436041257a0d9
687,716
def sort_ipv6_address_without_mask(ip_address_iterable): """ Sort IPv6 addresses | :param iter ip_address_iterable: An iterable container of IPv6 addresses | :return list : A sorted list of IPv6 addresses """ return sorted( ip_address_iterable, key=lambda addr: (...
e8c51a270937ff3ee18fbe35269da10298ce2186
687,717
def build_from_cfg(name, cfg, registry, default_args=None): """Build a module from config dict. Args: name (str): Name of the object cfg (addict): Config dict of the object registry (:obj:`Registry`): The registry to search the type from. default_args (dict, optional): Default i...
8eb9b9717764ae1c1ca121a59b466ef7c2d72f70
687,718
import glob def getFeatures(dirSrc, extFilesSrc, lsGenres): """ Reads samples in form of multiple text files and returns a pair of feature matrix X and target vector y. dirSrc: Absolute path to directory of source text files extFilesSrc: File extension of source text files (e.g. "txt") ...
47b0ddbe36e34788ba3eed20aebc8852a36e8245
687,719
def max_spike_power(FWHM): """ max_spike_power(FWHM): Return the (approx.) ratio of the highest power from a triangular spike pulse profile to the power from a perfect sinusoidal pulse profile. In other words, if a sine gives you a power of 1, what power does a spike profile ...
ef6ade4ad285fa817ab3f119b2fd1ba20fe409e4
687,720
def chunks(l, n): """ @type l: list (or other iterable) @param l: list that will be splited into chunks @type n: int @param n: length of single chunk @return: list C{l} splited into chunks of length l Splits given list into chunks. Length of the list has to be multiple of C{chunk} o...
415cb8dddce061ddf5b6cd8e0915a82fd5ddf11a
687,721
def lambda_(func): """:yaql:lambda Constructs a new anonymous function Note that to use this function 'delegate' mode has to be enabled. :signature: lambda(func) :arg func: function to be returned :argType func: lambda :returnType: obj type or message .. code:: yaql> let(func...
ccae591c70e7f4697345bcde1c3c57a7c6603341
687,722
import torch def truncated_normal(size, std): """ Pytorch does not have a truncated normal function to we manually make one in order to cut the dependancy on tensorflow Modified Version of: https://discuss.pytorch.org/t/implementing-truncated-normal-initializer/4778/20 """ mean = 0 tensor ...
0064f5a5c97809072b9493f823667d4036921d50
687,723
def uniquify_tuples(tuples): """ Uniquifies Mimikatz tuples based on the password. cred format- (credType, domain, username, password, hostname, sid) """ seen = set() return [item for item in tuples if "%s%s%s%s"%(item[0],item[1],item[2],item[3]) not in seen and not seen.add("%s%s%s%s"%(item[0]...
c0abc020ff1efd5e2be2a72f2c20a53e315b1133
687,724
def compare_equal(compare_data): # pylint: disable=redefined-outer-name """ Returns a function which checks that a given data is equal to the stored reference. """ return lambda data, tag=None: compare_data(lambda x, y: x == y, data, tag)
45215759bb4aac2a9fe304e75c40e3ff70acd787
687,725
def type_validator(property_type): """Create validator that requires specific type. Args: property_type: The type of the validator. Returns: Validator that only accepts values of a specific type. """ def type_validator_impl(value): if not isinstance(value, property_type): raise TypeError('...
8ba043af22a133ed5bd613bf7a926912d4053275
687,726
import random import string def generate_random_alphanumeric(size: int = 16) -> str: """ AUTHORS: -------- :author: Alix Leroy DESCRIPTION: ------------ Generate a string of alphanumeric characters of a specific size The default size is 16 characters PARAMETERS: -----------...
4b84dacace3e170ed2c82d6affdfc53e8dd0923a
687,728
def prod(lst): """Product of list elements.""" if len(lst) == 0: return 0 x = lst[0] for v in lst[1:]: x *= v return x
156de3b3b9689460a4a84bcd4e868a2888299d09
687,730
def get_agent_location_from_maze_string(mazeString=str): """[Get the location of the agent from the maze] Args: mazeString ([str], optional): [string of the maze location]. Defaults to str. Returns: [tuple]: [location of the maze] """ mazeString = [list(x.strip()) for x in mazeStri...
62e15c2d4b90283649fa25cc4b07d657eed2ea8b
687,731
def decompose_path(path): """ Break a path down into individual parts Parameters ---------- path : string Path to variable on the Returns ------- structure : tuple of strings Tuple of split apart path """ return tuple((path_entry for path_entry in path.split('/')...
09d33183fbd4020f85bfc2e178dc387064262bde
687,732
from typing import OrderedDict def groupby(items, by): """ Group items using a function to derive a key. :param items: The items to group :param by: A lambda function to create a key based on the item :return: an Ordered dict """ result = OrderedDict() for it...
21b10c5fb4ba795cd3a43f380c8cdb823b3c2bfe
687,734
def check_textbound_overlap(anns): """ Checks for overlap between the given TextBoundAnnotations. Returns a list of pairs of overlapping annotations. """ overlapping = [] for a1 in anns: for a2 in anns: if a1 is a2: continue if a2.start < a1.end a...
e10618fc2cc1642ffd295ed59f939a120094254a
687,735
def det3x3(matrix): """ Calculate a determinant of a 3x3 matrix. Should be usually substituted by `numpy.linalg.det`, but is indispensable for matrices with uncertainties. :param matrix: 3x3 array/matrix which allows for 2d indexing :type matrix: numpy.ndarray or uncertainties.unumpy.matrix :re...
cf212c2e8710a2f4c60b091eede77b5b1c8b78b7
687,736
import numpy def CalculateMeanRandic(mol): """ ################################################################# Calculation of mean chi1 (Randic) connectivity index. ---->mchi1 Usage: result=CalculateMeanRandic(mol) Input: mol is a molecule object. ...
26f642cd91d8b9e2f5a5b91b9d846bb7312a662d
687,737
def remove_stopwords(documents, stop_words): """ removes stopwords from corpus Parameters ---------- documents : list of documents, where each doc is string. Returns ------- None. """ documents_processed = [] for document in documents: docum...
e080bc0e95aa2ad864b6a0d44b91b857f2a68f5a
687,738
def get_counts(filename): """ reads the .counts_edit file and extracts the counts :param filename: counts file (original or simulated) :return: list of counts """ with open(filename, "r") as counts_file: counts = [] for line in counts_file: line = line.strip() ...
2bb9914fbca82550e121f0dcb5c55f6817da6c91
687,739
from functools import reduce def get_url_from_image_key(image_instance, image_key): """Build a URL from `image_key`.""" img_key_split = image_key.split('__') if 'x' in img_key_split[-1]: size_key = img_key_split.pop(-1) else: size_key = None img_url = reduce(getattr, img_key_split,...
ecbf3926af3eee00234fe24b97e107412da75375
687,741
import io def replace_marker(filepath, marker, lines): """Replace given marker with provides lines.""" # Read source file with io.open(filepath, 'r', encoding='utf-8') as handle: source_lines = handle.readlines() # Replace marker, and use any text before it as an indent string changed = F...
35b9928a048ec3530d258cb8a948edb7ebc0a068
687,742
def str2meaning(s): """Helper function to eval a string in the Meanings namespace.""" return eval(s)
fe8c5d3f6cf26be9154ed27364a29a674b8140f1
687,743
def center_crop(img, w_target, h_target): """ Center-crop a PIL image according to the target dimensions """ w_im, h_im = img.size # preconditions: if(w_target > w_im or h_target > h_im): return None # get the min dimension: min_dim = min(w_im, h_im) if w_im == min_dim: ...
f761c059ac5787672d7e7f35a2c061e13925b9bb
687,744
def _get_human_bytes(num_bytes): """Return the given bytes as a human friendly KB, MB, GB, or TB string thanks https://stackoverflow.com/questions/12523586/python-format-size-application-converting-b-to-kb-mb-gb-tb """ num_bytes = float(num_bytes) one_kb = float(1024) one_mb = float(one_kb ** 2)...
b48a74b619734df839db752a247d5e6fcd6da05e
687,745
import os def home_dir(user): """Returns the user's home directory path.""" return '/' + os.path.join('home', user[0], user[:2], user)
9333b3d286f5eb12abf46aadccf42de300aed3fc
687,746
from pathlib import Path def _zip_links(links, linked_paths): """Given a set of Paths and a resolved collection per Link in the Paths, merge.""" # Alias the resolved destinations with the symbolic name of the Paths used to resolve them. if len(links) != len(linked_paths): raise ValueError('Expected to recei...
20a7425985e4a91ad9f53160a991ba162669b815
687,747
import re def get_brute(brute_file, mini=1, maxi=63, banned='[^a-z0-9_-]'): """ Generates a list of brute-force words based on length and allowed chars """ # Read the brute force file into memory with open(brute_file, encoding="utf8", errors="ignore") as infile: names = infile.read().split...
57ace4ffcb311c232e9c275e9e033d155beb4316
687,748