content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def build_ns_name(prefix, identifier): """Builds a namespace name from the given prefix and identifier :param prefix: The prefix which must end with '-' for legacy reasons :param identifier: The id associated with the namespace """ return prefix + identifier
b048ab8dca66d958ae3a6836eb0dcf886628f047
578,378
import pathlib import json def input_data(file): """Read json instruction file to store record i.e. api details to the database.""" # load in the instructions to add building outlines api from LINZ file_path = pathlib.Path().cwd() / pathlib.Path(file) with open(file_path, 'r') as file_pointer: ...
d55bc0192b0f04aca44231d5321fd5fd44b90019
578,380
import random def random_higher_num(size_list): """ Generates a random number list and finds the bigger @params: size_list => integer that defines the size of the random list @return: tuple => max_number ordered_random_list """ random_list = [random.randint(-500, ...
7440e0bdde26b4d8bd7f781dccbd6563db2c6420
578,381
def _trim_quality(seq, qual, to_trim, min_length): """Trim bases of the given quality from 3' read ends. """ removed = 0 while qual.endswith(to_trim): removed += 1 qual = qual[:-1] if len(qual) >= min_length: return seq[:len(seq) - removed], qual else: return None...
8aa42a0cf4df8cbfd73e3bb464430ef8bf57b0e0
578,382
import torch def indexes_to_one_hot(indexes, n_dims=None): """Converts a vector of indexes to a batch of one-hot vectors. """ #SRC: https://discuss.pytorch.org/t/fastest-way-of-converting-a-real-number-to-a-one-hot-vector-representing-a-bin/21578/2 indexes = indexes.type(torch.int64).view(-1, 1) n_dim...
6f848e19fdc63c1ed7e7f7e9672a4b8ef1d5c9ba
578,387
from datetime import datetime def str2time(string, pattern): """convert the string to the datetime.""" return datetime.strptime(string, pattern)
11140342e3c035a75cc9973acc927d9fc235c790
578,388
def is_empty_line(line: str) -> bool: """ Tell if a line is empty. Arguments: line: The line to check. Returns: True if the line is empty or composed of blanks only, False otherwise. """ return not line.strip()
b1c0854cdacf7b18a9f616910fbb046cebb87e4b
578,394
def scheme_false(val): """Only False is false in Scheme.""" return val is False
aa9c77c53d22b17d925b09a88846ea67ad3107ae
578,401
import uuid def GenerateUniqueName(prefix=None, suffix=None): """Generate a random unique name using uuid4. Args: prefix: String, desired prefix to prepend to the generated name. suffix: String, desired suffix to append to the generated name. Returns: String, a random name. "...
4492f84325092d0bac19ebc00f339093c5267733
578,402
def prefetch_photo_urls(pets): """Prefetch photo_urls related to pets in queryset.""" return pets.prefetch_related('photo_urls')
34b9eae36e2b261362c681054e44ef406f5ea9c3
578,408
def checkOtherPointsClicked(game, clickX, clickY): """ If one of the opponent's points cards has been clicked, return the card that was clicked, else None """ for card in game.otherPlayer.pointsCards: if card.imageObj.collidepoint(clickX, clickY): return card return None
f65b791e1048a0e27389e5e12187df175dff1041
578,412
def meters_to_feet(meters): """Converts meters to feet. Args: meters: A distance in meters. Returns: A distance in feet. """ return meters / 0.3048
319e0e5b2dd18fe06dfe0e4b3a669592db029dda
578,414
def make_things_v2_file(sensors): """Creates and returns the contents of a file that can be used to Copy and Past values into the fields used for setting up a Things Network version 2 device. """ contents = '' app_euis = set() for s in sensors: dev_id = f"{s['model']}-{s['bldg_abbrev']}...
faf8ae8e432b502a301ea21701912a57c3ab786d
578,415
def num_is_int(num): """ Check whether a number is an integer. :param num: :return: """ return float(num).is_integer()
87c67cc64da2477332298170169d0f1e85b5b777
578,425
def max_scaling(x): """ Scaling the values of an array x with respect to the maximum value of x. """ return [i/max(x) for i in x]
7f8eecd9c59dad45053248ba6aa90411401a2a68
578,426
import random import string def create_filename(in_filename): """Create random filepath.""" random_str_len = 10 random_name = "".join(random.choices(string.ascii_lowercase + string.digits, k=random_str_len)) return random_name + ".epub"
97a16198500cffeeacc26055818a0049e0e95803
578,427
def utm2mgrs(e, n, grid, zeros=0): """ Convert UTM easting/northing pair and grid zone to MGRS-style grid reference, e.g. "18Q YF 80 52". Adapted from http://haiticrisismap.org/js/usng2.js """ square_set = int(grid[:-1]) % 6 ew_idx = int(e / 100000) - 1 # should ...
5aae5469ba62d64d4d37b973358aebd065f5e933
578,429
def query( otherwise, uri ): """Extract the query component.""" first = uri.find('?') if -1 == first: return otherwise last = uri.find('#') if -1 == last: return uri[1+first:] elif last < first: return uri[1+first:last] return otherwise
b3b02d4ec605ee0ebdaaf1ef8d917b281c523ee9
578,430
def rebin(x, factor): """ Rebin a vector, or the first dimension of an array, by averaging within groups of "factor" adjacent values. """ if factor > 1: x = x.reshape(len(x)//factor, factor, -1).mean(1).squeeze() return x
c4cd1a0630131e9f22e4a8aaf0da62e798ac4f54
578,433
def nb_cases_vides(game): """ Renvoie le nombre de cases vides dans la grille. Paramètre game : matrice numpy 4x4 représentant la grille du jeu. """ nb = 0 for i in range(4): for j in range(4): if game[i, j] == 0: nb += 1 return nb
ef0b4b35ff88a7f5daf22cd05602fc150bfe151f
578,435
def alphaList() : """List of upper case letters for comparison.""" return list(map(chr, range(ord('A'), ord('Z')+1)))
beea40bfd120a51b2bdb23675c2531632e07249f
578,436
def compute_missing_citations(cittopics, outcitations): """ This function is used to compute the missing citations for a paper :param cittopics: the CitTopic :param outcitations: the list of records including outcitations :return: a list of missing citations """ missing = [] for c in cit...
284e99a836c591192942e273c5680d2a753d3a92
578,439
from datetime import datetime def execution_date_to_millis(execution_date): """converts execution date (in DAG timezone) to epoch millis Args: date (execution date): %Y-%m-%d Returns: milliseconds """ date = datetime.strptime(execution_date, "%Y-%m-%d") epoch = datetime.utcfr...
1d5d9299545680afcbe97cc13b087cec0f4273ff
578,440
from typing import List def _text_contains_terms(field_text: str, search_terms: List[str]) -> bool: """Checks if any of the provided search terms was found in the provided text. Args: field_text: A string representing a product field value. search_terms: A list of localized terms to find in the field_tex...
72203d8396fe8e29a69c0ac36daffd6f4fca45c3
578,442
def create_silence(length): """Create a piece of silence.""" data = bytearray(length) i = 0 while i < length: data[i] = 128 i += 1 return data
819c232ab24408511f060a6dea0259208571a086
578,445
from typing import Union def str_lower(batch: Union[str, list, tuple]): """Recursively search for strings in a list and convert them to lowercase Args: batch: a string or a list containing strings at some level of nesting Returns: the same structure where all strings are converted to low...
936f0633fd991ed0ba1671b9722c4ae574e3fc5b
578,453
def pairwise(nodes): """Create pairs of nodes: 1->2, 3->4, ...""" group1 = nodes[::2] group2 = nodes[1::2] return zip(group1, group2)
c38d424987154fca16a6e3eb650142beb1be8729
578,456
def safe_index(object, keys): """Safely index a document, returning None if the value isn't found.""" if len(keys) == 1: # first check dict lookups, in case of conflicting property names # with methods (e.g. case/update --> a dict's update method when # it should be the case block's upda...
018c227000267317224b10bec3f7b08dcdf312a1
578,457
from typing import List def to_bits(integer: int, bit_length: int) -> List[int]: """ Convert a given integer to a list of bits, with the least significant bit first, and the most significant bit last. :param integer: Integer to be converted to bits. :param bit_length: Amount of bits to which the ...
2403ae19f75a2fa2fbbdb47a7771aca0d93f8ead
578,458
def fibonacci_memory(nth_nmb: int) -> int: """An recursive approach to find Fibonacci sequence value, storing those already calculated.""" # Initial cache is set, hardcoded values make up the numbers for the base case cache = {0: 0, 1: 1} def fib_mem(_n): if _n not in cache: # Add...
d06ec2cbaaf55f919cb83149a8fba249de0ad4fe
578,459
def _unpack_pyspark_row(r): """Unpack a `pyspark.sql.Row` that contains a single value.""" return r[0] # NB: 0 as in 0th column; pyspark.sql.Row provides indexing # for syntactic sugar
ce76902577193d351194859e0717526e6f8a8d30
578,461
def extract_text_data(text): """ Extract the data of the text : total of characters, total of words, total of lines :param text: The text to operate on :return: an object containing th text data """ total_char = 0 total_words = 0 total_lines = 0 lines = text.split('\n') for li...
a2a087072458b235dc50959b1a49d58d52df3286
578,462
from typing import Callable def try_action(action: Callable[[], None]) -> bool: """Return True if an action succeed, otherwise false >>> try_action(lambda: 1/0) False >>> try_action(lambda: None) True """ try: action() return True except: return False
a6f341fafe68a08d86fd05cac91c0f51bb3d7948
578,469
def _filter_for_times(data, **kwargs): """ Uses the start_time and end_time keyword arguments to filter the data. :param data: a dataframe with pbp data :param kwargs: kwargs as given to get_pbp_events, for example :return: a dataframe filtered to fit time-related kwargs """ if 'start_time'...
3fe33fff33110773ba8c32e2933daf960dc031f4
578,471
def IF(logical_statement, expression_true, expression_false): """Evaluates the logical statement. If it is true, reuturns the true expression. If not, returns false expression. Parameters ---------- logical_statement : condition that evaluates to True or False condition that will return True or...
78228a545a6695a1d0210b36008c0bfa0b093d70
578,472
import torch def rgb_recombine_median(d_rgb_tensors: torch.Tensor, median_r: torch.Tensor, median_g: torch.Tensor, median_b: torch.Tensor) -> torch.Tensor: """ Recombine separated median RGB to the delta RGB tensor. :param d_rgb_tensors: Delta RGB tensor [batch_size, 3, height, width]. :param median_r...
4d9c06454224dc8d25edb69fba5c29435d9f87ac
578,477
import math def get_speed(vehicle): """ Get speed consider only 2D velocity. """ vel = vehicle.get_velocity() return math.sqrt(vel.x ** 2 + vel.y ** 2)
b52e8db661c175c0f9a47b0543c597ca4b3ca273
578,480
def get_array_type(arr): """Returns if the array is a scalar ('scalars'), vector ('vectors') or tensor ('tensors'). It looks at the number of components to decide. If it has a wierd number of components it returns the empty string. """ n = arr.number_of_components ret = {1: 'scalar...
886949122ea3d4b2ea395c9fbdec618e0af973a8
578,484
def enclose_in_double_quotes(query_txt): """ Encloses each word in query_txt in double quotes. Args: query_txt: Search query Returns: '"query_word1"' """ return '"' + query_txt + '"'
9f8d10af7102be31844ad1d88efaf1fe8ca3adbe
578,490
def handles(cursor): """Returns a dict of handles that form (ROWID, id) pairs.""" sql_handles = cursor.execute("SELECT ROWID, id FROM handle").fetchall() all_handles = dict() for handle in sql_handles: rowid, contact_id = handle all_handles[rowid] = contact_id return all_handles
0b9b865770f7775feb70d60680ea9a36f0f259f0
578,492
def _digit_to_hex(string_of_digit): """Convert string of digits to string of hex.""" return "".join( [ hex(int(i))[2:] for i in [ string_of_digit[i : i + 2] for i in range(0, len(string_of_digit), 2) ] ] )
7d62a53fc1009da2e33ac3198036e304a3e699bd
578,493
import pathlib def root_dir() -> pathlib.Path: """Returns root directory""" return pathlib.Path(__file__).parent.parent
af2edceba8c0e23a1ca901c6d8aa4ec3a5c67e0d
578,496
def evaluate_full_projection_params(model, true_richness): """Given a true richness, determine the values of the projection model parameters Parameters ---------- model : dict Dictionary of cubic splines for each of the projection model parameters true_richness : float The true rich...
0e8e9bc780581bbb5de5de17329bc586231d3e7e
578,497
def py6s_bandnames(mission): """ visible to short-wave infrared wavebands (Py6S nomenclature) notes: [1] Landsat8 'B8' === 'PAN' [2] Landsat7 'PAN' is missing? """ switch = { 'Sentinel2':['01','02','03','04','05','06','07','08','09','10','11','12','13'], 'Landsat8':['B1','B2','B3','B4','B5...
1b00d2ea34eccd23da0d655e4985d6ddfa890963
578,500
def flags_to_direction(flags): """ Returns a str indicating the direction of the packet (H2C or C2H) """ assert flags in [0,1,2,3] if flags in [0,2]: return ">" # host->controller (or h2d?) elif flags in [1, 3]: return "<"
7c1b9aaa6f0563903272d21bef514592dafcf64d
578,502
def scd_session_cp(pytestconfig) -> bool: """True iff SCD auth1 user is authorized for constraint processing""" return pytestconfig.getoption('scd_auth1_cp')
30da412d61f37e63c83d61e30058a6cbf91ee22e
578,503
def wrap_text_to_lines(string, max_chars): """wrap_text_to_lines function A helper that will return a list of lines with word-break wrapping :param str string: The text to be wrapped :param int max_chars: The maximum number of characters on a line before wrapping :return list the_lines: A list of ...
358cb40a999c5bf50a5fcf73391700fe493de109
578,504
def get_sample_id(sample): """Return id attribute of the object if it is sample, otherwise return given value.""" return sample.id if type(sample).__name__ == "Sample" else sample
d2cc0f24e6bd453e8ddc414260cd0b0e8ea49866
578,511
import re def compute_score(state, zero_ind): """ Compute the sum of the position of the flowers (#) in state, given that the 0th pot is at index zero_ind """ indices = [match.start() - zero_ind for match in re.finditer("#", state)] return sum(indices)
b85ab054ac2b2b10423d0d89e6dc29ef695e4eb4
578,514
import json def load_json(fileuri): """Load json file into a dict""" fd = open(fileuri, 'r') try: return json.load(fd) except Exception as e: raise e finally: fd.close()
29dd254b7ab95da160fb4de37997803548999891
578,515
def get_user_display(user): """Adaptor for allauth ACCOUNT_USER_DISPLAY""" return user.get_full_name()
8f8f2c8d5c05aec59a23073935d52eed79df87c6
578,516
def get_account_id(req): """Get account ID from request headers.""" return req.headers.get('Account-Id')
6be3fa56f8bc32e3eb4f0c2cbe75238f43a90ae4
578,517
def compute_cost(im1, im2): """Implementation of the cost minimised by Lucas-Kanade. Args: im1, im2: Images as (h, w) np.array Returns: Cost as float scalar """ assert im1.shape == im2.shape h, w = im1.shape d = im1 - im2 d = (d * d).sum() / (h * w) assert isinsta...
a0675a59a6502371afc88bfa5ca1176cb660a49f
578,520
def pbits(num: int, pad: int = 32) -> str: """Return the bits of `num` in binary with the given padding.""" return bin(num)[2:].zfill(pad)
fe445ac023c9aab0d889901c49aaf19635137b68
578,521
def raster_center(raster): """This function return the pixel coordinates of the raster center """ # We get the size (in pixels) of the raster # using gdal width, height = raster.RasterXSize, raster.RasterYSize # We calculate the middle of raster xmed = width / 2 ymed = height / 2 ...
211bdfd358e0f1463e799c49396b284bfe522bc8
578,523
def GetFlakeIssue(flake): """Returns the associated flake issue to a flake. Tries to use the flake's issue's merge_destination, and falls back to the issue itself if it doesn't merge into any other ones. Args: flake: A Flake Model entity. Returns: A FlakeIssue entity if it exists, otherwise None....
3697181efb517f14e3f79984b32fb58955525d6d
578,526
def my_function(x): """Simple function that can be minimized.""" sm = 0 for i in range(len(x)): sm += (x[i] - 4) ** 2 return sm
bbfafeee8e83e5911247bad77f246430aa04f75d
578,532
def get_version_substitute(version_str: str): """Transform provider version str to universal version type.""" version_str = version_str.lower() # substitute edit and edition with version if "edition" in version_str or "edit" in version_str: version_str = version_str.replace(" edition", " version...
19b16b976c0af9ecd02a4a5de3392c960326eac1
578,534
from pathlib import Path def get_directory(base_path, vin): """Generate directory where data files go.""" path = Path(base_path) / Path(str(vin)) path.mkdir(parents=True, exist_ok=True) return path
ef3fbda689b7feba527bb014896a170b873f5665
578,537
def osm_length_sql(grid, osm, cat): """ Returns a sql fragment that sums the length of OSM line features per grid cell by category Args: grid (string): a PostGIS table name containing the grid osm (string): a PostGIS table name containing the OSM line features cat (string): a Po...
90b39fb9327e9b108c15cde5bf4cd50fb6d85ee6
578,539
def wrap_as_dictionary(keys, values): """ Wrap values with respective keys into a dictionary. # Arguments keys: List of strings. Values: List. # Returns output: Dictionary. """ output = dict(zip(keys, values)) return output
e728ce7eaba130246606bb4725658880db521682
578,540
from random import shuffle def random_matrix(n): """ Generate random n x n matrix without repeated entries in rows or columns. The entries are integers between 1 and n. """ a = list(range(n + 1)) shuffle(a) # Use slicing to left rotate m = [a[i:] + a[:i] for i in range(n + 1)] # Shu...
68d0317b5ee1369da78c8b769571545d31cf9e72
578,542
def get_readout_time(dicom_img, dcm_info, dwell_time): """ Get read out time from a dicom image. Parameters ---------- dicom_img: dicom.dataset.FileDataset object one of the dicom image loaded by pydicom. dcm_info: dict array containing dicom data. dwell_time: float Effe...
fb081c91bce9e19ba46e202a4512ca4e46d39eb9
578,543
def load_rttm(file_path): """ rttm file to dictionary """ rttm = {} with open(file_path, 'r') as _file_path: for line in _file_path: line = line.split() meeting_name = line[1] start = float(line[3]) duration = float(line[4]) rttm.setdefault...
668de1db60acd546577320b622db4242e526775b
578,544
def boolean_string(s): """ Python argparse for bool consider the input as str. Handle it with this function """ if s not in {'False', 'True'}: raise ValueError('Not a valid boolean string') return s == 'True'
efc87438b9af0808661500b5fc070013149c5231
578,547
def calculate_nps(scores): """Takes in a list of floats and returns the Net Promoter Score based on those scores. Args: scores -- list of floats representing scores Returns: float -- Net Promoter Score from -100.0 to +100.0 """ detractors, promoters = 0, 0 for s i...
7b3916dcb8ee689ba6df1449c2a42f2643aa9537
578,551
import json def route(file_name): """ Creates a list representing the route given in file_name (in JSON format) """ f = open(file_name) route = json.load(f) f.close() return route
42548808508d7821a3a6719db4a5dfdcb87f1f09
578,553
from datetime import datetime def parse_datetime(timestamp: str) -> datetime: """ Parse a string value from an AWS response as "2020-09-21 01:53:07.692000+00:00" into a datetime Parameters ---------- timestamp: str A timestamp to be parsed """ return datetime.strptime(timestamp, "...
110ec04a029b206ba34cf2e6829d053fa6d3bd28
578,557
def initial_velocity(final_velocity, acceleration, time): """ Calculates the initial_velocity when given final_velocity, acceleration and time Parameters ---------- final_velocity : float acceleration : float time : float Returns ------- floa...
1d53c8645547c22999c41e631cff021ccd2ec53b
578,558
def is_freq(*args): """Determine if input args require FreqPart""" is_freq = False if len(args) == 1 and type(args[0]) == tuple: args = args[0] # if called from another script with *args for arg in args: if "freqs" in arg or "wavenumber" in arg: is_freq = True br...
32a0e09d9446bc9990ca73b33f7eab722fcdf285
578,568
def get_data_id(data_str): """ If data_str is of the format <ID>:<NAME>, or <URI>/<PATH>:<NAME> return ID or URI """ if ':' in data_str: name_or_id, _ = data_str.split(':') return name_or_id else: return data_str
d8b03a67113db996110b8a9af95ccbed974da5ba
578,572
import re def validate_password(string): """Validate password. Minimum length of 8 and should include at least 1 digit and 1 letter""" pattern = re.compile(r"^(?=.*[a-z])(?=.*[0-9]).{8,}$") return bool(pattern.match(string))
41bb90e596c53b8b8f5e27a50d27d0ebd6616267
578,575
import inspect def type_name(value): """ Returns a user-readable name for the type of an object :param value: A value to get the type name of :return: A unicode string of the object's type name """ if inspect.isclass(value): cls = value else: cls = value....
d57cba5d9f45ccb0d59062859dbe994f07327b92
578,576
import requests import time def call_crossref_api(doi): """ Calls the crossref works API for a given DOI. """ url = "http://api.crossref.org/works/{}".format(doi) headers = { "User-Agent": "JournalsDB/1.1 (https://journalsdb.org; mailto:team@ourresearch.org)" } r = requests.get(url...
ce4f60b5f25c64a2eb88dcefc7e7077118799b1f
578,578
def start_delayed(env, generator, delay): """Return a helper process that starts another process for *generator* after a certain *delay*. :meth:`~simpy.core.Environment.process()` starts a process at the current simulation time. This helper allows you to start a process after a delay of *delay* sim...
3613a05d81493d0d047a83a87f22c6a83051d275
578,583
def percents (x, y): """What percentage of x is y""" one_percent = x/100 result = y/one_percent return result
13ba8e9af132e41118214180dc099ab9bb02c7d4
578,588
def is_dataclass_type(cls: type) -> bool: """Like dataclasses.is_dataclass(), but works correctly for a non-dataclass subclass of a dataclass.""" try: return "__dataclass_fields__" in cls.__dict__ except Exception: return False
7920fa20801bc61bd9089bc7ea3e321f749f2198
578,589
def _parse_qualimap_coverage(table): """Parse summary qualimap coverage metrics. """ out = {} for row in table.find_all("tr"): col, val = [x.text for x in row.find_all("td")] if col == "Mean": out["Coverage (Mean)"] = val return out
9e7b51a4cd96547ae23038824b9c2fc4cf1391f4
578,590
import random def random_edges(vs): """Returns a set of random edges, given a set of vertices.""" vxv = [(u, v) for u in vs for v in vs] return set(random.choices(vxv, k=min(len(vxv), 50)))
2f8f2381303a38a9381b60e08522eb5b80860c21
578,592
import string import random def random_word(length = 12): # type: (int) -> str """ Returns a randomly generated string 'length' characters long containing only word characters ([a-zA-Z0-9_]). """ word_chars = string.ascii_letters + string.digits + '_' return ''.join(random.choice(word_chars) for _ in range(leng...
4dfd1f855fc4c46fe5389f6ce3fa2391436ba36a
578,599
def hex_to_rgb(hex_str): """Returns a tuple representing the given hex string as RGB. >>> hex_to_rgb('CC0000') (204, 0, 0) """ if hex_str.startswith('#'): hex_str = hex_str[1:] return tuple([int(hex_str[i:i + 2], 16) for i in range(0, len(hex_str), 2)])
0bd2ae4cf4a28d1154a65bfbd5e3c85638e81a40
578,601
def exit_H_CUST(state): """ Handle leaving the ``H_CUST`` state. Add the customer data being processed to the list of all processed customers. """ current_customer = state.pop('current_customer', None) if current_customer: state.setdefault('customers', []).append(current_customer) r...
aadb262727e4c3b0880d55c987d877cf15fe89e0
578,608
def getFirstTask(wmspec): """Return the 1st top level task""" return next(wmspec.taskIterator())
d4b18d8af0176a89f4c4ffadce7d7128e31bf975
578,610
def quaternion_real(quaternion): """Return real part of quaternion. """ return quaternion[0] #return jnp.float64(quaternion[0])
d69b9217515afe9272ddea4a695f3b21b70cbee6
578,618
def _merge_cov_data(d1, d2): """ Merge covariance data from two segments into a new one. See also: https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online """ d3 = d1 + d2 n1 = d1[0]...
3bf719a625db4f8fd8ba1b86322f300227327cdd
578,619
def _get_collectd_type(oid_group_name): """Returns the collectd type name based on oid_group_name.""" # This names a collectd type defined in types.db. return 'ifx_' + oid_group_name
b5f21773e3fcf3f2a5786004dc1a02a295c77f43
578,623
def centre(response, start): """ Subtracts the value at index start from a numpy array :param response [ndarray] the array to be modified: :param start [int] the index to centre on: :return [ndarray] the modified array """ return response - response[start]
673bde203a8e3493a93bd8aeb59d7a2c8e876dcf
578,625
def filter_publishes(app, sg_data_list): """ Filters a list of shotgun published files based on the filter_publishes hook. :param app: app that has the hook. :param sg_data_list: list of shotgun dictionaries, as returned by the find() call. :returns: ...
d9d1ed4506c516261a8ed2c4b52655287e86f28a
578,626
def add_string(strings, s): """Adds a string to the pool, deduping it. Returns the index of the entry of the string, whether new or existing.""" for n, t in enumerate(strings): if t == s: return n strings.append(s) return len(strings) - 1
3e5ec10f6c47a9734dd743c15d5bbba676edc65e
578,628
def import_memory_data(filename): """ Imports the special memory data format. # are comments, empty lines ignored, pairs of integer """ with open(filename, "r") as f: contents = f.read() lines = contents.splitlines() avals = [] bvals = [] for line in lines: line = li...
5c0ea221f426dbec3f7ca8986ec36addeef5d802
578,629
def ircLower(string): """ Lowercases a string according to RFC lowercasing standards. """ return string.lower().replace("[", "{").replace("]", "}").replace("\\", "|")
6d64ea5a8b0ce489eac5d81e5f7438df631ef5f8
578,630
def apply_weight(loss_dictionary: dict, losses: dict): """ Author: SW Apply the weight for each loss to a dictionary of computed loss values :param loss_dictionary: dict: the name and value of each loss function :param losses: dict: dict: the name and loss objects :return: loss_dictionary: dict:...
7c9d4680235f9fe6aa39165cd748d75a9f425157
578,633
def parse_executable_str(exec_str): """ Split the string describing the executable into a path part and an options part. """ first_space = exec_str.find(" ") if first_space == -1: first_space = len(exec_str) return exec_str[:first_space], exec_str[first_space:]
1d85e9e378edff119bcdaf2421002e4ea0266fa7
578,634
def isDescendantWidget(maybeParent, widget): """Return True if 'widget' is 'maybeParent' or a descendant of it. Widget parenthood is tested for Tk in this function. """ if widget is maybeParent: return True else: return any(( isDescendantWidget(w, widget) for w...
3ef70f5cb2d9a8cf48caf6fc9fd17407523bd380
578,636
def _numbers_close(x, y, tolerance=1e-6): """ Returns True if the given (real) numbers are close enough. The given tolerance is the relative difference allowed, or the absolute difference, if one of the numbers is 0. """ # Instead of using a try and ZeroDivisionError, we do a test, # NaN c...
27d1ddfca61148df6c7e643ac140f5cd2acdc543
578,640
import hashlib def get_readable_info(file_obj): """ Extract useful information from reading a file This function calculates the md5sum and the file size in bytes from a file-like object. It does both operations at the same time, which means that there is no need to read the object twice. After t...
b454129f741205b32ad109aa7dd7d885db6b6389
578,641
def jac(set_a, set_b): """ Compute the Jaccard Index. """ if len(set_a) == 0 or len(set_b) == 0: index = 0 else: index = len(set(set_a).intersection(set(set_b))) / len( set(set_a).union(set(set_b)) ) return index
8910c06b15d221247df366d646064cc427c678c8
578,642
def split_features_labels(features, label_key): """Splits labels from features. Args: features: Dict of tensors. This dict need to have label_key. label_key: String. The key of label in features dict. Returns: features: Dict of tensors without label_key. labels: features[label_key] tensor. """...
2868a207f6d1e33592af78329b1b7ce924dc5dd9
578,643
from datetime import datetime def _append_current_datetime(file_path: str): """ Insert date and time into file path and return it. """ now = datetime.now().strftime("%Y_%m_%d_%H%M%S") if file_path.endswith('.log'): return file_path.replace(file_path, f'_{now}.log') return f'{file_path}...
4983326b0c2a142b8ae1f18e3759c6f7e93d5428
578,646
def exit_mode(mode): """ Returns 'min' if given 'max' and vice-versa. Arguments - mode: 'max' or 'min' """ return 'min' if mode == 'max' else 'max'
311c3d6a3062f1b0b7397dd5efb31901079331b8
578,647