content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def extract_email_addresses(emails, sep=","): """ Transforms a string of multiple email adresses (separated by commas) into a list :param str emails: Single string of emails separated by a specific character :param str sep: The separator used in the emails parameter. Defaults to ',' :return: A list ...
d2e04b1c36abd80856ebe47105d4a25bb4553f7c
559,804
def find_exchange_or_parameter_by_id(dataset, uuid): """Find exchange or parameter in ``dataset`` with id ``uuid``. Raises ``ValueError`` if not found in dataset.""" for exc in dataset['exchanges']: if exc['id'] == uuid: return exc for param in dataset.get('parameters', []): ...
33619132cc574b8b1e23034138f22c8519e6d2f4
608,229
def field_items_text(content): """ Creates a comma separated string of values for a particular field """ if len(content): tag = content[0].find_all(class_="field-items")[0] if len(tag.contents): return ', '.join([c.text for c in tag.contents]) else: return...
7356c8c4b850f8bd8dc3ad1eff38c5074275bdab
366,644
def assign_y_height_per_read(df, phased=False, max_coverage=100): """Assign height of the read in the per read traces Gets a dataframe of read_name, posmin and posmax. Sorting by position, and optionally by phase block. Determines optimal height (y coordinate) for this read Returns a dictionary ma...
d2723371fda2ccff7822b5a1cec7ed88f474c370
71,947
def _BuildOutputFilename(filename_suffix): """Builds the filename for the exported file. Args: filename_suffix: suffix for the output file name. Returns: A string. """ if filename_suffix is None: return 'results.html' return 'results-{}.html'.format(filename_suffix)
ae4087a3bcf50b0715685f5359962813e2fdc70d
55,568
import re def snake_case(camelCase): """ Function to convert a camelCaseString to a snake_case_string :param camelCase: camelCaseString :type camelCase: str :returns: snake_case_string """ first_cap_re = re.compile('(.)([A-Z][a-z]+)') all_cap_re = re.compile('([a-z0-9])([A-Z])') r...
12dd5de3853ccc016f73942fb583336e76a90cec
131,845
def get_cdxj_line_closest_to(datetime_target, cdxj_lines): """ Get the closest CDXJ entry for a datetime and URI-R """ smallest_diff = float('inf') # math.inf is only py3 best_line = None datetime_target = int(datetime_target) for cdxj_line in cdxj_lines: dt = int(cdxj_line.split(' ')[1]) ...
35c6b1a374e153982abe6edf2d2e6625cf8e8937
72,211
def display_binary_4bit(num: int): """Displays the binary string representation for a given integer. If the number is within 4 bits, the output will be 4 binary digits; if the number is 8 bits then 8 binary digits will be the output. Examples: >>> display_binary_4bit(151)\n '10010111' ...
52cdab625a043b97e73d5e87298483268e4def76
241,995
def definition_area_ref(t, x0): """ reference solution for ode with respricted definition area. :param t: time :param x0: initial value :return: samples of reference solution for time t """ x_ref = 1. / (1. / x0 - 1. / 2. * (t ** 2)) # analytical solution of this ODE return x_ref
5342eb8004f7720689823a3a61709cd516de56dc
415,478
def get_min_max(ints): """ Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers """ # If list has no elements return None if not ints: return None # If the size of the list is 1 than return the pre...
6641cf0d3f9f55a487e67df590c592547c0ea5c7
518,274
def quartic_easeinout(pos): """ Easing function for animations: Quartic Ease In & Out """ if pos < 0.5: return 8 * pos * pos * pos * pos fos = pos - 1 return -8 * fos * fos * fos * fos + 1
e317c61db1a100104a4647e6db75ddde647340e7
162,015
def has_substr (s, subs) : """Returns true if `s` contains `subs`""" return subs in s
db4e10151a15bf6d7e8e0e6a6aaa88b8bdabbe60
190,575
def list_from_string(list_str=None): """Get list of items from `list_str` >>> list_from_string(None) [] >>> list_from_string("") [] >>> list_from_string(" ") [] >>> list_from_string("a") ['a'] >>> list_from_string("a ") ['a'] >>> list_from_string("a b c") ['a', 'b...
949d93c83c8242210458d448ebabc0845de7e4b3
264,686
def get_namespace(type_or_context): """ Utility function to extract the namespace from a type (@odata.type) or context (@odata.context) :param type_or_context: the type or context value :type type_or_context: str :return: the namespace """ if '#' in type_or_context: type_or_context =...
6b84732b23c5e09731927a75b4aeeda8752750b0
74,093
import re def isEndStoryText(string): """ Return True if reach the end of stories. """ match = re.search(r'^\*\*\*', string) if match == None: r = False else: r = True return r
36f2b8f333c4188c2c3a53a6da036308e8a8152e
686,281
def add_args(parser): """ Create parser for command line utility. :meta private: """ parser.add_argument("--model", help="Trained prediction model", required=True) parser.add_argument("--test", help="Test Data", required=True) parser.add_argument("--embedding", help="h5 file with embedded ...
1b9d9bb2cbe5d2d0431dc529fc8b4826852c5f11
83,885
def prepare_prediction_column(self, prediction): """Return the class label of highest probability.""" return prediction.argmax(axis=-1)
f51e54ff59ac1084c147dec37eaaafa23567466f
511,088
import hashlib def md5(*txt): """ Returns the md5-checksum for `txt`. This can be used to test if some piece of text, for example a grammar source file, has changed. """ md5_hash = hashlib.md5() for t in txt: md5_hash.update(t.encode('utf8')) return md5_hash.hexdigest()
7333fcfd53c6b0e40d6cc6797b7f10453c32a048
261,063
def _additional_env_args(additional_env): """Build arguments for adding additional environment vars with env""" if additional_env is None: return [] return ['env'] + ['%s=%s' % pair for pair in additional_env.items()]
ccd0fbb99c9b133d0ea0bee3ea2acbfe8a7105d4
135,944
import fnmatch def _is_globbed(name, glob): """ Determine if the name is globbed based on the glob list """ if not glob: return True return any( (fnmatch.fnmatchcase(name, i) for i in glob) )
9411f2f36fc1f8ed67027a3490eec0a58929c20f
416,479
def decode_rgb565(val): """Decode a RGB565 uint16 into a RGB888 tuple.""" r5 = (val & 0xf800) >> 11 g6 = (val & 0x7e0) >> 5 b5 = val & 0x1f return ( int((r5 * 255 + 15) / 31), int((g6 * 255 + 31) / 63), int((b5 * 255 + 15) / 31) )
0c9a67016df686eb23282de74f663493caa305a9
687,811
def latest_date_between(date_1, date_2): """Utility function to compare the dates and return latest date.""" if date_1 > date_2: return date_1 else: return date_2
6ef511dc35812ca2cf1842cec8a9454fe0503891
615,373
def H_generator(N, adjacency_matrix): """ This function maps the given graph via its adjacency matrix to the corresponding Hamiltiona H_c. Args: N: number of qubits, or number of nodes in the graph, or number of parameters in the classical problem adjacency_matrix: the adjacency matrix gen...
f220146f0ed5682f77963ebed60d7b91acceaa82
548,823
def collect_hmeans(path): """ Collects hmean values in log file. """ hmeans = [] keyword = 'hmean=' with open(path) as read_file: content = [line.strip() for line in read_file] for line in content: if keyword in line: hmeans.append(float(line.split(keyword)[-...
9ea5cef5120cdda245e5e51ff164ca31d0872ed9
423,027
import torch def length_penalty(sequence_lengths, penalty_factor): """ Calculate the length penalty according to https://arxiv.org/abs/1609.08144 lp(Y) =(5 +|Y|)^α / (5 + 1)^α Input: sequence_lenthgs: the sequences length of all hypotheses of size [batch size x beam size x vocab size] p...
2b5742ee0514d1f33f94d82d5fb8c5f2d0d095eb
245,655
def refbasis(reading,ref): """Argument: raw ADC reading, raw ADC basis. Returns an absolute potential based on the ADC reading against the 2.5 V reference (reading from pot as a value between 0 and 1023, reference value in V (e.g. 2.5))""" return round((float(reading)/float(ref))*2.5,3)
91dccf15e520b3054fc6502d0346d7002cf5116d
142,797
import torch def one_hot_to_class_indices(labels: torch.Tensor) -> torch.Tensor: """ Converts one hot encoded label tensor to a tensor representing class ids. :param labels: One-hot encoded label tensor """ # Check that labels do not overlap with each other if not labels.is_floating_point(): ...
4fbd0612787ed31248cf09238e03bacc21b765ae
467,766
def devilry_multiple_users_verbose_inline(users): """ Returns the provided iterable of user objects HTML formatted. Perfect for formatting lists of users inline, such as when showing examiners or candidates on a group. """ return { 'users': users }
9cec004b7362bd1a513b5d02a154e2af5cbca7ef
620,442
import re def replace_chars(token, chars_to_replace): """Replaces all characters in the dict with their specified replacement.""" for c in token: if c in chars_to_replace: token = re.sub(c, chars_to_replace[c], token) return token
57b543f56baa9fb89ac32e3fe4f9fe6997a6df6f
413,005
def find_a_sequence_inside_another_sequence(seq, seq_to_find): """Check if a sequence exists in another sequence Example: seq = [1,2,4,5,6,2,3,1,2,3,4] seq_to_find = [4,5,6] find_a_sequence_inside_another_sequence(seq, seq_to_find) >> True :type seq: lis...
0d115a34ecc6dde3220b878324fc4414c358b908
271,510
from typing import List def arrayToFloatList(x_array) -> List[float]: """Convert array to list of float. Args: x_array: array[Any] -- Returns: List[float] """ return [float(x_item) for x_item in x_array]
617377ae4bf5e55db2882451d91d6839df0bec3d
672,391
def get_attrs(obj, config_attrs): """ Given an object obtains the attributes different to None. :param obj: object containing the attributes. :param config_attrs: a list of all the configurable attributes within the object. :return attr_data_dict: A dictionary containing all the attributes o...
18348e05d799406961169dcb195531b25fe03946
693,119
def as_list(x): """A function to convert an item to a list if it is not, or pass it through otherwise Parameters ---------- x : any object anything that can be entered into a list that you want to be converted into a list Returns ------- list a list containing x ...
68415bfe9aeee8b69d5e03d0c7af3c9459803f7e
603,670
def get_count_words(document, words): """ Takes in a Document object and a list of words to be counted. Returns a dictionary where the keys are the elements of 'words' list and the values are the numbers of occurrences of the elements in the document. Not case-sensitive. :param document: Docum...
30643557c047899a4a92514e991e15b39f6b6d90
266,984
from datetime import datetime def format_time_from_arg(time_string): """ Format a time string from args and return a datetime. :param time_string: String of the form HH:MM:SS. :type time_string: str :return: datetime """ time_from_arg = datetime.strptime(time_string, '%H:%M:%S') curre...
9339532ea13ad0024b57eaa10bd88ea9b10282f3
277,524
import torch def fMAPE(preds, targs, *kwargs): """ Loss function Mean Absolute Percentage Error N-BEATS paper definition """ return torch.mean( torch.abs((targs - preds) / targs) )
a847550230a046d14effced268df4c135edabaef
228,085
def map_components_by_name(components): """Given a dictionary or list of components, map them into a dictionary by name""" if isinstance(components, dict): components = components.values() return { component.name: component for component in components }
2f7e4b061cbef754d979c6c12d0cb4bc67f8dc22
420,670
import warnings def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emmitted when the function is used. Taken from http://code.activestate.com/recipes/391367-deprecated/ """ def newFunc(*args, **kwargs): wa...
d9d3681fb3cd3c48ace662c06cbba3690391a7c1
343,939
def path_segments(path, **kwargs): """ Create an array of vertices and a corresponding array of codes from a :class:`matplotlib.path.Path`. Parameters ---------- path A :class:`matplotlib.path.Path` instance. Other Parameters ---------------- kwargs See :func:`matpl...
6073bcad156548dad5d6bd43a3d9c797b830de41
336,836
import re def parse_size(size, binary=False): """ Parse a human readable data size and return the number of bytes. Match humanfriendly.parse_size :param size: The human readable file size to parse (a string). :param binary: :data:`True` to use binary multiples of bytes (base-2) for ...
fc53c07d81df5e4fb39b5dca7c9a62c4a9a6f3b2
103,609
def correct_position(first, second): """ :param first: a string. :param second: a string. :return: the number of characters in first and second which are equal and are located at the same index. """ return sum([f == s for f, s in zip(first, second)])
e374e2fa1fcd224f3d5b4bf471177af1d38e36db
236,758
def first(a, fn): """ Example: first([3,4,5,6], lambda x: x > 4) :param a: array :param fn: function to evaluate items :return: None or first item matching result """ return next((x for x in a if fn(x)), None)
72fd47eff62a406f42a0fcd6901f010c98954464
55,697
import re def replace_string( text, old_string, new_string ): """ Check that `old_string` is in `text`, and replace it by `new_string` (`old_string` and `new_string` use regex syntax) """ # Check that the target line is present if re.findall(old_string, text) == []: raise RuntimeError(...
93811fe03ac720baab12b3bd0733a8b05cf6b3a0
663,918
def quantize_duration(dur): """Quantize the duration to the nearest 500 milliseconds. This function was adapted from Sven Marnach's answer to this question: http://stackoverflow.com/questions/9810391/round-to-the-nearest-500-python Arguments: dur (int) Returns: An int """ i...
3d3ba93e6f6ca46c2c2392a3bd18492465fa0e80
152,836
import logging import json def is_newformat(filename): """ Check if app is new format (with FolderDefinition as top object) :param filename :return: True if new format, throws exception otherwise """ with open(filename, 'r') as mf: logging.info("Reading file: " + filename) cont...
c169360882777dd9897870da0c90203c268ac528
577,481
import re def structure_from_viewer(status, atlas_layer, atlas): """ Get brain region info from mouse position in napari viewer. Extract nx3 coordinate pair from napari window status string. Return brainglobe (BG) structure number, name, hemisphere, and a "pretty" string that can be displayed for...
a0f92a90cf13b1bc01081167f95c248a1b74c046
690,208
def _bowtie2_args_from_config(config): """Configurable high level options for bowtie2. """ qual_format = config["algorithm"].get("quality_format", "") if qual_format.lower() == "illumina": qual_flags = ["--phred64-quals"] else: qual_flags = [] num_cores = config["algorithm"].get(...
c40a518fd4ec5b98f36c04e0f93a673bef76a4cb
417,860
from typing import Any from typing import List from typing import Optional def get_path(obj: Any, path: List[str]) -> Optional[Any]: """ Get a nested value by a series of keys inside some nested indexable containers, returning None if the path does not exist, avoiding any errors. Args: obj: an...
58a92a461c9ce20eaca2f879e8c9a90d7546f4fc
519,096
def ensure_evidence(badge_data: dict) -> dict: """Given badge_data, ensure 'evidence' key exists with list value""" if 'evidence' not in badge_data: badge_data['evidence'] = [{}] return badge_data
755eb002d1b8c79e000c785c4049c29b5e30975f
313,189
def _find_new_name(old_name, node_names): """Disambiguate a node's name from a list of existing node names by adding successively larger integers. """ count = 0 new_name = old_name + "." + str(count) while new_name in node_names: count += 1 new_name = old_name + "." + str(count) ...
37f899fc5ffc4983709aa893be7332f200287819
396,192
def points_to_bbox(p): """ from a list of points (x,y pairs) return the lower-left xy and upper-right xy """ llx = urx = p[0][0] lly = ury = p[0][1] for x in p[1:]: if x[0] < llx: llx = x[0] elif x[0] > urx: urx = x[0] if x[1] < lly: lly = x[1] elif x[1] ...
5303bd02af4ab8e14929b43723c5591832c66b92
466,599
def to_int(x, error=0): """Convert argument to int.""" try: return int(x) except (ValueError, TypeError): return error
2c363a1d9125e396a76007d9986748b98130e1ab
12,142
def merge_components(local_component, target_component): """ Find resulting component from merging the first (local) component into the second. The resulting component will maintain the parent identifier of the target component. """ local_bounds, local_center, local_size, local_parent = local_compo...
bdb9b437d0981f46b676c427034b7716c8727560
36,799
def split(s, esc='\\', sep=' '): """ enhance the split func of str, support escape default '\' single-back-slash >>> split('www.abc.com\.a', sep='.') ['www', 'abc', 'com.a'] """ l = [] ss = [] for c in s: if c == esc: l.append(c) else: [ss.appe...
13b835d5ddb22609c5e40ea669d3ffeec24b59c8
267,323
import re def axes_from_cmd(cmd, alt_names=None): """ Get axes name from command string :param cmd: str :param alt_names: dict {name_in_cmd: name_in_file} :return: str """ alt_names = {} if alt_names is None else alt_names cmd = cmd.split() axes = cmd[1] if axes in alt_names: ...
443acce54aaec1f9bf1fda3031464bcc1566399e
646,684
def _between_lines(lines, beg, end, single=False): """ Extract lines from `beg` to `end` :param lines: content list which is split for each newline :param beg: starting point of parsing :param end: end point of parsing :param single: whether there are multiple sections to exist :return: extracte...
6e9fd61a5415e60acfc6562b2feb66b06f909391
493,384
import re def remove_html_elements(string: str) -> str: """Removes any html elements and attributes from any string passed""" regex = re.compile("<.*?>") clean_text = re.sub(regex, "", string) return clean_text
2aaca8e085ef73bc765adb48692cdab823998236
407,392
def _indexing(x, indices): """ :param x: array from which indices has to be fetched :param indices: indices to be fetched :return: sub-array from given array and indices """ # np array indexing if hasattr(x, 'shape'): return x[indices] # list indexing return [x[idx] for...
8061aee1464ffef0bc13eab0c59b472fd5dc140c
115,670
def terms_accept_url() -> str: """Path to accepted terms.""" return '/terms/accept'
44f3409491591eb5284d249d34da4cf06f150a3a
64,256
def reproject(link, node, epsg): """ reporoject link and node geodataframes for nodes, update X and Y columns """ link = link.to_crs(epsg=epsg) node = node.to_crs(epsg=epsg) node["X"] = node["geometry"].apply(lambda p: p.x) node["Y"] = node["geometry"].apply(lambda p: p.y) retur...
5ead99d074ea1d643f598d790b083dda511caa1a
8,345
def dicom_age_in_years(age_string): """Helper function to extract DICOM age into float Parameters ---------- age_string : str The age string as defined in the DICOM standard, see http://dicom.nema.org/medical/dicom/current/output/chtml/part05/sect_6.2.html Returns ------- f...
f537617fc7b3d9481019c2c684097e917d8bc780
278,028
def _parse_expected_tuple(arg, default=tuple()): """ Parse the argument into an expected tuple. The argument can be None (i.e., using the default), a single element (i.e., a length-1 tuple), or a tuple """ try: _ = iter(arg) except TypeError: tpl = tuple(default) if arg is None ...
39b4925ffc7af098f8a8c9746ee246a1ea944c5b
446,687
def get_iwp_label_key( iwp_label ): """ Retrieves a key that locates the supplied IWP label within the underlying dataset. The key returned locates the label both temporarly and spatially. Takes 1 argument: iwp_label - IWP label to locate. Returns 1 value: label_key - Tuple identify...
e5814e14f3d1b4c40074e4429ae5729ea7087321
684,160
def any_a_in_b(a, b): """Return true if any element *s* of <a> also exists in <b>.""" return any(s in b for s in a)
1573f5b446768894c89a12840300be1268041504
466,728
import importlib def load_module(module_path): """ Load's a python module. ex: module_path = "confidant.authnz.rbac:no_acl" Will load the module confidant.authnz.rbac and return the function no_acl """ module_name, function_name = module_path.split(':') module = importlib.import_module(modul...
2536293f8b2556b91fdd34c9f81bf7f29c8ee7d1
464,207
def find_min_id_ind(tmp_sel_anch_dict): """ Finds the index of minimum ID from the selected anchors' IDs. """ selected_id = list(tmp_sel_anch_dict['AnchorID']) min_id_ind = selected_id.index(min(selected_id)) return min_id_ind
36669853ead3531b3925c95c8ed669b1a0058b71
536,234
from typing import List from typing import Any def contains_sublist(list_: List[Any], sublist: List[Any]) -> bool: """Determine if a `list` contains a `sublist`. :param list_: list to search for the `sublist` in. :param sublist: Sub list to search for. :return: True if `list`...
3c6a9cd063f19b9d712be94970f29f017af0a89f
421,946
def DictToEnvVarsProperty(env_vars_type_class=None, env_vars=None): """Sets environment variables. Args: env_vars_type_class: type class of environment variables env_vars: a dict of environment variables Returns: An message with the environment variables from env_vars """ if not env_vars_type_cl...
52f4663376d18cba6ceca9116668d35b658db81a
406,714
def url_join(parts): """ Take various parts of a url and join them """ return "/".join(map(lambda part: part.strip('/'), parts))
778377572592a814913f734000f57fc080c586f9
99,506
def is_cap(word: str) -> bool: """Return True if the word is capitalized, i.e. starts with an uppercase character and is otherwise lowercase""" return word[0].isupper() and (len(word) == 1 or word[1:].islower())
78787ca4ed8a4c70b0b19a0c92aa6ae9d72ee2f1
656,629
import re def proto_should_have_icon(f): """Check if this PROTO file should have an icon. Hidden and deprecated PROTO nodes doesn't need an icon. """ file = open(f, 'r') row = file.readlines() for line in row: if re.match(r'^#[^\n]*tags[^\n]*:[^\n]*hidden', line) or re.match(r'^#[^\n]...
2c95a137779bddb5bee2b96655e35ccaf32d82b0
288,516
import requests def check_orb_response(response): """Check Orbital API response.""" try: response.raise_for_status() return True except requests.exceptions.HTTPError as err: r_json = response.json() print("\nFAILED:") print('Response Error: ', err) print(r_j...
3665bb08674e637c627dc79564e0976f2df292e4
335,719
import random def random_policy(state): """ Ignore the state, move randomly. """ action = { 'command': random.randint(0, 1) } return action
675e489f3490ebe4e0279c1704536ba6282767f9
588,780
def startswith(this, that): """Returns **True** if *this* or *that* starts with the other.""" if len(this) < len(that): return that.startswith(this) else: return this.startswith(that)
5f68940f0656507c64f7906f60aaa8834191fa8c
486,034
def general_spatial_relation(sp_el1, sp_el2, f): """General function for computing spatial relations with a function f given. Parameters ---------- sp_el1: optional the spatial information of element 1. sp_el2: optional the spatial information of element 2. f: function ...
92e4dc07778212b43996df23b41a36fa3047ce4f
66,477
def _format_date_time(date, time): """ Helper func to format date & time strings from the case coords file Parameters ---------- date : str Format: MMDDYYYY time: str Format: HHMM Returns ------- str Format: MM-DD-YYYY-HH:MM """ month = date[:2] ...
f9b88d02026cb6c0b9ba339d65e9adff7d06f539
351,546
import re def isfilepath(value): """ Return whether or not given value is Win or Unix file path and returns it's type. If the value is Win or Unix file path, this function returns ``True, Type``, otherwise ``False, Type``. Examples:: >>> isfilepath('c:\\path\\file (x86)\\bar') True, ...
56a423a3b27df5ad0e66291db0bd2698fef5a8b5
16,996
def get_sets(df_raw, num=0): """ Group raw data into measurement sets conducted at the same temperature. Parameters ---------- df_raw : pandas.DataFrame Raw measurement data. num : int, optional Number of measurement points per temperature level. Default is 0, which me...
eb7e5faf1cb91fffe44a1cb69d4fd50f08bc8391
438,814
def calc_sales_price(price): """ 计算折扣 :param price: 打折前的价格 :return: 打折后的价格 """ if price<0: raise ValueError("price should not < 0!") sales=0.9*price return sales
743a1e9d535c5f65d5db2b2a512996686104d6bd
211,813
def uncapitalize(string: str): """De-capitalize first character of string E.g. 'How is Michael doing?' -> 'how is Michael doing?' """ if len(string): return string[0].lower() + string[1:] return ""
1a294f171d16d7a4c41fb0546feca3c03b7ae37a
1,430
def _calcgbar(Ip, Vclamp, A=1): # Unused """ Estimate (lower bound) the cell's maximum conductance from its peak current Ip := Peak current [nA] Vclamp := Clamp Voltage [mV] A := Cell surface area [um^2] return gbar [pS/um^2] """ Gmax = Ip/Vclamp # Maximum conductance...
30d42870e928286052a446867279375430ba161f
220,347
def get_obsid_beam_dir(obsid,beam,mode='happili-01'): """ Get directory path for obsid + beam Default assumes happili-01 setup / access to 02-04 Can also run in happili-05 mode where everything is local Parameters ---------- obsid : str Obsid provided as a string beam : int ...
aafed805e36772a0c665e25ff6d1c59229052fb4
525,149
import gzip def gz_open(fname, omode): """ Use :py:mod:`gzip` library to open compressed files ending with .gz. Parameters ---------- fname : str Path to file to open. omode : str String indicating how the file is to be opened. Returns ------- file File Ob...
1016ef102586d36e8949d4bad36d79ec13af1e14
64,300
import csv def get_csv_collection(filename, **kwargs): """ Loads a record collection from a CSV file. The CSV file MUST include columns for Artist, Title, and Year Arguments: filename (str) - CSV filename **kwargs (dict) - Optional kwargs: skip=0, don't load the first <skip> rows Returns...
72761b39b200bb94e9759ffc63a1cf52beb7c264
89,009
def naorthreshold(lmbda, mu, costofbalking): """ Function to return Naor's threshold for optimal behaviour in an M/M/1 queue. This is taken from Naor's 1969 paper: 'The regulation of queue size by Levying Tolls' Arguments: lmbda - arrival rate (float) mu - service rate (float) costo...
d43c11a8c0fa98102cfeabfc98de6076c0d97f98
636,396
import json def readPalette(filePath): """Read the contents of a palette file.""" with open(filePath, 'r') as f: return json.loads(f.read())
19b85df302b4af1e652908a38ddd8c04e23b890a
178,990
def is_default_extra(extra: bytes) -> bool: """Checks if the tx_extra follows the standard format of: 0x01 <pubkey> 0x02 0x09 0x01 <encrypted_payment_id> :param extra: Potential default extra bytes. :type extra: bytes :return: True if the passed in bytes are in the default tx_extra format ...
c84eb2324723224397028a0ab8d9f70610e4b682
392,224
def plain_text_to_html(string): """Convert plain text to HTML markup.""" string = string.replace("&", "&amp;") return string
8dfaf9287ec8f765d77c241e2161c1729cb8c422
624,374
def read_input_samples(data_dict): """ Function that takes only the input property from the dictionary Ignores train or test and just takes all inputs as equal :param data_dict: data dictionary with the full file input structure loaded :return: a dictionary of just input values >>> dict = {'tra...
edfafe34b2b005be13105d79153683a7a9c2a1d2
238,705
def _table_create_query_var(model): """Returns the name of the variable to hold the model's table creation query""" return '{}_TABLE_CREATE'.format(model.get_table_name().upper())
fa6c37ee711df16a2cb2cf20db9575ee614f8b5a
567,178
def etl_path(ctx, branch: str): """ append branch to container path """ return ctx.obj['container_path'] + '\\' + branch if branch else ctx.obj['container_path']
4efa07bc9a2f8718a5de200c4ba1fbd174c06a69
453,563
def year_quarter(target_date_obj): """Returns the yearly quarter (coded as 0,1,2,3) in which a given target datetime object lies. Args: target_date_obj: target date as a datetime object """ m = target_date_obj.month if m >= 12 or m <= 2: # December - February return 0 elif m >...
fee09a686eff67127972918d7f0c31063c1e6015
138,067
import gzip import pickle def load_pickle_gz(filename): """Loads a compressed object from disk """ with gzip.GzipFile(filename, 'rb') as fin: obj = pickle.load(fin) return obj
506231dc173fd498946bb1df590193a59184e19d
458,330
def compose(f, g): """ Return the composition of one-variable functions: `f \circ g` See also :func:`self_compose()` and :func:`nest()` INPUT: - `f` -- a function of one variable - `g` -- another function of one variable OUTPUT: A function, such that compose(f,g)(x) = f(g(...
00cb40c299778f8f867b7c1419842910975ca368
484,577
def num_param_Gauss(d): """ count number of parameters for Gaussian d-dimension. input d [int] : dimension of data """ return 0.5 * d * (d + 3.0)
84a967bff81277ec8c391a5a504e3a8a6747a22a
661,100
import re def stripout(txt): """ Replace white space and non \w characters in text :param txt: some text to clean :return: clean text """ txt = txt.replace(' ', '_') return re.sub('\W', '', txt)
38bf70d52662b285553b399fad73901d64a6024e
356,877
def entry_exists(entry): """ Check if entry exists. :param entry: Text of entry, scraped from the wiki. :type entry: str """ return not "This page doesn't exist yet!" in entry
ddbaa0998220b79a8f7b09df884b7d0a074ae47f
541,323
def get_hk_variable_names(my_df): """ This procedure will return al ist of variables in the housekeeping file. Parameters ---------- my_df: ACT Dataset The dataframe to get the variable names from Returns ------- var_names: list The names of each variable in the fil...
54c2034306c77ab44560ef58c78065c8c7adecfb
120,098
import json def parseOutput(outputMsg): """ parse the full stdOut from call to endUser_sim to get the returned result """ resultStr = outputMsg.split('\n')[-2] resultStr = resultStr.replace("'", '"') # make single quotes double resultStr = resultStr.replace('True', '"True"') # put quotes around ...
f23b5f8b8dcfe23752c841fb64170d68e5195bea
533,991
def get_session_length(row): """ Calculate length of session in seconds""" time_delta = row['session_end'] - row['session_start'] session_length = time_delta.total_seconds() return session_length
f6ce61db58635a5da494707ed7d4b651df250fbd
96,060