content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def never_resample(): """ Function that always returns false and thereby enables switching off resampling. This function is needed to switch off resampling. :return: Boolean that always equals false """ return False
69a9b8730ed699a505581efc4a4845b01b88543c
647,325
def get_max(self): """Return the maximum value of the ParamExplorer Parameters ---------- self : ParamExplorerInterval A ParamExplorerInterval object Returns ------- max_value: float Maximum value of the ParamExplorer """ if len(self.value) > 0 and isinstance(self....
29897c300e789a3f1e2023ef3a0be86f19456ea9
647,326
from typing import Union from typing import Tuple def divmod_int(numerator: Union[int, float], denominator: Union[int, float]) -> Tuple[int, int]: """Return the result of divmod, as a tuple of integers.""" quotient, remainder = divmod(numerator, denominator) return int(quotient), int(remainder)
71ae719703d68e6c43a4b01e123fbd08b91acb65
647,327
import string def clean_tokens(tokens): """Tokens are lower-cased, stripped of punctuation, and filtered for NULL.""" tokens = [w.lower().strip(string.punctuation) for w in tokens] tokens = [w for w in tokens if w] tokens = tokens or ["NULL"] return tokens
63b36242f4bc44d5018bdd176b62e95b01776649
647,329
def class_mix_data(data): """ > input: [[label, ...], [label, ...], [label, ...], ... ] > output: [ [[label, ...], [label, ...], [label, ...], ... ], <- class 0 [[label, ...], [label, ...], [label, ...], ... ], <- class 1 . . . [[label, ...], [label, ...], ...
41f6d2d2c4c720ff95cf72d51743d80db7ecc47b
647,330
def search(pattern, text): """Search for pattern occurrences in text. Args: pattern: pattern string to be searched (str). text: text string to be searched on (str). Returns: list of indexes of all occurrences. """ result = [] for x in range(len(text) - len(pattern)): ...
a54cdc6fca86a5471d08092989b5a4f491bbd540
647,331
def show_in_nav_for(level=0, icon=None): """ Use as a class / method decorator to flag an exposed object in the site navigation @show_in_nav_for(users.guest) @expose class SubPage: ... """ def decorate(f): f.show_in_nav = level f.icon = icon f.exposed = True ...
030ef8e38ef398f7e3461a11807e12dc15460848
647,333
def get_sha1_or_none(repo, ref): """Return string of the ref's commit hash if valid, else None. :repo: a callable supporting git commands, e.g. repo("status") :ref: string of the reference to parse :returns: string of the ref's commit hash if valid, else None. """ commit = repo("rev-parse", "-...
d20473120136b5f2410b5210a013451bfa68e250
647,336
def anchor_in_soup(soup, anchor_name): """Find if a given anchor id is present in a HTML data""" return bool(soup.find("", {"id" : anchor_name})) or bool(soup.find("", {"name": anchor_name}))
f24d1370f3c1e0f0c7d3e6723014600f219601e4
647,337
import sys import os def versioned_directory(d): """Find a subdirectory of d specific to the Python version. For example, on Python 3.6.4 rc 1, it returns the first of these directories that exists:: d/3.6.4.candidate.1 d/3.6.4.candidate d/3.6.4 d/3.6 d/3 d ...
86ca8d53732f4605729534aaffcb0cb8de03589d
647,338
def directory_fmt(directory): """In ensure that directories end with '/'; fixes recursive copy.""" return directory.rstrip('/') + '/'
3f8da4abf4ff1ec1a07d48f15e675c380597f843
647,339
import os def construct_db_url() -> str: """ Constructs a database url from environment variables """ database_name = os.environ.get("DATABASE_NAME") db_host_name = os.environ.get("DATABASE_HOST_NAME") user_name = os.environ.get("DATABASE_USER") password = os.environ.get("DATABASE_PASSWORD...
53f2e7c7b31bd2753a13d38c8c51fd72807ed1bb
647,341
def is_dualtor(tbinfo): """Check if the testbed is dualtor.""" return "dualtor" in tbinfo["topo"]["name"]
2587bf9d8425bc5b1445e02923a52e28aae6fddf
647,342
def read_lines(path): """ Reads lines from file into list with leading and trailing whitespace removed. """ with path.open() as f: lines = f.readlines() lines = [l.strip() for l in lines] return lines
e7db6ed55daee6aec53deb3aedbdfe8526812801
647,344
def is_date_between(test_date, min_date=None, max_date=None): """ Devuelve True si la test_date está entre min_date y max_date o es igual a alguna de ellas. """ is_higher_than_min = min_date is None or test_date >= min_date is_lower_than_max = max_date is None or test_date <= max_date return is_hig...
35029c09249fdb9f6a76d8f991e477de2baf73be
647,345
def weekly_test_data(): """ Provides test data for the full system test when using "weekly" time_scale.""" time_scale = "weekly" time_per_task = { "Free" : 480 * 9, "Work" : 480 * 5, "Sleep" : 480 * 7 } min_task_time = 60 preferences = { "Free" : { "av...
0a1500f3926f78e0b975a7de9c8defc2f92ff456
647,347
from functools import reduce def get_model_size(model): """Computes the total number of parameters. :param model: A Pytorch's nn.Module model. :return: The number of parameters. """ nb_params = 0 # store original state orig_state = model.training # we want the number of parameter for ...
76aeb71179e86b2fe82e3777a46795b7ffc3d1ce
647,348
def get_sync_vertices(g): """ Returns a list of sync vertices. A sync vertex is a vertex with no outgoing arcs. Args: g: data structure encapsulating graphs. Returns: A list of all vertex names. """ return [v for v in g.get_vertices() if len(g.neighbours(v)) == 0]
2c0a691a9b872b1ebf02333e9976042fb2c4de4b
647,349
import os def none_path_join(partial_path_list): """Join a list of partial paths. If any part of the path is None, returns None. Args: partial_path_list (list): List of partial paths Returns: path or None (str or None): joined path string or None """ if None in partial_path_...
e8b9ef4ea338c408448fa306683375b9ef0b75f2
647,350
def get_no_aliens(sett, alien_width): """Determine the number of aliens that fit in a row. Spacing between each alien is equal to half alien width""" available_space_x = sett.screen_width - 1.5 * alien_width no_of_aliens = int(available_space_x / (1.5 * alien_width)) return no_of_aliens
db9bf8a50c85867dd002fcb70c6e40b24512f606
647,351
import re def remove_comments(code): """ Remove C-style comment from GLSL code string """ pattern = r"(\".*?\"|\'.*?\')|(/\*.*?\*/|//[^\r\n]*\n)" # first group captures quoted strings (double or single) # second group captures comments (//single-line or /* multi-line */) regex = re.compile(patter...
692b1c0380ebc20f71771c4859626f308eb53231
647,352
def lr_schedule(epoch): """Learning rate schedule""" if epoch <= 100: lr = 2e-4 else: lr = 2e-4 * (200 - epoch) / 100 return lr
7c6492aa48cb3a2329e2e52cd2c5fe0e50c1d5a9
647,353
import random import string def _generate_random_code(): """ Generate 6 random characters that can be used as a room code """ return ''.join(random.choice(string.ascii_uppercase) for _ in range(6))
d16c13164c4e65850311051461df5f24a912e293
647,354
def benchmarkRandomFragment( fasta, size ): """returns a random fragment of size.""" contig, strand, start, end = fasta.getRandomCoordinates( size ) s = fasta.getSequence( contig, strand, start, end ) return s
90b4bc90a7aaedbb8f129e1f82eac88225447e39
647,355
def greet(adventurer: str) -> str: """ returns a greeting string that greets the title cased adventurers name >>> greet('bob') 'Hello Brave Bob' :param adventurer: the name of the adventurer to greet :return: a greeting "Hello ..." """ return f"Hello Brave {adventurer.title()}"
3fe2471468254b3f763c07cb80f51fee43466157
647,356
def headers(): """ Posibility adding authorization token to header of request """ return {'Authorization': 'token_secure'}
99d2cb60293bc8fde8eaa2e3fdf18469b74bd3a3
647,357
import os def complete_vel_paths(dictionary, root): """ The velocity dictionary is complicated because we don't want to prepend the data path to a constant velocity. Args: dictionary (dict): A dict of relative file names or directories. root (str): The absolute path to the relative pa...
6bd588843bb2041c592e3e1614e18ce7a79b6c36
647,358
from curses import setupterm, tigetnum import sys import platform import os def terminal_colors(stream=sys.stdout) -> int: """ Get number of supported ANSI colors for a stream. Defaults to sys.stdout. >>> terminal_colors(sys.stderr) 0 """ colors = 0 if stream.isatty(): if plat...
d839a530a35c2ac5b0f94a325338c65bf0187ded
647,360
import six def ascii_to_bytes(seq): """Converts seq from ASCII string to byte array""" return six.iterbytes(seq)
b44827b9b431117ae510115c5a1f2d5aa90b33fb
647,362
def _fixture_to_strings(lines: list, delimiter: str = '\t') -> list: """ Helper so that our unit tests are a little more readable. Real tabix files give delimited strings, not lists of fields """ return [delimiter.join(line) for line in lines]
bf76c2a8228c66d3fa32a9f257fc2ddf146f9e67
647,363
import re def process_tex(lines): """ Remove unnecessary section titles from the LaTeX file. """ new_lines = [] for line in lines: line = re.sub(r'^\s*\\strong{See Also:}\s*$', r'\paragraph{See Also}', line) if (line.startswith(r'\section{sknano.') or line.startswith(r...
21e81a2d208c775a4d4270655539a327cb8a1eb6
647,365
from typing import Optional import platform from typing import Tuple import time def _get_cpu_usage() -> Optional[float]: """ Get the current CPU usage as a percentage. Returns: A percentage value between 0 and 1, or None if the CPU usage could not be determined (most likely because the s...
30ce12b5f811b6e990cee5f908cb38e78ac32f4a
647,366
from typing import Tuple from typing import List def get_mot16_scenario_a() -> Tuple[List[Tuple[int, int, int]], List[float]]: """ https://arxiv.org/pdf/1603.00831.pdf """ centers = [] # timestamp 0 cx = 0 cy = -1 cz = 0 centers += [(cx, cy, cz)] # timestamp 1 cx = 2 c...
1518b7a1f538d662b5a94b6a24953a9b3fc28dd6
647,368
def to_warp_func(parameter1, parameter2, parameter3): """ Test function. <process> <input name="parameter1" type="float" desc="a parameter."/> <input name="parameter2" type="string" desc="a parameter."/> <input name="parameter3" type="int" desc="a parameter."/> <return> ...
a3c887f147bb8cf80d9f1ef79f5909b8738504a2
647,369
import os def _read_lists(fid): """ Read all kinds of lists from text file to python lists """ if not os.path.isfile(fid): return None with open(fid,'r') as fd: _list = fd.readlines() my_list = [] for _item in _list: if len(_item) < 3: _list.remove(_ite...
c3520c2c45558e01cdc8b07b320390d509026cc4
647,370
def split_csp_str(val): """ Split comma separated string into unique values, keeping their order. :returns: list of splitted values """ seen = set() values = val if isinstance(val, (list, tuple)) else val.strip().split(',') return [x for x in values if x and not (x in seen or seen.add(x))]
e5ef698ed6dbb1dd2c9c832926c95b3e85743051
647,371
def dict_to_list(dict_to_convert): """Converts a dictionary to a multi-dimensional array. The first item of the tuple is the key from the dictionary""" result_list = [] for name, values in dict_to_convert.items(): result_list.append([name] + values.get_all_stats()) return result_list
70e92d91d8b336a477d4e96e01cee63177fb638a
647,372
def parse_incar(incar): """ Parameters ---------- incar: str Path to VASP incar Returns ------- encut: int Energy Cutoff """ encut = None with open(incar, "r") as f: for line in f: if "ENCUT" in line: encut = float(line.split("...
97e006818a36f4fbd825eddb23d02cfed044911d
647,373
def find_indices(nums, val): """Given a list, find the two indices that sum to a specific value""" for i, outer_num in enumerate(nums): for j, inner_num in enumerate(nums): if outer_num + inner_num == val: return (i, j) return False
6d162c3a390586cf7e5db6be9a9ed1c5750ac02f
647,374
from sys import stdin def enter_float(): """ Enter a floating point number and check its validity """ number_float = None while not number_float: try: s =stdin.readline() number_float = float(s) if number_float == 0: break except ...
3763aa736ee03c9dd47d09df3b8dda7c28a3dfc1
647,375
def _esbuild_outs(sourcemap, entry_point, outdir): """Supply some labelled outputs in the common case of a single entry point""" result = {} if outdir: # We can't declare a directory output here, because RBE will be confused, like # com.google.devtools.build.lib.remote.ExecutionStatusExcepti...
8adc07dff27c5c67e0ad225db929454554ba3825
647,377
def parse(config): """Read name/address list and return dictionary""" addresses = {} tabus = {} for line in config: line = line.strip() if line: tokens = line.split(":") name = tokens[0] address = tokens[1] addresses[name] = address ...
029a845ef1bb579d461b686bfa43c9c6c2edf847
647,378
def expandtabs(s, tabstop=8, ignoring=None): """Expand tab characters `'\\\\t'` into spaces. :param tabstop: number of space characters per tab (defaults to the canonical 8) :param ignoring: if not `None`, the expansion will be "smart" and go from one tabstop to th...
90220575225518c6db0082c157901dfd19448b9f
647,379
import re from pathlib import Path def markdown_joplin_to_vieweb(md, public): """ Adapt the given md from joplin api so that joplin-vieweb access the images and attachments. Roughly: transform ![image.png](:/id) to ![image.png](/joplin/joplin_ressources/id) """ return md # change links to imag...
bbd44311c9e7533bfb1691dbfe75f42eeea1fc2f
647,380
def get_path_upload_cover_album(instance, file) -> str: """Построение пути к файлу обложки альбома, format: (media)/album/user_id/image.jpg """ return f'album/user_{instance.user.id}/{file}'
7433d7e85942b782a8d48bca3fa7688e24e7a506
647,381
def getOutputShape(model, index = -1): """ Gets the shape of a single output. For compatibility returns the shape of the last output if there are multiple outputs. Return: Numeric dimensions, omits dimensions that have no value. eg batch size. """ s = [] ...
87234355b9ab0ae48abe1912a80b07d1f6c45e09
647,382
import numpy def _frequencies(freq): """ tuple of floats to string """ freq = numpy.array(freq) assert freq.ndim == 1 freq_str = "" for val in freq: freq_str += "{:>8.1f}\n".format(val) return freq_str
dd602fab89818c8c35719e35e966cdb4655f0c82
647,383
def dice_outcome_extractor(run): """Return the atmospheric temperature of the final state.""" return run.states[-1].TATM
f1f6dd3e9796964370289389579bda623f6c5572
647,384
def input_a_float(): """Input a float and return the float.""" return float(input("Saisir un nombre : "))
f7d6e82c6a5101452d1bcf406f887b28b533ecf3
647,385
import argparse def arg_parse(): """Parse command line arguments.""" p = argparse.ArgumentParser() p.add_argument('infile', help='Path to file containing targets.') p.add_argument('n1', help='Night 1 in Y-m-d') p.add_argument('n2', help='Night 2 in Y-m-d') p.add_argument('observatory', help='A...
cf077cda624c6f792f269fccf2820f8287982ffc
647,386
from typing import Dict def retrieve_possible_object_indexes(complex_object: object) -> Dict[str, object]: """ This method retrieves public variables of a class that can be used to build indexes. :param complex_object: :return: """ indexes: Dict[str, object] = {} object_vars = vars(co...
108123f638675d96f64965eb22e6cb9f47940225
647,387
import argparse def get_command_args_predict(): """ Get argument parsed prediction Arguments: input - pathe ti image to predict checkpoint -saved model / checkpoint file category_names - class mapping top_k most likely classes - top k probablities gpu - Use Gpu ...
62f60550c7d60345a0a7bf3f5b0aba5ac59f238d
647,388
import random def random_threshold_sequence(n,p,seed=None): """ Create a random threshold sequence of size n. A creation sequence is built by randomly choosing d's with probabiliy p and i's with probability 1-p. s=nx.random_threshold_sequence(10,0.5) returns a threshold sequence of length 10...
b3d4087e1ef0dfdc0e39234fec4a6ac39920ed86
647,389
def get_mnsp_quantity_bands(data) -> dict: """Get MNSP quantity bands""" interconnectors = (data.get('NEMSPDCaseFile').get('NemSpdInputs') .get('PeriodCollection').get('Period') .get('InterconnectorPeriodCollection') .get('InterconnectorPerio...
6553f3c06abe7b18211072950b4c847f6f66244a
647,390
def __add(thiselement, char): """Shorthand for adding a character....""" if thiselement == None: return char return thiselement + char
06285ddc5320d20f22e394c5d5f4890558d59b61
647,391
def is_np_chunk(tree): """ Returns true if given tree is a NP chunk. A noun phrase chunk is defined as any subtree of the sentence whose label is "NP" that does not itself contain any other noun phrases as subtrees. """ if tree.label() == 'NP' and \ not list(tree.subtrees(lambda ...
48fb62410831a3ae3f2454fb1d2551753ed00fd8
647,392
import numpy def calcQuadCoords(vertices, cells, qpts): """Compute coordinates of quadrature points.""" nqpts = qpts.shape[0] ncells = cells.shape[0] spaceDim = vertices.shape[1] quadCoords = numpy.zeros((ncells, nqpts, spaceDim), dtype=numpy.float64) cellCoords = vertices[cells,:] for iDim in range(sp...
7bb578302149fa4b2fe58267ce011f31f21311b9
647,393
def linear(x, root): """ Returns a decay factor based on the linear function .. math:: f(x) = \\begin{cases} -x/root + 1 & \\mbox{if} x < root; \\\\ 0 & otherwise. \\end{cases} :param x: The function argument *x*. ...
e7e1cfcdab4775f40e157236fbd36eca42729236
647,394
def get_flows_from_logbook(logbook, persistence_backend): """ Gets all flows for a logbook :param obj logbook: A TaskFlow logbook :param obj persistence_backend: A connection to the persistence backend :return iter[obj, ..] all_flows: An iterable of flow objects """ return persistence_backen...
94b16bfe5de55ad635d47600e773d11a6efafc9b
647,395
def load_capcodes_filter_dict(filename): """Load capcodes ignore or match data to dictionary.""" capcodes = dict() try: print("Loading data from '{}'".format(filename)) with open(filename, "r") as text_file: lines = text_file.readlines() for item in lines: ...
92f9ea7c5621cb4c5f2cc9bc0655d2321dc126a8
647,396
import os def get_tents_demo_bin(): """Gets path to compiled binary `tents-demo`. (See README.md for detail).""" tents_demo_bin = os.environ['TENTS_DEMO_BIN'] assert os.path.exists(tents_demo_bin) return tents_demo_bin
b1ea7ac1aae663fd1f86e8d891fbeb6eaaa7cdef
647,398
def insertion_sort_descending(dList): """ Given a unsorted list of integers other comparable types, it rearrange the integers in natural order in place in an descending order. Example: Input: [8,5,3,1,7,6,0,9,4,2,5] Output: [9,8,7,6,5,5,4,3,2,1,0] """ n = len(dList) for i i...
755f469332560639728bbb71fa7db85b2f6e0ce1
647,400
import json def get_cli_body_ssh_vrf_interface(command, response, module): """Get response for when transport=cli. This is kind of a hack and mainly needed because these modules were originally written for NX-API. As such, we assume if '^' is found in response, it is an invalid command. Instead, the ...
56eeb6cd6d6ae48b0887bf6155e9b0fbd449088c
647,401
def verse(bottle): """Sing a verse""" bot1 = 'bottles' if bottle > 1 else 'bottle' bot2 = 'bottles' if bottle - 1 != 1 else 'bottle' next_bottle = bottle - 1 if bottle != 1 else 'No more' return '\n'.join([ f'{bottle} {bot1} of beer on the wall,', f'{bottle} {bot1} of beer,...
1d364e0e9231260fec405c7b69c1a97be3d1961b
647,402
def to_layer(operation_list, num_wires): """Convert the given list of operations to a layer. Args: operation_list (list[~.Operation]): List of Operations in the layer num_wires (int): Number of wires in the system Returns: list[Union[~.Operation,None]]: The corresponding layer ...
e05fed5db3051d4e5d99d2bb91159eabcd87a6f1
647,403
def add_ids(edges): """ Adds ids to edges missing ids """ for e in edges: if 'id' not in e: e['id'] = e['subject'] + '-' + e['predicate'] + '-' + e['object'] return edges
6770ff65eeb4e6d722b226c0333363657be1e7bd
647,404
def read_distances(filename): """ reads in the distances from the file and converts them into meters Args: filename: the name of the file. Returns: list of the distance values from the file converted into meters """ # initialize the list in which we save the distances distance_...
7d565dd05d8a3779d0898e07c9767b460738a1c9
647,405
def float_endf(string): """ convert endf-float format to scientific notation """ if "Inf" in string: string = "0.0" if "." in string: string = string[0] + string[1:].replace("+", "e+", 1) string = string[0] + string[1:].replace("-", "e-", 1) return float(string)
7d57e086f0209078b3f8ff23f42c13450466e57e
647,406
from typing import Hashable def _key_from_dict(d) -> Hashable: """Convert nested dict into a frozen, hashable structure usable as a key.""" if isinstance(d, dict): return frozenset((k, _key_from_dict(v)) for k, v in d.items()) elif isinstance(d, (list, tuple)): return tuple(map(_key_from_dict, d)) els...
da98436c65b71933900f0a59f6ef39a84de665c2
647,407
def istensor(x, attrs=['shape', 'dtype', 'min', 'max']): """ Return true if x has shape, dtype, min and max. Will be true for Numpy and PyTorch tensors. >>> import numpy as np >>> M = np.zeros((2,3)) >>> istensor(M) True >>> istensor([1,2,3]) False :param object x: Any object...
4641642abb1935e41c07d58ca1a83d1a809e8ad8
647,408
def compute_optalpha(norm_r, norm_Fty, epsilon, comp_alpha=True): """ Compute optimal alpha for WRI Parameters ---------- norm_r: Float Norm of residual norm_Fty: Float Norm of adjoint wavefield squared epsilon: Float Noise level comp_alpha: Bool Whether ...
7206d14d41df1f9d9c5e9989f4b9fc36b9b8ae31
647,409
def _return_ordered_config(unordered_config: dict, template_config: dict) -> dict: """Orders the keys in unordered_config according to the order in template_config. Note this function assumes all keys in both dictionaries are identical, including all nested dictionaries. """ # create a dictionary ...
f74f62973511bf26b188c77e6ee6d31367c8fcf6
647,410
import re def get_code(location): """ 获取登录code """ code_pattern = re.compile("(?<=access=).*?(?=&)") code = code_pattern.findall(location)[0] return code
4bc8f46026b9e3f7914f6f972ff1e6e1bcc39554
647,414
def num_to_bitstring(num, length): """Returns string of bits from number, truncated at length. Algorithm: While the number storing the bitvector is greater than zero, find the last digit as (num mod 2) and then bit-shift the string to the right to delete the last digit. Add the digits into a string fr...
c31d233f67febe7a34d5874ff7a098d796c9cffc
647,415
def IDlistGenerator(data): """ This function creates a simple list with all the ids of the threatSightings section, behavior section and threatHunting section. """ uuidList = [] # Full uuid list behList = [] # List with the behavior IDs huntBehList = [] # List with the behavior IDs into the hunting queries ...
6d998cbd617c90e78b1f837d46cb18a678ee95ab
647,416
def getUsersInConversation(cursor, sender_id, bot_id): """ Returns a list of Humhub User IDs participating in the conversation using the sender ID :param cursor: Mysql Cursor :type cusor: mysql.connector.cursor.MySQLCursor :param sender_id: Humhub conversation sender ID :type sender_id: int...
68da3f30c4aa68820c95a4d434528e1bcbc7804b
647,417
import re def embolden(word, quote): """Make word bold in quote, regardless of but maintaining case""" return re.sub(r"(" + word + r")", r"<b>\1</b>", quote, flags=re.I)
2b92ac93742bebc8faddf615782679144586b9e5
647,418
def get_function_name(stack_outputs, function_logical_id): """Obtains the function name from given stack outputs. :type stack_outputs: dict :param stack_outputs: CloudFormation stack outputs. :type function_logical_id: str :param function_logical_id: logical ID of the function resource. :rtyp...
d718f658804344abf4e9c2d6c1fda3261da7385e
647,419
def header_population(headers): """make column headers from a list :param headers: list of column headers :return: a list of dictionaries """ return [{'id': field, 'name': field, 'field': field, 'sortable': True} for field in headers]
0f439daf146bb72a8062d950e62ae87673495f5c
647,420
from pathlib import Path def _get_wb_path(filename): """Path of excel file to import""" workbook_filepath = Path.cwd().joinpath('Workbooks/'+filename) return workbook_filepath
e513c0407950183f9cbc5145be76a926c0565fc4
647,422
import os def get_output_path(path_to_event_file): """Returns the path where the pickle of output data will be stored. Args: path_to_event_file: The path where the event file lives. Used so that the output pickle is stored in that same directory. """ # Get the directory where the event file was fou...
8221c4a47517f3898bd034181534fd1d9d8afe51
647,423
import argparse def parse_arguments(): """ Declare program arguments and handle parsing :return: ArgumentParser object or exit if arguments not satisfied """ parser = argparse.ArgumentParser(description='Iterate through images, decide if the watermark should be white or' ...
ad32bc50e08a15e0f4251b7eb4f6ef8050cb1731
647,424
def adjacent_cloud_Sentinel(Fmask, cloud_shadow, dilatation): """ Return Fmask with all classes (adjacent cloud included). """ cloud_shadow_Fmask = cloud_shadow * Fmask dilatation_Fmask = (dilatation - cloud_shadow) * 4 other_Mask = - (dilatation - 1) remain_Fmask = other_Mask * Fmask re...
d1f3f6187cd208fb9f7fe109c0815e0aad392cd1
647,425
def getRawTimes(grid): """ A helper function to get all times inside a grid, returns a list of times """ times=[] for i in range(grid.getDomainSet().getLength()): times.append(grid.getDomainSet()[i].getValue()) return times
8bc9cdb57069469b9d0ce7eb3a6f3d7dfaf5c67e
647,426
import torch def sum_tensor_gen(dim, m): """Generate the summation matrix for the Laplace basis object. Args: dim ([type]): [description] m ([type]): [description] Returns: [type]: [description] """ return torch.stack( torch.meshgrid(*[torch.arange(1, m + 1, 1) fo...
878896b1629a8e126dbd3baddfc73c4efe1e00f7
647,427
def Activate(line): """Checks if we are reading nodes, elements, or something else Parameters ---------- line : string The line to check for activation Returns ------- active : string 'nodes' if we are going to read nodes, 'elems' if we are going to read ...
323fa110c6a8004008f21dd8ad57170e5e2d59ab
647,428
import json def prettydump(pdu_obj): """Unpack PDU dictionary and dump it as a JSON formatted string""" return json.dumps(pdu_obj, indent=4, sort_keys=True)
e9f53b4213f02613eb581992e0295b40795f5c6c
647,430
def allof(*items): """ allof(*items) → Return the result of “all(…)” on all non-`None` arguments """ return all(item for item in items if item is not None)
2343fded5ad33e65faccdd13f215ddc0dce2d0df
647,431
def negative_dice_parse(dice: str) -> str: """ :param dice: Formatted string, where each line is blank or matches t: [(t, )*t] t = (0|D|2T|FT|2F|F|T) (note: T stands for Threat here) :return: Formatted string matching above, except tokens are r...
473eda79fdf761dc552c4afe193b288f9eb77075
647,432
def gpio_function(pin): """ Shows the function of a GPIO channel. will return a value from: GPIO.INPUT, GPIO.OUTPUT, GPIO.SPI, GPIO.I2C, GPIO.HARD_PWM, GPIO.SERIAL, GPIO.UNKNOWN :param pin: :return: GPIO.INPUT, GPIO.OUTPUT, GPIO.SPI, GPIO.I2C, GPIO.HARD_PWM, GPIO.SERIAL, GPIO.UNKNOWN """ ret...
f75a55be7591530e9d4bd66d9f442b63276133d5
647,433
def bridge_h_1(current_state, goal_state): """ adds up the amount of time remaining on the left side :param current_state: :param goal_state: :return: """ h = 0 for x in current_state.state[0].values(): h += x return h
fbf54a78ffc4c7c5a6b74f662e8216e054c05b96
647,434
from typing import OrderedDict def merge_list(col1, col2): """ Given two sequences col1 and col2, returns a list of the items in them, in order, omitting any from col2 that are also in col1. """ cs = OrderedDict() for c in col1: cs[c] = 0.0 for c in col2: cs[c] = 0.0 ...
b7070f916c75acc627689d6adc56eea316080816
647,435
def show_seconds(value, show_units): """Return nicely formatted seconds.""" if value is None: return "unknown" if show_units: return f"{value} s" return value
24aed8018571c233aaf94079aeee6cff34f63e26
647,436
def isValid(s): """ :type s: str :rtype: bool """ parentheses = {')':'(', '}':'{',']':'['} keys = parentheses.keys() values = parentheses.values() stringList = list(s) seen = [] if (len(stringList) % 2 != 0): return False else: for i in range(len(str...
bee7c37c911d82ddfd0017c95e28334a2b27223f
647,437
def calculate_n50(contigs, assembly_size): """Calculate the n50 of the assembly.""" n50_stats = {'n50': 0, 'l50': 0} total_length = 0 total_contigs = 0 for length in contigs: total_length += length total_contigs += 1 if total_length >= assembly_size//2: n50_stats[...
ee0aaf0f51a0a519fa0bcf954a4e364c7d22f275
647,439
import functools def decorator_of_context_manager(ctxt): """Converts a context manager into a decorator. This decorator will run the decorated function in the context of the manager. :param ctxt: Context to run the function in. :return: Wrapper around the original function. """ def deco...
2d7ff8d728d6d3f73e988f35e7da1993540826b3
647,440
import re def unindent_lines(text, format=None, trailing_newline=True): """ Unindent each line in the string text. Return new version of text. """ # Find the indent lines = text.splitlines() indents = [] for line in lines: if line == '': continue m = re.sear...
2e0547a99738027b7a37740e6b1716e27991e215
647,441
from typing import Callable from typing import Dict import numpy from typing import Tuple def finite_difference( function: Callable, parameters: Dict[str, numpy.ndarray], perturbation_fraction: float = 1.001, ) -> Tuple[numpy.ndarray, Dict[str, numpy.ndarray]]: """A function which calculates the forwa...
8d058e2dde75efb013451226cf9e9505b98e42a6
647,442
def write_iter_in_file(path_to_file_write, iterable, fun_prepline=None, mode="w"): """ Write a iterable as text line in file >>> mi_iterable = ["line1", "line2", "line3"] >>> write_iter_in_file("file.txt", mi_iterable) 3 :param path_to_file_write: path file where write :param iterable: Ite...
108f6948c657b1f2dda913f427732b62d75dadd1
647,443
import time def expectTrue(functional, interval=0.2, timeout=2): """Helper function to run a function with expected latency""" delay = 0 while delay < timeout: if functional(): return True time.sleep(interval) delay += interval return False
e68fef68bc0a1969d6d09e009da53dadbdd5a47f
647,444