content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def _get_zip_filename(xml_sps, output_filename=None): """ Obtém o nome canônico de um arquivo ZIP a partir de `xml_sps: packtools.sps.models.sps_package.SPS_Package`. Parameters ---------- xml_sps : packtools.sps.models.sps_package.SPS_Package output_filename: nome do arquivo zip Returns ...
2545fc02849d73da99a2d6c4bda3d69307f8afa1
675,223
def asic_cmd(asic, cmd, module_ignore_errors=False): """ Runs a command in the appropriate namespace for an ASIC. Args: asic: Instance of SonicAsic to run a command. cmd: Command string to execute. module_ignore_errors: Flag to pass along to ansible to ignore any execution errors. ...
76d7fe2f1ca79dc57c711c364bbd8fc76613e097
675,224
import configparser def _config_ini(path): """ Parse an ini file :param path: The path to a file to parse :type file: str :returns: Configuration contained in path :rtype: Dict """ conf = configparser.ConfigParser() conf.read(path) return dict(conf)
12ee936fe64e89a8c6af0c44cbd6ab97f308bb8e
675,226
def read_messages_count(path, repeat_every): """ Count the predictions given so far (may be used in case of retraining) """ file_list=list(path.iterdir()) nfiles = len(file_list) if nfiles==0: return 0 else: return ((nfiles-1)*repeat_every) + len(file_list[-1].open().readlines())
c931bca2eeeefa2b02cc5770bc62c22f5e60a4b2
675,227
import math def percent(n, precision=0): """ Converts `n` to an appropriately-precise percentage. """ # 'or 1' prevents a domain error if n == 0 (i.e., 0%) places = precision - math.floor(math.log10(abs(n) or 1)) return '{0:.{1}%}'.format(n, places)
fe4690dcb6175bff6e5e19e88a87b6339892e8fd
675,230
def Focal_length_eff(info_dict): """ Computes the effective focal length give the plate scale and the pixel size. Parameters ---------- info_dict: dictionary Returns --------- F_eff: float effective focal length in m """ # F_eff = 1./ (info_dict['pixelScale'] * #...
75d21f27c04193a5615c1877bed6d69ada2c3cad
675,233
def irb_decay_to_gate_infidelity(irb_decay, rb_decay, dim): """ Eq. 4 of [IRB], which provides an estimate of the infidelity of the interleaved gate, given both the observed interleaved and standard decay parameters. :param irb_decay: Observed decay parameter in irb experiment with desired gate interle...
09f5b504ffffb047dc903a19bd51753c46cca7c2
675,239
def jaccard(words_1, words_2): """words_1 และ words_2 เป็นลิสต์ของคำต่าง ๆ (ไม่มีคำซ้ำใน words_1 และ ไม่มีคำซ้ำใน words_2) ต้องทำ: ตั้งตัวแปร jaccard_coef ให้มีค่าเท่ากับ Jaccard similarity coefficient ที่คำนวณจากค่าใน words_1 และ words_2 ตามสูตรที่แสดงไว้ก่อนนี้ Doctest : >>> words_1 = ['x', '...
0cc1c777f70360a4389558aef013116cc3bf50e7
675,242
import json def get_rev_list_kwargs(opt_list): """ Converts the list of 'key=value' options to dict. Options without value gets True as a value. """ result = {} for opt in opt_list: opt_split = opt.split(sep="=", maxsplit=1) if len(opt_split) == 1: result[opt] = Tru...
26c5ea709245211b83bcaeccbff320d212fa32ea
675,244
def collectReviewTeams(reviewers): """collectReviewTeams(reviewers) -> dictionary Takes a dictionary as returned by getReviewersAndWatchers() or getPendingReviewers() and transform into a dictionary mapping sets of users to sets of files that those groups of users share review responsibilities for. The same user ...
3ab69a7c504592ad7f680b3e5af59536e76c4112
675,245
def int_to_lower_mask(mask): """ Convert an integer into a lower mask in IPv4 string format where the first mask bits are 0 and all remaining bits are 1 (e.g. 8 -> 0.255.255.255) :param mask: mask as integer, 0 <= mask <= 32 :return: IPv4 string representing a lower mask corresponding to mask ""...
d3029ac0e8dd63b1ae361e0351a1e2b8e29be39f
675,249
def zero_fill(value: bytearray) -> bytearray: """ Zeroing byte objects. Args: value: The byte object that you want to reset. Returns: Reset value. """ result = b'' if isinstance(value, (bytes, bytearray)): result = b'/x00' * len(value) result = bytearray(res...
e5ce1b6162071e3aed7d5adb3aa5b0a20fc526a7
675,252
def get_user_choice(choices): """ ask the user to choose from the given choices """ # print choices for index, choice in enumerate(choices): print("[" + str(index) + "] " + choice) # get user input while True: user_input = input("\n" + "input: ") if (user_input.isdig...
5b1c379524b6f66d315c20288487921258b302fa
675,256
def get_size_from_block_count(block_count_str, size_step=1000, sizes = ["K", "M", "G", "T"], format_spec=":2.2f"): """Transforms block count (as returned by /proc/partitions and similar files) to a human-readable size string, with size multiplier ("K", "M", "G" etc.) appended. Kwargs: * ``size_step``:...
5e9efdc7ed573b19a51ca8602b24e56726d40597
675,257
import functools def memoize(f): """ Minimalistic memoization decorator (*args / **kwargs) Based on: http://code.activestate.com/recipes/577219/ """ cache = {} @functools.wraps(f) def memf(*args, **kwargs): fkwargs = frozenset(kwargs.items()) if (args, fkwargs) not in cache: ...
c87499db6856f988db389afd54350b96f7334fd2
675,262
import cgi def check_api_v3_error(response, status_code): """ Make sure that ``response`` is a valid error response from API v3. - check http status code to match ``status_code`` :param response: a ``requests`` response :param status_code: http status code to be checked """ assert n...
ca1be2ac3cff99b06fc0aaba73a075ff90024c9b
675,264
def fail(s): """ A function that should fail out of the execution with a RuntimeError and the provided message. Args: s: The message to put into the error. Returns: A function object that throws an error when run. """ def func(): raise RuntimeError(s) return fu...
f7a3e886d671a5eca872620cb6117912573f9c81
675,265
def is_simple_locale_with_region(locale): """Check if a locale is only an ISO and region code.""" # Some locale are unicode names, which are not valid try: lang, sep, qualifier = locale.partition('_') except UnicodeDecodeError: return False if '-' in lang: return False # ...
f59af0a4d4b8d9905a2558facdbd863e879105aa
675,269
def format_output_mesmer(output_list): """Takes list of model outputs and formats into a dictionary for better readability Args: output_list (list): predictions from semantic heads Returns: dict: Dict of predictions for whole cell and nuclear. Raises: ValueError: if model outp...
5603ac838b9f31179577c81de4be4b72e62fdbd3
675,271
import torch def extract_torchmeta_task(cs, class_ids): """ Extracts a single "episode" (ie, task) from a ClassSplitter object, in the form of a dataset, and appends variables needed by DatasetDistance computation. Arguments: cs (torchmeta.transforms.ClassSplitter): the ClassSplitter ...
7a342b95d88a65b9103380b3ed08d9e28a3ca5bf
675,272
import unicodedata def full2half(uc): """Convert full-width characters to half-width characters. """ return unicodedata.normalize('NFKC', uc)
2d41e41279f3b3a3a992097340aefb7b18333cfd
675,274
def simple_function(arg1, arg2=1): """ Just a simple function. Args: arg1 (str): first argument arg2 (int): second argument Returns: List[str]: first argument repeated second argument types. """ return [arg1] * arg2
ef302ed0b01af83ad373c90c6689a33ed8922ee1
675,276
def _object_type(pobj): ############################################################################### """Return an XML-acceptable string for the type of <pobj>.""" return pobj.__class__.__name__.lower()
9720d869a001416110932de33a7c6b0f57f76e02
675,278
import re def smi_tokenizer(smi): """ Tokenize a SMILES """ pattern = "(\[|\]|Xe|Ba|Rb|Ra|Sr|Dy|Li|Kr|Bi|Mn|He|Am|Pu|Cm|Pm|Ne|Th|Ni|Pr|Fe|Lu|Pa|Fm|Tm|Tb|Er|Be|Al|Gd|Eu|te|As|Pt|Lr|Sm|Ca|La|Ti|Te|Ac|Si|Cf|Rf|Na|Cu|Au|Nd|Ag|Se|se|Zn|Mg|Br|Cl|U|V|K|C|B|H|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\\\|\/...
65cbb63fff66582be2da19f655d7cecd45fd2e9a
675,279
def b2s(binary): """ Binary to string helper which ignores all data which can't be decoded :param binary: Binary bytes string :return: String """ return binary.decode(encoding='ascii', errors='ignore')
c92a07c37545f259ee1ffa6252c9e9e337ee3a42
675,280
def get_intersection_difference(runs): """ Get the intersection and difference of a list of lists. Parameters ---------- runs set of TestSets Returns ------- dict Key "intersection" : list of Results present in all given TestSets, Key "difference" : list of Resu...
6a534749357027b8e11367a1956a6ffe2d438455
675,282
def Nxxyy2yolo(xmin, xmax, ymin, ymax): """convert normalised xxyy OID format to yolo format""" ratio_cx = (xmin + xmax)/2 ratio_cy = (ymin + ymax)/2 ratio_bw = xmax - xmin ratio_bh = ymax - ymin return (ratio_cx, ratio_cy, ratio_bw, ratio_bh)
7dc7e7fd36a5bea9606dfd2414199abc7de00190
675,283
def all_children(mod): """Return a list of all child modules of the model, and their children, and their children's children, ...""" children = [] for idx, child in enumerate(mod.named_modules()): children.append(child) return children
c132968d51f0f1cad5c356a1e6b52afbf82c145f
675,284
def normalize_filename(filename): """Normalizes the name of a file. Used to avoid characters errors and/or to get the name of the dataset from a url. Args: filename (str): The name of the file. Returns: f_name (str): The normalized filename. """ if not isinstance(filename, str...
df3a511666e54d007fec514aa4eded24c90c001e
675,289
def find_double_newline(s): """Returns the position just after a double newline in the given string.""" pos1 = s.find(b'\n\r\n') # One kind of double newline if pos1 >= 0: pos1 += 3 pos2 = s.find(b'\n\n') # Another kind of double newline if pos2 >= 0: pos2 += 2 if pos1 >= 0:...
629b26df85ef068a6b390640c5ffbbde8ae7616b
675,291
import re def promote_trigger(source: list, trigger: str) -> list: """Move items matching the trigger regex to the start of the returned list""" result = [] r = re.compile(trigger) for item in source: if isinstance(item, str) and r.match(item): result = [item] + result else...
db5b3f8fa6e73be764f993132f85c05b8690176c
675,295
def oscar_calculator(wins: int) -> float: """ Helper function to modify rating based on the number of Oscars won. """ if 1 <= wins <= 2: return 0.3 if 3 <= wins <= 5: return 0.5 if 6 <= wins <= 10: return 1.0 if wins > 10: return 1.5 return 0
31350d7ab5129a5de01f1853588b147435e91ab2
675,299
import math def initial_compass_bearing(lat1, lng1, lat2, lng2): """ Calculates the initial bearing (forward azimuth) of a great-circle arc. Note that over long distances the bearing may change. The bearing is represented as the compass bearing (North is 0 degrees) Args: lat1 (str): The l...
d49055401e3f3be7f8c87a9cc65cdf8747d706ce
675,300
import base64 def get_svg(path): """Get an svg image into format to properly display This formats the svg image found at `path` into the str necessary for displaying in a dcc.Img component. from https://github.com/plotly/dash/issues/537 Parameters ---------- path : str path to t...
fa4583b15ffe5dbc0c795a05b5c68195e252989b
675,306
def clean_meta_args(args): """Process metadata arguments. Parameters ---------- args : iterable of str Formatted metadata arguments for 'git-annex metadata --set'. Returns ------- A dict mapping field names to values. """ results = {} for arg in args: parts = [x...
e0e55a759b0a563216350b14cd6bc0de648006f3
675,308
def _default_filter(meta_data): """The default meta data filter which accepts all files. """ return True
61a682e8cb3ef2ed39c365c78b3cf9d407bfceb4
675,309
import uuid def generate_fwan_process_id() -> str: """ Generates a new Firmware Analysis Process ID """ return str(uuid.uuid4())
7ab3262d4bd1c915c086d5df9f582628245aae58
675,310
import keyword def pykeyword(operation='list', keywordtotest=None): """ Check if a keyword exists in the Python keyword dictionary operation: Whether to list or check the keywords. Possible options are list and check. The default is 'list'. keywordtotest: The keyword to test for if the oper...
7e8e3e1792e347b7dd6ec88fcf7c2411a7b212f5
675,315
def validate(contacts, number): """ The validate() function accepts the contacts array and number as arguments and checks to see if the number inputted is in the range of the contacts array. It returns a number inputted by the user within that range. """ while number<1 or number>len(contacts): p...
f9dc7b4287e9f0bdc7c6da8240c49e0f4438c6c8
675,316
def thresh_hold_binarization(feature_vector, thresh_hold): """ Turn each value above or equal to the thresh hold 1 and values below the thresh hold 0. :param feature_vector: List of integer/float/double.. :param thresh_hold: Thresh hold value for binarization :return: Process and binarized list ...
b16d7d1b4e9700b41da82b2985a29eaa3f6d25ad
675,317
def transform_okta_user(okta_user): """ Transform okta user data :param okta_user: okta user object :return: Dictionary container user properties for ingestion """ # https://github.com/okta/okta-sdk-python/blob/master/okta/models/user/User.py user_props = {} user_props["first_name"] = o...
8a1379f1a72c8d4d665d1f4daeae8a02c86a4c13
675,318
def _compare_fq_names(this_fq_name, that_fq_name): """Compare FQ names. :param this_fq_name: list<string> :param that_fq_name: list<string> :return: True if the two fq_names are the same """ if not this_fq_name or not that_fq_name: return False elif len(this_fq_name) != len(that_fq_...
69f3505ac1f5cdec0cd5824b86927a2f33ffb7bf
675,320
def remove_element_from_list(x, element): """ Remove an element from a list :param x: a list :param element: an element to be removed :return: a list without 'element' Example: >>>x = [1, 2, 3] >>>print(arg_find_list(x, 3)) [1, 2] """ return list(filter(lambda a: a...
34b8fc375719c41a9ec31a0c086d9268e51be089
675,324
def equal(param1, param2, ignore_case=False): """ Compare two parameters and return if they are equal. This parameter doesn't run equal operation if first parameter is None. With this approach we don't run equal operation in case user don't specify parameter in their task. :param param1: user i...
e25f4f63836790cae9c08ceaccc2d161be7b9921
675,329
import torch def BCEFlat(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: """Same as F.binary_cross_entropy but flattens the input and target. Args: x : logits y: The corresponding targets. Returns: The computed Loss """ x = torch.sigmoid(x) y = y.view(x.shape).type...
81ae53a5af7dcb05561d0285f72b1bb668261c39
675,332
def _parse_message(exc): """Return a message for a notification from the given exception.""" return '%s: %s' % (exc.__class__.__name__, str(exc))
89cd5fafb6b79bd575bea2fb0c9de30b5157c130
675,336
import string def printable_substring(the_str): """Returns the printable subset of the_str :param str the_str: a putative string :return str the_pr_str: the portion of the_str from index 0 that is printable """ i = 0 the_pr_str = '' while i < len(the_str): if the_str[i] in string....
ba0251252e0878bfbc1f94bdef21376ed45c53d0
675,339
def make_read_only(tkWdg): """Makes a Tk widget (typically an Entry or Text) read-only, in the sense that the user cannot modify the text (but it can still be set programmatically). The user can still select and copy text and key bindings for <<Copy>> and <<Select-All>> still work properly. Inp...
57c8560b0c3979963397aaa635f7567644140012
675,341
def is_array(value): """Check if value is an array.""" return isinstance(value, list)
757c4f07d456a41d42fc98ed3a469695f7420201
675,346
import random def expand_model_parameters(model_params, expansion_limit): """Expand a model template into random combinations of hyperparameters. For example, if model_params is: {name: regression, l2_strength: [0, 1], train_steps: [100, 50] } Then the returned new_model_params will be the following: [ ...
c083abcaf5c09fbc365c5f3fa77095b24fd2f57f
675,347
import json def mock_hue_put_response(request, context): """Callback for mocking a Philips Hue API response using the requests-mock library, specifically for a put request. This mock response assumes that the system has a single light with light_id of '1', and the expected request is to set the 'on' ...
cc54a09d9595ac6e0868f7143bd663d2da78c3e4
675,349
import math def translate_key(key): """ Translate from MIDI coordinates to x/y coordinates. """ vertical = math.floor(key / 16) horizontal = key - (vertical * 16) return horizontal, vertical
1916fb2abc97f421494c3ced21d9f8ec05936845
675,354
def naniži(vrijednost): """Pretvaranje vrijednosti koja nije n-torka u 1-torku.""" return vrijednost if isinstance(vrijednost, tuple) else (vrijednost,)
1a59e09b39c5f83ee210fd296691c949a6a62584
675,358
import math def calculate_fov(zoom, height=1.0): """Calculates the required FOV to set the view frustrum to have a view with the specified height at the specified distance. :param float zoom: The distance to calculate the FOV for. :param float height: The desired view height at the specified ...
8868bf32e7d0d2240a0d2996b9444b82074eb024
675,360
from typing import Counter def avg_dicts(*args): """ Average all the values in the given dictionaries. Dictionaries must only have numerical values. If a key is not present in one of the dictionary, the value is 0. Parameters ---------- *args Dictionaries to average, as positiona...
efe54e9263f5675263aba1bbc775ca38c7d694bb
675,362
def first_ok(results): """Get the first Ok or the last Err Examples -------- >>> orz.first_ok([orz.Err('wrong value'), orz.Ok(42), orz.Ok(3)]) Ok(42) >>> @orz.first_ok.wrap >>> def get_value_rz(key): ... yield l1cache_rz(key) ... yield l2cache_rz(key) ... yield get_...
00ec3f8de716270142715a521cb27fbb3f5a6264
675,364
def add1(num): """Add one to a number""" return num + 1
ae7daac0e4f46d755fd24978b85a4103d93b0e93
675,365
def chomp(string): """ Simple callable method to remove additional newline characters at the end of a given string. """ if string.endswith("\r\n"): return string[:-2] if string.endswith("\n"): return string[:-1] return string
4ad36802075451d6800dda41417db42c919b4f21
675,366
def subtract(datae): """Subtracts two fields Parameters ---------- datae : list List of `np.ndarray` with the fields on which the function operates. Returns ------- numpy.ndarray Subtracts the second field to the first field in `datae`. Thought to process a list of ...
fa493877f1959c86c89e986dbac8d2807afafe05
675,372
import itertools def flatten(list_of_lists): """ Takes an iterable of iterables, returns a single iterable containing all items """ return itertools.chain(*list_of_lists)
8c7a4b3d06e6e959eb20b0b57868a39d317daaf4
675,379
import time def timer(function): """Decorator for timer functions Usage: @timer def function(a): pass """ def wrapper(*args, **kwargs): start = time.time() result = function(*args, **kwargs) end = time.time() print(f"{function.__name__} took: {end -...
09f29d87f25cb04a9cf9e82233f49be476830581
675,383
def add_default_module_params(module_parameters): """ Adds default fields to the module_parameters dictionary. Parameters ---------- module_parameters : dict Examples -------- >> module = add_default_module_params(module) Returns ------- module_parameters : dict ...
4731c6fbe06232f8bedf1b586c5cf01a8b4de336
675,385
def yesno(value): """Converts logic value to 'yes' or 'no' string.""" return "yes" if value else "no"
6b333a4f1bedd2a0f6c07af47fdba11cea8a060f
675,387
def str2bool(val): """ converts a string to a boolean value if a non string value is passed then following types will just be converted to Bool: int, float, None other types will raise an exception inspired by https://stackoverflow.com/questions/15008758/ ...
85d4ee26ccea660014fb9bd2891dcf7bc234e459
675,391
def _find_text_in_file(filename, start_prompt, end_prompt): """ Find the text in `filename` between a line beginning with `start_prompt` and before `end_prompt`, removing empty lines. """ with open(filename, "r", encoding="utf-8", newline="\n") as f: lines = f.readlines() # Find the star...
a77b68257639e877e8a899ae63e97dce3a7f066f
675,392
import math def refraction_angle( theta1, index2, index1=1.0): """ Determine the exit angle (theta2) of a beam arriving at angle theta1 at a boundary between two media of refractive indices index1 and index2. The angle of refraction is determined by Snell's law, sin theta1 /...
348c7add495448424018b964d9d964c9c416bdfe
675,393
def region_key(r): """ Create writeable name for a region :param r: region :return: str """ return "{0}_{1}-{2}".format(r.chr, r.start, r.end)
1f66b7e8b141b97728a6c5f12604bcd17d321df1
675,397
from pathlib import Path def _read_lark_file() -> str: """Reads the contents of the XIR Lark grammar file.""" path = Path(__file__).parent / "xir.lark" with path.open("r") as file: return file.read()
16806475468f02d379bcb0750d1ca62e2c7f4a5f
675,403
def outliers_detect_iqr(s, factor=1.5): """ Detects outliers in a pandas series using inter-quantile ranges Parameters ---------- s : pandas.core.series.Series Pandas Series for which the outliers need to be found factor : int iqr factor used for outliers Returns -----...
681e0d9310e17cf73c7b61f56128a7bde30ad960
675,406
import bisect def compute_previous_intervals(I): """ For every interval j, compute the rightmost mutually compatible interval i, where i < j I is a sorted list of Interval objects (sorted by finish time) """ # extract start and finish times start = [i.left for i in I] finish = [i.right...
cc8c935dc7e1bf5f308e125515d61d250e2d5bcf
675,407
def read_bytes(filename, offset, number): """ Reads specific bytes of a binary file. :param filename: path to file :type filename: string :param offset: start reading at offset :type offset: integer :param number: number of bytes :type number: integer ...
c04c7659211f7bfee3d88b27cd014cea303b13c4
675,408
def combine_roi_and_cav_mask(roi_mask, cav_mask): """ Combine ROI mask and CAV mask Parameters ---------- roi_mask : torch.Tensor Mask for ROI region after considering the spatial transformation/correction. cav_mask : torch.Tensor Mask for CAV to remove padded 0. Returns ...
103021df9035c2ad87cb9735f81d78af700df645
675,409
import re def getDatefromName(fname): """ Returns the date of the form YYYY-MM-DD from fname, or an empty string if there is no string that matches. If there are multiple matches, this returns the first of them. """ dates = re.findall(r"\d{4}-\d{2}-\d{2}", fname) if len(dates) == 0: ...
24bd989c840483cb2f105f6c6f38794984534b9c
675,415
def pname(name, levels=None): """ Return a prettified taxon name. Parameters ---------- name : str Taxon name. Returns ------- str Prettified taxon name. Examples -------- .. code:: python3 import dokdo dokdo.pname('d__Bacteria;p_...
4ae357f82531f6a4b1aeee3007e65a304fa134cb
675,416
def create_parameter(model, parameter_id, value, constant=True, units="dimensionless"): """ Creates new parameter for libsbml.Model. It is not necessary to assign the function to a value. The parameter is automatically added to the input model outside of the function. Parameters ---------- ...
fa7206e53941aa8bfe81f5f1ee1cd764c3c12668
675,418
def datetime_to_string(datetime): """convert a datetime object to formatted string Arguments: datetime {datetime} Returns: [string] -- formatted datetime string """ return "/".join([str(datetime.day), str(datetime.month), str(datetime.year)])
984d49e0f263855b03e7191bbdb549258bd2ca64
675,433
import re def extract_options(text, key): """Parse a config option(s) from the given text. Options are embedded in declarations like "KEY: value" that may occur anywhere in the file. We take all the text after "KEY: " until the end of the line. Return the value strings as a list. """ regex = ...
43089bc40961b50751e008264d6960007747beee
675,438
from typing import Union def map_value( x: Union[int, float], in_min: Union[int, float], in_max: Union[int, float], out_min: Union[int, float], out_max: Union[int, float] ) -> float: """Maps a value from an input range to a target range. Equivalent to Arduino's `map` function. Args: x: t...
06941afe1d269ee622aa1c75564622897cdcde2e
675,439
def _get_workflow_input_parameters(workflow): """Return workflow input parameters merged with live ones, if given.""" if workflow.input_parameters: return dict(workflow.get_input_parameters(), **workflow.input_parameters) else: return workflow.get_input_parameters()
70de5e28c8b7b29258b134b7bd12df24d7cf4d46
675,440
def autocov(v, lx): """ Compute a lag autocovariance. """ ch = 0 for i in range(v.shape[0]-lx): for j in range(v.shape[1]): ch += v[i][j]*v[i+lx][j] return ch/((v.shape[0]-lx)*v.shape[1])
4d05c29171ab92fe353e55e2f63a21a635e87059
675,446
def compute_score(segment, ebsd): """ Compute Dice measure (or f1 score) on the segmented pixels :param segment: segmented electron image (uint8 format) :param ebsd: speckle segmented out of the ebsd file (uint8 format) :return: Dice score """ segmented_ebsd = ebsd >= 128 segmented_se...
b9c2e2db9dcca67d79e46dc5bd489e077918c602
675,447
def get_graphlist(gg, l=None): """Traverse a graph with subgraphs and return them as a list""" if not l: l = [] outer = True else: outer = False l.append(gg) if gg.get_subgraphs(): for g in gg.get_subgraphs(): get_graphlist(g, l) if outer: retu...
1ca173bb3bf526593e1d10360cfe12e913a28b28
675,449
def heads(l): """ Returns all prefixes of a list. Examples -------- >>> heads([0, 1, 2]) [[], [0], [0, 1], [0, 1, 2]] """ return map(lambda i: l[:i], range(len(l) + 1))
a39394ff83edb2254660a58269419825ad8813c4
675,453
def list_subtract(a, b): """Return a list ``a`` without the elements of ``b``. If a particular value is in ``a`` twice and ``b`` once then the returned list then that value will appear once in the returned list. """ a_only = list(a) for x in b: if x in a_only: a_only.remove(...
d0557dbf0467e00c909d143c464f4af76eb130c6
675,454
def _patsplit(pat, default): """Split a string into an optional pattern kind prefix and the actual pattern.""" if ':' in pat: kind, val = pat.split(':', 1) if kind in ('re', 'glob', 'path', 'relglob', 'relpath', 'relre'): return kind, val return default, pat
9ff9eb6a8ba24df3a66ff74bd4bc6feda20d5eda
675,455
def indent_level(level:int): """Returns a string containing indentation to the given level, in spaces""" return " " * level
09532674504a54569130739a8ef92aa37cd93f0b
675,456
import difflib def diff(a, b): """A human readable differ.""" return '\n'.join( list( difflib.Differ().compare( a.splitlines(), b.splitlines() ) ) )
ad683cd696af6b2fd3412fb8c2956213950f5edf
675,458
def getData (tup): """ argument: tuple with tuple of int[0] and string[1] inside return: int for smallest int, largest int, number of unique strings """ numbers = () words = () for elem in tup: if elem[0] not in numbers and (type(elem[0])==int): numbers = numbers + (elem...
2ab4b4df027bdc3d785b0d467fb2929970cd6754
675,464
import time def CreatePastDate(secs): """ create a date shifted of 'secs' seconds respect to 'now' compatible with mysql queries Note that using positive 'secs' you'll get a 'future' time! """ T=time.time()+time.timezone+secs tup=time.gmtime(T) #when="%d-%d-%d %d:%d:%d"%(tup[0],tup[1],tup[2],tup[...
bad798fb9e7588d1bbdbca9a814cf44fdbadb733
675,470
def decompose(field): """ Function to decompose a string vector field like 'gyroscope_1' into a tuple ('gyroscope', 1) """ field_split = field.split('_') if len(field_split) > 1 and field_split[-1].isdigit(): return '_'.join(field_split[:-1]), int(field_split[-1]) return field, None
83dc5f235ab39119b21f1f0e125f2292f812a74c
675,473
def build_path(tmp_path_factory): """Provides a temp directory with various files in it.""" magic = tmp_path_factory.mktemp('build_magic') file1 = magic / 'file1.txt' file2 = magic / 'file2.txt' file1.write_text('hello') file2.write_text('world') return magic
4b715f51ad22985cd9cc6d48f96c15e303ff45b4
675,478
def run_model(model, X_train, y_train, X_test, y_test, params): # pylint: disable=too-many-arguments """Train the given model on the training data, and return the score for the model's predictions on the test data. Specify parameters of the model with the provided params. Args: model (callable): ...
332bcfe0f9b59c370ac5df784e4b443b02ccb23e
675,479
def user_agrees(prompt_message: str) -> bool: """Ask user a question and ask him/her for True/False answer (default answer is False). :param prompt_message: message that will be prompted to user :return: boolean information if user agrees or not """ answer = input(prompt_message + ' [y/N] ') re...
5a9e92ac073d1801a733d0bd1407cba4a6b5f927
675,481
def get(yaml_config, key_path, default_value=None): """ Get a value in a yaml_config, or return a default value. :param yaml_config: the YAML config. :param key: a key to look for. This can also be a list, looking at more depth. :param default_value: a default value to return in case th...
6eaab8c580f34d58558478a730e1279ab4778fcd
675,483
def error_margin_approx(z_star, sigma, n): """ Get the approximate margin of error for a given critical score. Parameters ---------- > z_star: the critical score of the confidence level > sigma: the standard deviation of the population > n: the size of the sample Returns ------- The approximate margin o...
4d2f18e8ee4a80e6e7e565ecd23c8c7413d35dce
675,485
def find_user(collection, elements, multiple=False): """ Function to retrieve single or multiple user from a provided Collection using a dictionary containing a user's elements. """ if multiple: results = collection.find(elements) return [r for r in results] else: return coll...
4e91f45673545bee25d912edcb20edff3dd8d1cb
675,489
def extract_name_and_id(user_input): """Determines if the string user_input is a name or an id. :param user_input: (str): input string from user :return: (name, id) pair """ name = id = None if user_input.lower().startswith('id:'): id = user_input[3:] else: name = user_input...
feb84b022e626bae091bb28e8d3f316bdbf1ba3d
675,496
def selection_sort(integer_list): """ The selection sort improves on the bubble sort by making only one exchange for every pass through the list. In order to do this, a selection sort looks for the largest value as it makes a pass and, after completing the pass, places it in the proper location. As wi...
5558fb9f754a1977ef6cd006022948e10e0438c0
675,497
def minsort(lst): """ Sort list using the MinSort algorithm. >>> minsort([24, 6, 12, 32, 18]) [6, 12, 18, 24, 32] >>> minsort([]) [] >>> minsort("hallo") Traceback (most recent call last): ... TypeError: lst must be a list """ # Check given parameter data type. if...
915c12c9a46e80c04ca04e209a99eea1a726af00
675,498
import logging def possible_int(arg): """Attempts to parse arg as an int, returning the string otherwise""" try: return int(arg) except ValueError: logging.info(f'failed to parse {arg} as an int, treating it as a string') return arg
2d842ca29fa057f0601e44aaea91e7ef8d71738b
675,500