content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import sympy def is_sympy(value): """Whether or not this is a Sympy type""" return isinstance(value, sympy.Basic)
d3ee9f7e2db8a441fa2cabb21ec594d496b91dfd
671,040
def yoshiyoshi(): """「にゃーん」を見つけたら、「よしよし」と返す""" return "よしよし"
1208e19cb0cd26172caf4c4c0a9248272b77b30e
671,041
import math def radial_decay(r_nmi, rmax_nmi): """ Calculates the radial decay factor for a given radius. Rmax_nmi < r_nmi: NWS 23 pdf page 53, page 27, Figure 2.12, empirical fit Rmax_nmi > r_nmi: NWS 23 pdf page 54, page 28, Figure 2.13, empirical fit (logistic regression) :param r_nmi: int Poin...
2cc26601fb3cc4c4d45788fb049e60ceaeb18438
671,042
def make_title(soup) -> str: """ :param soup: HTML předzpracované balíčkem beautifulsoup - soup object :return: title stránky """ # v případě nenalezení head nebo head.text if not soup.head or not soup.head.title: return '' return soup.head.title.text
99996149304863b8ee9ee982bc27c34d500de968
671,043
import time def get_date(basename): """Return date object representing date of M3 observation""" return time.strptime(basename[3:11], "%Y%m%d")
09b58050380d703eb85ad22e91e81581c39c9e59
671,045
def num_jobs(num_workers): """How many jobs to run in stress tests.""" return min(100, num_workers * 10)
9bde7dde8ee6777004ac996722ecae30e3c12363
671,046
def air_density(ambient_temperature, conductor_temperature, elevation): """From section 4.5.2, eq 14a, valid for SI units.""" Tfilm = (conductor_temperature + ambient_temperature) / 2 return (1.293 - 1.525e-4 * elevation + 6.379e-9 * elevation ** 2) / ( 1 + 0.00367 * Tfilm )
3598d83a8be1a1c90e1bd438a56739eb20294f86
671,047
import argparse def parse_args(): """Parses input arguments.""" parser = argparse.ArgumentParser() parser.add_argument('-i', '--data', dest='input',default='', help='Path to pkl data file.') parser.add_argument('-o', '--model', dest='output', help='path to save model.', ...
15c432e1e4129c9f42a787e73134b584f8ee6b93
671,048
def subset(data: list, default_length: int): """ Get a subset of a list :param data: list :param default_length: default length of list :return: list """ # Stop if nothing was found: if len(data) == 0: return [] # Select some IDs length = default_length if len(data) > d...
90350f53451b4ef287e47f167b23283340f059ea
671,049
def _MakeOptional(property_dict, test_key): """Iterates through all key/value pairs in the property dictionary. If the "test_key" function returns True for a particular property key, then makes that property optional. Returns the updated property dict. """ for key, value in property_dict.items(): if test_...
eb358f149b41a165efe6bff7c51b2978e176c017
671,050
from typing import Optional import os import tempfile def makeTestTempDir(default_base: Optional[str] = None) -> str: """Create a temporary directory for test usage. The directory will be created within ``LSST_RESOURCES_TEST_TMP`` if that environment variable is set, falling back to ``LSST_RESOURCES_TMPD...
f70dd038e90c13fdf9ffbe871608e950e04ab45c
671,051
def find_index_of_minimum(arr): """Returns the index of the minimum number Arguments: arr {list} -- the input list Returns: int -- the index of the minimum number """ minimum = arr[0] index_of_minimum = 0 for index, item in enumerate(arr): if item < minimum: ...
097ae01d7f69a7cad38cb0fded141240fc42ebd7
671,052
def total_len(s1, s2): """ (str, str) -> int Return sum of the lengths of s1 and s2. >>> total_len("bob", "go") 5 >>>total_len("hey", "and") 6 """ return (len(s1 + s2))
800943431985a4125623cc89580c4e94aebe628a
671,053
def stars(number_of_stars, max_stars): """ For a given number of stars, will return number of stars. :param int number_of_stars: number of stars :param int max_stars: max number of stars :return: a string """ star_true = "★" star_false = "☆" return star_true * number_of_stars + star...
6e72e2d1839641152fa272505108c93cf1d259b6
671,054
def _get_match_groups(ping_output, regex): """ Get groups by matching regex in output from ping command. """ match = regex.search(ping_output) if not match: raise Exception('Invalid PING output:\n' + ping_output) return match.groups()
7780b40cef696167907ce4dd145aa4b178ec81d4
671,055
import os def DoesLocalBranchExist(repo_dir, branch): """Returns True if the local branch exists. Args: repo_dir: Directory of the git repository to check. branch: The name of the branch to test for. """ return os.path.isfile( os.path.join(repo_dir, '.git/refs/heads', branch....
8b7ac8874744e2bde0527b9a6782ae2694603a1a
671,056
from typing import Union from pathlib import Path import sqlite3 def is_database_locked(db: Union[str, Path]) -> bool: """Checks is database locked Notice: This function will block the thread for a while (the timeout is set to 0) """ conn = sqlite3.connect(str(db), timeout=0) try: conn.e...
33f0f95e3d0bedf48dce1620ebcc2852da5c5c4a
671,057
def norm(t): """ normalisiere einen numpy zu werten zwischen 0 und 1 """ return (t - t.min()) / (t.max()-t.min())
408b2698efa8f7338f10d6f2c1177127475829c0
671,058
def _need_loop(v): """ if a variable should loop to concat string :param v: any variable :return: Boolean """ return isinstance(v, list) or isinstance(v, dict) or isinstance(v, tuple)
b6f2a98e49f2233b2a368a1716f904a7845c3ca8
671,059
def struct2spglib(st): """Transform :class:`~pwtools.crys.Structure` to spglib input tuple (cell, coords_frac, znucl). """ return st.get_spglib()
a8d2e08c7e17e507eb9b2992ae834009403bd4e9
671,060
async def rewrite_links( html_file: bytes, data_root: str, ontology_type: str, ontology: str ) -> bytes: """Rewrite relative links as absolute paths and return file.""" _html_str = html_file.decode("utf-8") html_str = _html_str.replace("images", ontology + "/images") html_str = html_str.replace("fil...
f4ae193794bf4f96a0d171c97c01bb963c8f6cd9
671,062
import sys def is_64bit_python(): """ Return True if the Python interpreter is 64-bit. """ return sys.maxsize > 2**32
b86a22c51f97b6a86c23af90195f5b28959f95c1
671,063
import time def date_tag(): """ Returns date tag string "YYMMDD". Returns: (str): date string """ return time.strftime("%y%m%d")
ee655fd6c8650983c7de73207e61caf8e233eb6a
671,064
def get_partners(bam, bams): """ Returns the partner bam files having the same ID """ partners = [] for bam_iter in bams: if bam in bam_iter: partners.append(bam_iter) return partners
d691918b5f7ac8149c5afd0002b8ef245aed4f15
671,065
import random import string def _generate_random_string(N: int = 6) -> str: """ Generate some random characers to use in the captcha. Parameters ---------- N : int Number of characters to generate. Returns ------- str A pseudo-random sequence of lowercase letters and ...
7a6baf14665efa99ad75d431b0d809d28ff1a9c8
671,066
def decrease(raw_table, base_index): """ Convert decrease flag to english """ if raw_table[base_index] == 0: return "stop" else: return "lowering"
4c4d728eec90fb20386a2dc5d7edacfb6a6e69ad
671,068
from passlib.context import CryptContext def make_passwordmanager(schemes=None): """ schemes contains a list of replace this list with the hash(es) you wish to support. this example sets pbkdf2_sha256 as the default, with support for legacy bcrypt hashes. :param schemes: :return: CryptCon...
fe278c057e735aca56716ecf397f7664ff010a37
671,069
def expand_dims_match(x, target): """ Expands dimensions of x to match target, an efficient implementation of the following process while len(x.shape) < len(target.shape): x = np.expand_dims(x, -1) """ assert x.shape == target.shape[:x.ndim], (x.shape, target.shape) return x[(*[...
1e07acc8dcac4b8d4ba0866e3a0b052d1a580941
671,070
def create_training(lines, token_to_id): """Takes in the flattened filtered data. Creates the training samples for the Baum-Welch algorithm. """ for idx, line in enumerate(lines): lines[idx] = map(lambda t: token_to_id[t], line) return lines
581b9b917e3513e1f08e50f43d50a430efee7384
671,071
import torch def predict_fn(input_data, model): """ Predict stock prices Parameters: ---------- input_data(num of samples, lookback): input data model: trained model Returns: -------- output (num of samples, output_size): predictions """ ...
5a2848a9fbcaa82d04ec97747d821346fbda8d2f
671,072
def map_lammps_to_database(keywords): # type: (dict) -> dict """ Takes a dictionary of mdp-parameters and converts it to the keywords used in the database. Parameters ---------- keywords : dict dictionary from LogFileReader Returns ------- dict dictionary of map...
da1e76c295ad8e829fe8ebb16e8ce0c69379a9e1
671,073
def missing_metadata_field() -> str: """Return a schema with missing metadata key.""" return """{ "type": "struct", "fields": [ { "type": "string", "nullable": true, "name": "name", "metadata": {} }, { "type": "integer", "nullable": true, "...
16d199d5b0f6ba3fc869c0395d60278baaf0bb37
671,074
def vector_cross(vector1, vector2): """ Computes the cross-product of the input vectors. :param vector1: input vector 1 :type vector1: list, tuple :param vector2: input vector 2 :type vector2: list, tuple :return: result of the cross product :rtype: tuple """ try: if vector1...
91710f5513201bf58c4f58bf3f2bcc9c1fa3b5bf
671,075
from typing import Callable from typing import Any from typing import Sequence from typing import Tuple from typing import List def partition( predicate: Callable[[Any], bool], iterator: Sequence[Any] ) -> Tuple[List[Any], List[Any]]: """A stable, out-of-place partition.""" results = ([], []) for...
533a8a00407c2afb8b43c7baacca30c82c09fda1
671,076
def after_space(s): """ Returns a copy of s after the first space Parameter s: the string to slice Precondition: s is a string with at least one space """ return s[s.find(' ') + 1:]
d16fe547b562a7089a0babf9578e7a06f7a1f69e
671,077
def str_to_microsec(str_1, str_2): """ Change the 2 provided numbers into a number of microseconds. Examples inputs: "100", "us" "2.76", "ms" "3", "s" """ if str_2 == "us": k = 1. elif str_2 == "ms": k = 1.e3 elif str_2 == "s": k = 1.e6 els...
7155d56351e6c2820a81d27b89b400110aec3769
671,078
def leiaDinheiro(mensagem): """ -> Verifica se o preço está no formato de dinheiro :param mensagem: Mensagem a ser exibida ao usuário :return: Retorna o preço convertido para float """ while True: preco = input(mensagem).strip() analisa_preco = preco # Em caso de preco c...
0b76c8d8d24adf0dee13255603c63fc4e65abcfb
671,079
def binom(n, k): """ *DESCRIPTION OF FUNCTION* Parameters ---------- n : int First number in the binomial coefficient. Can be thought of as the set being drawn from k : int Second number in the binomial coefficient. Can be thought of as being the nuber of items drawn from the se...
af29dd2f5e9848391898b9fd010cb66a1eec3faf
671,081
def no_duplicates(route): """ This function removes duplicate nodes that may be present in a route, ensuring it can be plotted. Parameters ---------- route : list list of nodes traversed by route, in order Returns ------- route : list list of nodes traversed by route, i...
aeb97e7370c0bf1d4a25c40264d5673fcea7f162
671,082
def single_function_to_run(batch, function_to_run): """ apply a list of functions on a batch of data """ for fn in function_to_run: batch = fn(batch) return batch
6bf769541346177b45156c8d1c9c93318f3fddf1
671,083
import re def de_camel(s: str, separator: str = "_", _lowercase: bool = True) -> str: """ Returns the string with CamelCase converted to underscores, e.g., de_camel("TomDeSmedt", "-") => "tom-de-smedt" de_camel("getHTTPResponse2) => "get_http_response2" """ s = re.sub(r"([a-z0-9])([A-Z])",...
604d149f809720d1912421e5a634429ceb2990d3
671,085
def value_at_coords(raster, x, y, band=1): """value at raster native coordinate system""" gen = raster.sample(xy=[(x, y)], indexes=band) return gen.next()[0]
c165b7d84785cddf4b01cdbd781f82d43d08c376
671,087
from typing import Sequence def wordpiece_tokens_to_normalized_text(wordpiece_tokens: Sequence[str]) -> str: """Concatenates wordpiece tokens to a normalized text and cleans up. The wordpiece tokens are results from BERT tokenization. They may contain symbols of '##' or ' ##' and some extra whitespaces. The fu...
f8dcdbb1c62b705495bd1c1cc7d35a928ebafa2c
671,088
import math def _realroots_cubic(a2, a1, a0): """gives the real roots of x**3 + a2 * x**2 + a1 * x + a0 = 0""" # see http://mathworld.wolfram.com/CubicFormula.html for details Q = (3*a1 - a2*a2) / 9.0 R = (9*a2*a1 - 27*a0 - 2*a2*a2*a2) / 54.0 D = Q*Q*Q + R*R if D > 0: # one real and ...
bb289af08d4f4d825133a8066b794980ae9b15b8
671,089
def get_assembly_ref_from_genome(genome_ref, ws_obj): """ Given a Genome object, fetch the reference to its Assembly object on the workspace. Arguments: ref is a workspace reference ID in the form 'workspace_id/object_id/version' ws_obj download workspace object for the genome Returns a work...
dd7ed899646cc284eda4e3493cce5388d1be9381
671,092
def get_string_by_card(all_strings, card=None, string_number=None): """Reduce the boundary_strings dataframe to a single card type or a single string number Args: all_strings: dataframe AdhSimulation.BoundaryCondition.boundary_strings dataframe card: string String ca...
d81144c39e3940763ac3ba6cf708f40982a5242f
671,093
def which_percentile(value, d): """ Returns the percentile of 'value' in 'd's distribution. :param value: The value whose percentile is required :param d: A pandas.Series or Numpy array which represents the distribution :return: int """ if len(d) == 0: return 0 return sum(d < va...
b521836055ba33175e9950aaf73ccafa79177f9d
671,094
from typing import List from typing import Dict from typing import Callable def solve_volume_based_compartments( compartments: List[Dict[str, float]], volume_nomo: Callable ) -> List[Dict[str, float]]: """Traverse a series of volume-based nomographs from the bottom compartment (retention) to the top compa...
6e20b552ab7dae1654e572230613c64f53c86bd4
671,097
import sys def prepare_for_reraise(error, exc_info=None): """Prepares the exception for re-raising with reraise method. This method attaches type and traceback info to the error object so that reraise can properly reraise it using this info. """ if not hasattr(error, "_type_"): if exc_in...
c66b23ddab0e56ef135d0fba8e359a62b83f718b
671,098
def floatify(item, default=0.0): """Another environment-parser: the empty string should be treated as None, and return the default, rather than the empty string (which does not become an integer). Default can be either a float or string that float() works on. Note that numeric zero (or string '0') ret...
29598351223dede5ca6b0b4da549b6d1f29c452f
671,100
import inspect def getdoc(obj): """Stable wrapper around inspect.getdoc. This can't crash because of attribute problems. It also attempts to call a getdoc() method on the given object. This allows objects which provide their docstrings via non-standard mechanisms (like Pyro proxies) to still be...
065e15b2e0d583fcbc0162e2865c1defb8595a06
671,101
def creds(request): """Fixture to share creds across the test class""" return request.config.getoption("--creds")
8474146b82041975df2b53c4cff8b93b541c0498
671,102
def total_root_by_year(df): """A function that calculates the total by year & root categories then unstacks the year""" return df.groupby(level=[0, 3]).sum().unstack(['Year']).fillna(0)
7e385c6c1b48c059d7b2f8fa2ab5ebe31caae15f
671,103
import re def build_key_pattern(genus): """Build a regex pattern for the genus key Parameters: genus - the genus of the file (a string) The pattern has one subgroup: the genus and species name """ # --- Species name from index line --- # # Relies on the assumption that index lin...
c87787dbf2b25ba33c3b5da5b97860d6fd1271ae
671,104
def first(t): """Return first item in array or None.""" return t[0] if t else None
b49b710920dcdf59f7ade26639048cb6a96fb6dc
671,107
import torch from typing import Optional def torch_huber( y_true: torch.Tensor, y_pred: torch.Tensor, sample_weight: Optional[torch.Tensor] = None, a: float = 0.9, ): """Computes Mean Huber Error. Args: y_true: true target values. y_pred: predicted target values. sampl...
a8251b9ba8f32fe684fbe641eb9333f6d5bc85c6
671,108
def date_to_json(value, obj): """Serialize a Date value.""" if value is None: return value else: return value.strftime('%Y-%m-%dT%H:%M:%S.%f')
c4426e17c7e08e6e357c8930f3f8ce7a0244f12f
671,109
def get_attributes_string(class_name, object_dict): """Unimportant utility function to format __str__() and __repr()""" return f"""{class_name}({', '.join([ f"{str(k)}: {str(v)}" for k, v in object_dict.items() ])})"""
b1f8ce4a15c423e419cd21f6ae5276f70d237b83
671,110
import requests import json import time def post_issue_comment(issue, comment_text, github_auth): """Attempt to post an issue comment and return whether it succeeded.""" r = requests.post("https://api.github.com/repos/mapserver/mapserver-import/" "issues/%s/comments" % issue['number'], ...
64c20596129fe07d6e3eebe51c032110ced01d20
671,111
def get_length(inp): """Returns the length""" return float(len(inp[0]))
cc3c5c6a054c580d7d121ee60ea91aab6e187d6d
671,112
def strip_domain_from_canonical_name(location: str, domain_dns_name: str) -> str: """ Given a location that is not a relative distinguished name, normalize it by re,oving the domain dns name and leading / if necessary. """ domain_lower = domain_dns_name.lower() if not location: # root of the domain...
f4b2de603fb288e8d19b04a53ec27f320f35b38b
671,113
import os import sys from datetime import datetime import subprocess as sp def bash(args): """ A task runner for bash """ cmd, task_id, job_id, workdir = args os.chdir(workdir) log_path = os.path.join( os.path.abspath('.dlauncher-rmi-%s' % job_id), 'task-%05d') out_file = open((l...
56edab2dd622675d79151d48ef657182850cdd77
671,114
def test_integrity(param_test): """ Test integrity of function """ param_test.output += '\nNot implemented.' return param_test
7e7ef1d24581c432d9df4003ce750531852d107e
671,116
def _html_template(site_name, author, js_snippet, css_snippet): """Create a HTML Template given a site name, author, snippet to include JS files and CSS files """ template_data = { 'site_name': site_name, 'author': author, 'js': js_snippet, 'css': css_snippet } wi...
16726c344a441c43e097fbb0f5445f08fb767ecb
671,117
def import_default(module_name, force=False, default=None): """ Provide an implementation for a class or function when it can't be imported or when force is True. This is used to replicate Pandas APIs that are missing or insufficient (thus the force option) in early pandas versions. """ i...
ffaba80de90bdacb81422070e5edad22443a305d
671,118
def new_network(address, ssid, frequency, encrypted, encryption_type, mode, bit_rates, channel): """{ address, ssid, frequency, encrypted, encryption_type, mode, bit_rates, channel }""" network = { 'address' : address ,'ssid' : ssid ,'frequency' : frequency ,'encrypted' : encrypted ,'encryption_type': encr...
209278f41571ad3771c1f16ea9a28265b2e0ff85
671,119
import math def calc_distance_2points(p1: tuple, p2: tuple): """ uses the hypothenus method to calculate the straight line distance between two given points on a 2d cartesian plane. :param p1: point 1 :param p2: point 2 :return: """ return math.hypot(p2[0] - p1[0], p2[1] - p1[1])
c8962fce968d533044a677f169aa7d17a0091599
671,122
import time def format_timestamp(secs): """Format a UNIX timestamp using ISO 8601 format. Args: secs: the number of seconds since the Epoch to convert into a timestamp Returns: an ISO 8601 compliant timestamp of the form "yyyy-mm-ddThh:mm:ssZ" """ return time.strftime("%Y-%m-%dT%H...
8f5b90f6ecd34b43ae78905cd3e8e2e88ffe46e6
671,123
import re def parse_table(table_lines): """Parse lines into a table. Table example: ```txt ID# Name Designation IAU/aliases/other ------- ---------------------------------- ----------- ------------------- 0 Solar System Barycenter ...
7bb45501cd13ff19105d700cb90c29ee5c136cbc
671,124
def getBucketName(year, month, day, radar): """ Get the name of a specific bucket where radar data is stored. Args: year: Year as an integer. month: Month as an integer. day: Day as an integer. radar: The 4 letter name of the radar, a string. Returns: The bucket nam...
ba92936b7a4bf0df57d46a64b440701d6705035d
671,125
def getSongImage(res): """ getSongImage(res): Image of songs :param: res: all information about the playlist -> getResponse(pl_id) :returns: list of all images to each song """ imagesList = [] # goes through all 100 songs (or less) for track in res['items']: imagesList.appen...
1f3cbf1da6bc16abbcec3bb61dbb62a0c3aeac92
671,126
def first_element_pivot(inputArray): """ The pivot subroutine given that we must take the first element of the array as pivot. """ pivot = inputArray[0] j = 1 for i in range(1, len(inputArray)): if inputArray[i] < pivot: inputArray[i], inputArray[j] = inputArray[j], inputArray[i]...
0c95b6e0a3fd05b4cad4aa4904e6a2991dcfc381
671,127
import math def __get_pooled_standard_deviation(s1: float, s2: float, n1: int, n2: int) -> float: """Calcultes pooled standard deviation Args: s1 (float): standard deviation of sample 1 s2 (float): standard deviation of sample 2 n1 (int): no observa...
6df03f669fbf41869b70d3dd085a26be4599f9af
671,128
def dummy_token(create_token): """Return a dummy token.""" return create_token()
b9e0c85af760445ab19dba2f2f10d244caf00c38
671,129
import ast def status_from_analysis(line): """ Utility method to obtain the process status boolean flags from the relative line in the final analysis output text file. :param line: string from log file :return: list of boolean status flags """ line = line.strip().split('\t') return [a...
7983bd8d9e74a457a019b912cdaa0a1b31272bd9
671,130
from pathlib import Path import glob import torch def read_expert_trajectories(folder_path): """ reads expert features found in folder_path. :return: torch tensor of all features of all expert trajectories. :rtype: torch float tensor, shape of (num of total features x feature length) """ fea...
1c8130671c10156c909ff528693d9984004a1538
671,131
def add_parser_arguments(parser): """Add arguments to an `argparse.ArgumentParser`.""" parser.add_argument( '--data', type=str, help='path to AnnData object with "spliced", "unspliced", "ambiguous" in `.layers`', ) parser.add_argument( '--out_path', type=str, ...
a26d5d918bb29c8f5bea8f312266d440ce07d4fd
671,132
def manage_addBooleanIndex(self, id, extra=None, REQUEST=None, RESPONSE=None, URL3=None): """Add a boolean index""" return self.manage_addIndex( id, 'BooleanIndex', extra=extra, REQUEST=REQUEST, RESPONSE=RESPONSE, URL1=URL3)
e8a43ee859466bf1d8362ffad242eeeee954c199
671,133
import numpy def argmin_use_numpy_select_last_index( data, axis=0, keepdims=True, select_last_index=False): """ Needed or operator `ArgMin`. """ if select_last_index: result = numpy.argmin(data, axis=axis) if keepdims and len(result.shape) < len(data.shape): result ...
1bf18069dfba936990cdd5bd1a7f29704e3aef2a
671,134
def insertion_sort(arr): """ insertion sort using swap Time: O(n^2) Space: O(1) """ for i in range(1, len(arr)): j = i while j > 0 and arr[j - 1] > arr[j]: arr[j - 1], arr[j] = arr[j], arr[j - 1] j -= 1 return arr
6b847f7f2fda869f40d7780f1f7777e944fde3ed
671,135
def combineLabels(timexLabels, eventLabels, OLabels=[]): """ combineTimexEventLabels(): merge event and timex labels into one list, adding instance ids @param timexLabels: list of timex labels for entities. @param eventLabels: list of event labels for entities. Includes no instances labeled as ...
fcc3421c3f38787a5ee9e262b5a1056df0f95ad2
671,137
def is_image(tensor): """ Check if a tensor has the shape of a valid image for tensorboard logging. Valid image: RGB, RGBD, GrayScale :param tensor: (np.ndarray or tf.placeholder) :return: (bool) """ return len(tensor.shape) == 3 and tensor.shape[-1] in [1, 3, 4]
738053703853410873befd7ece0154572ad926fd
671,138
def slice_parents(parent1, parent2): """ Crossover method 1: ==================== Slices the seeds of both parents in the middle and combines them. Retruns the combines new seeds. """ length = len(parent1) // 2 child_seeds = parent1[:length] + parent2[length:] return child_seeds
d77fb0cd62a95d8601ec414b4d56fb2eeb5e1fbd
671,139
import re def condense_output_list(output_list, options): """ Takes the "output_list", made of list of blocks of different type and merges successiv blocks of the same type. >>> condense_output_list([[['inputBlock', 'a', 4]], ... [['inputBlock', "b", 2], ['outputBlock', 'c', ()]]], ...
f1662aecfec363e1ec4d36202b9f92ec44395520
671,140
def file_to_ids(file_path): """Read one line per file and assign it an ID. Args: file_path: str, path of file to read Returns: dict, mapping str to ID (int) """ str2id = dict() with open(file_path) as file: for i, line in enumerate(file): str2id[line.strip()] = i ...
970085bae7df57dcde8c1ede5a14070f12aa2c55
671,141
from typing import Union def is_close( actual: Union[int, float], expected: Union[int, float], threshold: Union[int, float] ) -> bool: """Compare the difference between two input numbers with specified threshold.""" return abs(round(actual, 2) - round(expected, 2)) <= threshold
f2edf48d6475429b230fd751a3ef899461c84e1f
671,142
def replace_consts_with_values(s, c): """ Replace the constants in a given string s with the values in a list c. :param s: A given phenotype string. :param c: A list of values which will replace the constants in the phenotype string. :return: The phenotype string with the constants replaced...
c04b44e338288709130ad930b833d6de4f3fece2
671,143
import re def truthtable2dict(vnumber): """read the truth table from a file, build one related dictionary. Args: vnumber: the number of variables on the last truth table. Returns: truthDict: one dictionary on the truth table, key: the integer value of the truth table, ...
7a1c9448c3061334ea201729b6b87ddf5e599332
671,144
def addrank(self, rankid, entry_rep: int, budget: int, roleid: str): """ Register a rank and role into the database. """ row = self.get_rank(rankid) if row is not None: return False self.cursor.execute( "INSERT INTO ranks VALUES (?, ?, ?, ?)", (rankid, entry_rep, budget, roleid),...
f1b7282d7f920c128d481f65f75eb66b5b2753a7
671,145
import random def calculate_countdown__random(count: int, index: int, duration: int) -> int: """ 把周期任务通过随机数的方式平均分布到 duration 秒 内执行,用于削峰 :param count: 任务总数 :param index: 当前任务索引 :param duration: 执行周期 :return: 执行倒计时(s) """ return random.randint(0, max(duration - 1, 1))
1c7854f6013d85c97d16f0b21bc851232faf6a8d
671,146
def _retrieve_door_state(data, lock): """Get the latest state of the DoorSense sensor.""" return data.get_door_state(lock.device_id)
99bd72bca095b8a375fd02e41310bd93963f8205
671,147
def read_file(filename): """Reads a file. """ try: with open(filename, 'r') as f: data = f.read() except IOError as e: return (False, u'I/O error "{}" while opening or reading {}'.format(e.strerror, filename)) except: return (False, u'Unknown error opening or re...
15df20899ad9c879fa8f8b7059fe70fa30bfb371
671,148
def threshold_data(datasets, threshold=None): """Deterministically thresholds probabilities to binary variables """ for k, v in datasets.items(): if k.endswith('.data'): if threshold is None: thresh = 0.5 elif isinstance(threshold, dict): thresh =...
c999ff20e118857ba60c582afc2e76dab43c30dd
671,149
from typing import Dict from typing import Any import yaml from pathlib import Path def read_yaml_file(filename: str) -> Dict[str, Any]: """Reads a YAML file, safe loads, and returns the dictionary""" cfg: Dict[str, Any] = yaml.safe_load(Path(filename).read_text()) return cfg
b8908e0069530ccd9f358841e5a9309c3d5b4e13
671,150
import torch def mask_center(x: torch.Tensor, mask_from: int, mask_to: int) -> torch.Tensor: """ Initializes a mask with the center filled in. Args: mask_from: Part of center to start filling. mask_to: Part of center to end filling. Returns: A mask with the center filled. ...
5a6da46b0c50719abddd2de7d4e7882bca419b27
671,151
import os def fetch_stop_words(path="../data/chinese/stopwords.dat"): """ 组装停用词 :param path: :return: """ try: if os.path.exists(path) is False: raise Exception("file not exists") infile = open(path, 'r', encoding='utf-8') stopwordslist = [] for str ...
95906410cc1a5bc5256cf203bbaa77a99315eb77
671,152
import os import json def load_relative_config_as_dict(experiment_path): """ Load the contents of the config file as a dict object """ base_path = os.path.dirname(experiment_path) rel_path = "config.json" path = os.path.join(base_path, rel_path) json_dict = None with open(path) as json...
e30a430f89df06b3855e8eb04d1f0c0fdc16a790
671,153
import sys def requires(moduleName): """Marks a function as requiring an optional module dependency.""" def decorate_function(fn): def wrapper(*args, **kwargs): if moduleName in sys.modules: result = fn(*args, **kwargs) return result else: ...
2a2cadb3b1583bf1cc2bafe40f6dd4b520f0d82f
671,154
import os def abspath(path, verify=True): # pragma: io """Combo of :func:`os.path.abspath` and :func:`os.path.expanduser` that will also check existence of directory. Parameters ---------- path : str Relative path string that can also contain home directories, e.g., ``"~/git/"``. verify ...
e8cd4fd631ad19d3cfe01732e7622b5df9c27299
671,155
def momentum_units_label_gev() -> str: """ Generate a GeV/c label. Args: None. Returns: A properly latex formatted GeV/c label. """ return r"\mathrm{GeV/\mathit{c}}"
32d1a2b30537a469318b581d8d066bce19899ab0
671,156