content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def string_to_list(coor_str): """ Method that transforms a list of coordinate lists into a tuple with latitude and longitude values. Params: ---------- coord_str: String - List of coordinate lists Return: ---------- coord: Tuple - Latitude and longitude values. ...
b16419c56da30808aaaa38d99d1704dd9ce3f51b
579,214
import re def parse_event_file(event_path): """Parse event file for compact display **Event format:** - Section :: [9H30] rdv with truc <---- will be displayed Some text Some text again [14H30] rdv with muche <----- will be displayed Some text again again - ...
9a53cd5a989c07e6491b9aa0497e202470136ee7
579,215
def make_task_key(x, y): """ Creates a key from the coordinates of a given task. The key is used to identify the tasks within a dictionary :param x: x coordinate :param y: y coordinate :return: the created key """ key = (x, y) return key
a211bd3cebbcc262e93ab549bb4c6666638e4def
579,217
import json def read_creds(path): """Returns JSON creds as dict.""" with open(path) as f: creds = json.load(f) return creds
78543126735ed6fbfe72d4683c79ec9a23e7df5c
579,219
import json def pprint_json(to_print): """Pretty print json. Args: to_print (json): The json to be printed. Returns: str: Pretty printed json string. """ return json.dumps(to_print, sort_keys=True, indent=4)
d949fefbba42d977211c70fdcb162487e53eab26
579,220
def max_unit_id_by_plant(gens_df): """Identify the largest unit ID associated with each plant so we don't overlap. The PUDL Unit IDs are sequentially assigned integers. To assign a new ID, we need to know the largest existing Unit ID within a plant. This function calculates that largest existing ID, or...
55bff1d221f23802f16b1cf2464d6fd494267aaf
579,221
import click import functools def pass_runtime(func=None, require_project=True, require_keychain=False): """Decorator which passes the CCI runtime object as the first arg to a click command.""" def decorate(func): @click.pass_context def new_func(ctx, *args, **kw): runtime = ctx.o...
2aeedb0d326f821b45bdd7bd847e0d1db67c6c61
579,224
def convert(k: str) -> str: """Convert key of dictionary to valid BQ key. :param k: Key :return: The converted key """ if len(k.split(":")) > 1: k = k.split(":")[1] if k.startswith("@") or k.startswith("#"): k = k[1:] k = k.replace("-", "_") return k
06eaa83cbc0ebdde02c498123cb48662936eba01
579,226
def longest_text(text_list): """Returns the length of the longer text in a list :param text_list: List of texts to measure :type text_list: list :return: The length of the longer text in the list :rtype: int """ max_length = 0 for text in text_list: if len(text) > max_length: max_length = len(text) retu...
52288de3f99c253c72e328574550ceb9bbe03e67
579,229
def part1(data): """ Each digit of a seven-segment display is rendered by turning on or off any of seven segments named a through g There are ten unique signal patterns: 0: 1: 2: 3: 4: aaaa .... aaaa aaaa .... b c . c . c . c b c b c ...
11be73780676b97fa20b8fd9137a6a4b3f1d845b
579,230
def atlas_repr_from_name(name): """Generate dictionary with atlas description given the name.""" parts = name.split("_") # if atlas name with no version: version_str = parts.pop() if not parts[-1].endswith("um") else None resolution_str = parts.pop() atlas_name = "_".join(parts) # For uns...
6dedc1b2e350a4a81318edf333b56b5b6aa3f7f4
579,231
from functools import reduce import operator def multidim2cmplist(ar1, ar2, *dim_vals, titles=None): """ Converts a multidimensional array to a list of tuples This may be useful for displaying part or all of an array as a table or exporting to a pandas dataframe, database or spreadsheet. position...
ddfcb22b5da11cf506c893acf336f2596e0328eb
579,232
def img( filename, alt ): """ place an image """ return "![{}]({})".format( str(alt), str(filename))
2ee98693303f2307f6b939f924eb1f494a21e2c8
579,234
import math def icc(theta: float, a: float, b: float, c: float = 0, d: float = 1) -> float: """Item Response Theory four-parameter logistic function [Ayala2009]_, [Magis13]_: .. math:: P(X_i = 1| \\theta) = c_i + \\frac{d_i-c_i}{1+ e^{-a_i(\\theta-b_i)}} :param theta: the individual's ability value. Thi...
2b0b5c7d0ada8ceddf6dcc2afb4a50ef097544d6
579,237
import torch def double_parameters(parameters: torch.Tensor) -> torch.Tensor: """Double parameters as (A, B, C, D) --> (A, B, A, B, C, D, C, D) etc Args: parameters: Parameter vectors (n_batch, n_parameters). Returns: parameters with shape (2*n_batch, n_parameters). """ n_batch, ...
88cf4c54bd29fb7a8cef9976d5c2d0a00a452bd2
579,238
from typing import Union from typing import List from typing import Tuple def _listify(arg: Union[None, str, List[str], Tuple[str]]) -> List[Union[str, Tuple[str]]]: """Return a list of strings or tuples where argument can be multiple types""" if arg is None or len(arg) == 0: return [] elif isinst...
ccc56c97f0bb4382fd87862e447182ace2a080b7
579,240
import jinja2 def _render_template(data: dict): """ Generates the html output of a jinja template rendered with `data` """ templateLoader = jinja2.FileSystemLoader(searchpath="/usr/local/src/") templateEnv = jinja2.Environment(loader=templateLoader) template = templateEnv.get_template("aerobio...
d8dd0d6492e7b90640a2872d4b436578ed8cc800
579,243
def convert_pattern_to_string(pattern): """ Converts a pattern to explicit format where "-" indicates the beginning of an itemset inside the main pattern and "--" indicates that the next item belongs to that itemset. Each "-" means the begin of a new itemset of length greater than 1. Atributes: ...
41401e496cf1d50967e5eabb0716e5cf13fa5fd6
579,244
def bytes_to_hex_str(data): """ converts a sequence of bytes into its displayable hex representation, ie: 0x?????? :param data: byte sequence :return: Hexadecimal displayable representation """ return "0x" + "".join(format(b, "02x") for b in data)
14c1fcf4b8fb39400bceadd572a4fca3d8f75d0a
579,250
def tag(name, *content, cls=None, **attrs): """Generate one or more HTML tags, from Fluent Python, page 155""" if cls is not None: attrs['class'] = cls if attrs: attr_str = ''.join(f' {attr}="{value}"' for attr, value in sorted(attrs.item...
5a2b481c84c051d5077339f00dfda4dbd07393fb
579,251
def _bool(value): """ Determine if the value supplied can be interpreted as bool. :param value: boolean value :return: True / False """ if not value: return False if isinstance(value, bool): return value value = str(value).lower().strip() if value in ['true', '1']: ...
f5c0710b51a26510bd47f8cba3a5853b0704ab23
579,252
def get_vtkTableHeaders(vtk_table): """ Returns the vtkTable headers (column names) as a Python list """ headers = [] for icol in range( vtk_table.GetNumberOfColumns() ): headers.append( vtk_table.GetColumn(icol).GetName() ) return headers
fff7eb3728791e1a2064595dfdfa7490f480ba08
579,260
def _s_suffix(num): """Simplify pluralization.""" if num > 1: return 's' return ''
53b3e866816c4575f500d52658b437c798824a96
579,262
def humanized_time(second): """ :param second: time in seconds :return: human readable time (hours, minutes, seconds) """ m, s = divmod(second, 60) h, m = divmod(m, 60) return "%dh %02dm %02ds" % (h, m, s)
af5f2017f8981f58afffab4c036d5436ea93fc91
579,270
import ast def get_node_functions(node): """Returns the nodes that are functions in node.body""" return [ child_node for child_node in node.body if isinstance(child_node, ast.FunctionDef) ]
4850f297b9fb2e53187a695551e65bbaa85971e8
579,273
def build_validation_result(is_valid, violated_slot, message_content): """ Defines an internal validation message structured as a python dictionary. """ if message_content is None: return {"isValid": is_valid, "violatedSlot": violated_slot} return { "isValid": is_valid, "vio...
401dfb01380bd4741b6b105b384b3b0891081550
579,279
def extract_country(country, data): """ Extracts data for country. Parameters ---------- country : string Name of the country. data : numpy array All data loaded from the csv file. Returns ------- count: numpy array Returns the count of cases vs time. """ ...
dd5057ba86189ab6dd1e0f6bc4a0803dc722ec79
579,287
def _require_hash(value): """ Utility function that tries to take the hash value of the value normally, otherwise, returns its object ID. Basically a way to force a value to produce some kind of hash, with less worry as to whether that hash reflects its true equality. Indeed, not every class tha...
096916bc650d4a45c159db7087ae435a5e72ebc4
579,296
import datetime def unix_ts(*args): """Get unix timestamp for date. Accepts same args as Python's datetime.datetime, viz year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]""" return int(datetime.datetime(*args).strftime("%s"))
2976602f536c0f6340ec44a1c4e56b1d41c6e9e6
579,297
import platform def check_wsl() -> bool: """Return True if Python is running in WSL""" if platform.system() == "Linux": return "Microsoft" in platform.uname().release return False
581b2c3c37635f41f255240818d56e820794e7e0
579,301
import inspect def get_inputs_from_dict(method, d): """ Get a dictionary of the variables in the `NameSpace`, `d`, that match the `kwargs` of the given `method`. Useful for passing inputs from an `argparser` `NameSpace` to a method since standard behaviour would pass also any unknown keys from `d...
64c8e97c4bedfb889f924d9af909b0a884286938
579,307
def join_action_pointer(action, pos): """Join action label and pointer value. Args: action (str): action label without pointer pos (int or str): pointer value Return: action_complete (str): complete action label """ if action.startswith('>LA') or action.startswith('>RA'): ...
82ae2b350d63a4809f9c6ae5ea52ef82ccb87f3a
579,308
import math def inverse_doc_frequency(term_count, num_items): """Return the inverse doc frequency for a term, that appears in term_count items in a collection with num_items total items. """ # implements IDF(q, t) = log(1 + N/f(t)) return math.log(1.0 + float(num_items) / term_count)
fb2b6863e91d89b31bec212ddaecc812871c8c34
579,310
def update_dict(original, other): """ Update the original dict with values from the other. If you delete a key in the other, it will not change the original. >>> d1 = dict(a=1) >>> d2 = dict(b=2) >>> d1 {'a': 1} >>> d2 {'b': 2} >>> d1.update(d2) >>> d1 {'a': 1, 'b': 2} >>> d2 {'b': 2} Tested in Pytho...
5948c33dba2c591ba7cbe270096be564b4c349d2
579,313
import socket import struct def read_message_tcp(sock: socket.socket) -> bytes: """Read TCP DNS message.""" ret = b"" try: message_len = sock.recv(2) ret = ret + message_len expected_len = 2 + struct.unpack("!H", message_len)[0] while True: portion_len = expecte...
5d6ceb6c85ec6dc0866ad3968de64d0ad4335883
579,321
def color_lane_pixels(img, leftx, lefty, rightx, righty): """ returns an image where the detected lane pixels are colored """ # copy image so as not to alter the original pix_img = img.copy() # color image red where the left lane was detected pix_img[lefty, leftx] = [255, 0, 0] # b...
9883e25bee1b23fd2a58fad78719424603911e2e
579,324
def atttyp(att: str) -> str: """ Get attribute type as string. :param str att: attribute type e.g. 'UNT002' :return: type of attribute as string e.g. 'UNT' :rtype: str """ return att[0:3]
ff8ce06bf39338727cd04b64518b755b9754aeea
579,325
def _transform_data(data, data_mapper=None): """Use mapper or transformer to convert raw data to engineered before explanation. :param data: The raw data to transform. :type data: numpy, pandas, dense, sparse data matrix :param data_mapper: A list of lists of generated feature indices for each raw feat...
d769c727f19f684822b1273a48918305ef76b148
579,326
import torch def normal_sample_shape(batch_size, mean_shape, std_vector): """ Gaussian sampling of shape parameter deviations from the mean. """ shape = mean_shape + torch.randn(batch_size, mean_shape.shape[0], device=mean_shape.device)*std_vector return shape
9c01b0a25134e811f62a524049eaa45b9570f4b7
579,327
def to_np(var): """Exports torch.Tensor to Numpy array. """ return var.detach().cpu().numpy()
d6ffcf50b2ad599bea00283fef07f693bec5a819
579,332
def indent(input_string): """Put 4 extra spaces in front of every line.""" return '\n '.join(input_string.split('\n'))
645f8f7e793e99aec9453327c5e07a429aeab439
579,335
import click def option(*args, **kw): """Factory function for click.option that makes help text more useful. When emitted, the help text will display any default passed to the option. :returns: Same object as `click.option`. """ default = kw.get('default') if default is not None: s_d...
508ef45352816c6eca06821d898a2b5b684dd911
579,337
def error_rate(y_true, y_pred, costs): """ Compute the weighted error-rate depending on the categories' weights Args: y_true (list): true color indices y_pred (list): predicted color indices costs (list): cost-per prediction error, created from the cost of error per cate...
0f0f66519975ba27be46d1e162c78d9d02daa9f2
579,338
def word_to_file(index, word): """Creates a filename from an index and a word.""" return "{}-{}.png".format(str(index).zfill(6), word)
6d001285fd0e4cf2b110efe72202c380f614625d
579,343
def _pt_to_data_coord(ax, x, y): """Convert (x, y) value in points into (x', y') value in data coordinates on axes `ax`.""" t = ax.transData.inverted() return t.transform((x, y)) - t.transform((0, 0))
6990a9736452adba4a39ccadc125e3553b827489
579,344
def get_es_worker(es_algorithm, logger, **kwargs): """Instantiate an evolution strategic algorithm worker. Return an ES algorithm worker from the algorithms package. Args: es_algorithm: algorithms.*. ES algorithm. logger: logging.Logger. Logger. Returns: algorithms.*Worker. ...
6a12d0f44c0edfe34235d145fdb38e5b64ac836f
579,350
from pathlib import Path from typing import Mapping from typing import Union def parse_mh_header(filename: Path) -> Mapping[str, Union[str, None]]: """ Attempts to parse the headers of an mhd file. This function must be secure to safeguard agains any untrusted uploaded file. Parameters ----------...
7d4c323e9f7e871415b927fda9e4c39da1b1db0b
579,351
from datetime import datetime def _prepare_summary(report, package_versions=None): """Return tests summary including number of failed and passed tests. Return summary with length of each list in report. Summary example: { "date": "08/06/2019 09:37:45", "failed": 61, "passed": ...
a50e8e796fd846faa4252860dc72570cc81e2239
579,352
from typing import Tuple def update_quarter_year_tuple( quarter_year_tuple: Tuple[int, int], quarters_to_increment_by: int, quarters_to_decrement_by: int) -> Tuple[int, int]: """Updates a given quarter_year_tuple by incrementing and/or decrementing it""" quarter, year = quarter_year_tu...
87b294d519b9d529172825511c0e6e77ccac18de
579,355
def convert_damages_data(damages): """Convert damages data from string to float and return converted data as a list.""" conversion = {"M": 1000000, "B": 1000000000} updated_damages = list() for damage in damages: if damage == "Damages not recorded": updated_damages.append(damage) i...
32d799f443ca3050af279764351bcbee9946d648
579,356
import pickle def load_pickled_city_file(path_to_file): # pragma: no cover """ Returns city object by loading pickled city file. Parameters ---------- path_to_file : str Path to city pickled file Returns ------- city : object City object """ city = pickle.load...
df2e195c314bc1abe8a5a727d89d1beb1b90ad1a
579,359
def is_in_ring(a): """ Whether the atom is in a ring """ return a.IsInRing()
0f0ea015aa4d91ea94d25affd4a937037a0f4ed0
579,364
def get_schedule_weekdays(schedule): """Return a list of weekdays the specified schedule is active.""" return [schedule["weekday"]] if schedule.get("weekday", None) is not None else range(1, 8)
cae9b8dba7e0f34f139cd555c31bb65af01f8ce9
579,367
from typing import List import math def _percentile_index(histogram: List[int], select_percentile: float = 0.95) -> int: """ Given an array of elements where each ith element refer to ith frequency, finds the index of the percentile indicated by percentile. :param histogram: Array of frequencies of i...
89eabb7af8c216fe69b5c7b3f04b34cf0d749915
579,368
def has_tag(filename, tag): """Check if a filename has a given tag.""" return f':{tag}' in filename
c6ae18c687a5bfeacfae635af3d858ec8bca0820
579,377
def _IntegerCeilingDivide(numerator, denominator): """returns numerator/denominator rounded up if there is any remainder.""" return -(-numerator // denominator)
a30875fde1d864b749b2d881915c9c463e79ed83
579,378
def get_op_name(op): """ Helper function that obtains the string name of an operation. """ return op.op.__class__.__name__
4622d2acbe83b3f8113cfdae85980609fc5027a0
579,379
def group_keys_by_attributes(adict, names, tol='3f'): """ Make group keys by shared values of attributes. Parameters ---------- adict : dic Attribute dictionary. name : str Attributes of interest. tol : float Float tolerance. Returns ------- dic Gro...
e229a8ee353400fb5098fef7f326a61d819d4cb9
579,380
def s3_url(bucket: str, key: str) -> str: """ Turn a bucket + key into a S3 url """ return '/'.join(["s3:/", bucket, key])
0cd749267b3d8ed3c63790b4348fa602eb6b6fca
579,385
def PredicateSplit(func, iterable): """Splits an iterable into two groups based on a predicate return value. Arguments: func: A functor that takes an item as its argument and returns a boolean value indicating which group the item belongs. iterable: The collection to split. Returns: A tuple c...
a2d631baa4b0ba140d74d0b1ba59d010e663ae45
579,386
def remove_dict_key(a_dictionary, val = None, dkey = None): """ ================================================================================================= remove_dict_key(a_dictionary, val, dkey) This function is meant to take either a value or a key t...
590ce4ca578533aaff886b10fd1a39ca154f6af9
579,391
import re def extract_quotes_sentence_regex(pattern, text): """ Extract matching groups and sentences from `text` based on regex `pattern` provided. Returns: list(tuple), list(str) – matched groups and sentences """ groups = [] sentences = [] for match in re.finditer(pattern, text): ...
31d53f743624f8c95e83c6ced580f069a358023d
579,392
def _is_test_bundle_with_provider(target, deps, bundle_provider): """Determines whether the target is a test bundle target that provides the specified bundle provider. Apple test bundle targets will provide a test bundle provider and will have a single dep that also provides the provider. Args: ...
b7a4bded018d52fd3ad4d375b04782662c225916
579,393
import operator def top_errors(errors_summary, min_count): """ Use the errors_summary to report the top errors. References: :func:`get_errors_summary` Args: errors_summary (dict): dictionary of error keys and total count in directory. min_count (int): include errors if frequ...
61cf2829247d4f0dd07cfbf3fb48fd1ed2ff5050
579,396
def load_metaparameters(param_dict=None): """ Parameters for bayesian optimizer. Default dictionary listed and updated by param_dict. """ metaparams = { 'conv_units': 3, 'filters': 80, 'filters_roc': 0., 'kernel_size': 100, 'kernel_roc': -1., 'stride': 5, ...
98844fa5876276b83a5fc3825d3d3dedeba26cd6
579,398
import torch def scale_transform(x: torch.Tensor, lower: torch.Tensor, upper: torch.Tensor) -> torch.Tensor: """ Normalizes a given input tensor to a range of [-1, 1]. @note It uses pytorch broadcasting functionality to deal with batched input. Args: x: Input tensor of shape (N, dims). ...
02196ea52538c361aceb9ce3264aae0b83c93fbb
579,399
import requests def geckoPrice(tokens, quote): """get price of combine pairs Args: tokens (comma separated strings): ie "bitcoin,ethereum" quote (comma separated fiat or quote currency): ie: "usd,eur" Returns: dictionary: Returns pairs quotes """ url = "https://a...
2016ef6a1845a0969ad55f46fba673bda8a3cc0d
579,403
def heatCapacity(T, hCP): """ heatCapacity(T, hCP) heatCapacity = A + B*T + C*T^2 Parameters T, temperature in Kelvin hCP, A=hCP[0], B=hCP[1], C=hCP[2] A, B, and C are regression coefficients Returns heat capacity at T """ return hCP[0] + hCP[1]*T + hCP[2]*T*...
a6541b37654eeeaca3bdfbc6d4b9b7844fecda62
579,404
def levenstein_distance(s1: str, s2: str) -> int: """Calculate minimal Levenstein distance between s1 and s2. Args: s1 (str): string s2 (str): string Returns: int: the minimal distance. """ m, n = len(s1) + 1, len(s2) + 1 # Initialize dp = [[0] * n for i in ran...
285ed0b81ce0ebd03cd594357b91a64ad38fb6a6
579,405
def pprSentPacket(pkt): """Pretty print a sent packet""" return "seq={seq}\ncurhop={curhop}\nnexthop={nexthop}\nsize={size}\ndata_len={data_len}\nmcsidx={mcsidx}\nflow={flow}\nmgen_seqno={mgen_seqno}".\ format(seq=pkt.seq, curhop=pkt.curhop, nexthop=pkt.nexthop, ...
867ec6052cf93adad6bc7a0905fd96afcce60382
579,407
def split_list_by_inds(data, inds1, inds2): """Take the data, a list, and split it up based on the indices in inds1 and inds2. Args: data: the list of data to split inds1, the first list of indices inds2, the second list of indices Returns: a 2-tuple of two lists. """ if data is None or len(data...
fc02ca98d2f2d6c3c6900385754139b04d413e1b
579,408
def get_val_stats(learner): """returns final stats from recorder""" rec = learner.recorder ret = {'loss':float(rec.val_losses[-1])} for i, name in enumerate(rec.metrics_names): ret[name] = float(rec.metrics[-1][i]) return ret
3f2e00a3ec0775732f300b1729da81876b98ca69
579,417
import json def read_h0_CF_file(h0_CF_filename): """ Reads CF Hamiltonian from json-file. Parameters ---------- h0_CF_filename : str Filename of the non-relativistic non-interacting CF Hamiltonian operator, in json-format. Returns ------- e_imp : float Average 3d onsi...
9ed809c930d85a3a0d46346ef978ba3e417b76cf
579,421
def _remove_gn_config_deps_touch_commands(commands): """Remove extra stamp touch commands from GN build. The Fuchsia build adds stamps for config_deps groups, remove them since they are not important for this comparison. They look like: touch TOOLCHAIN/obj/.../${config}_deps.stamp Args: ...
93a57b85ab4d141e42476624ce707effafaadea1
579,431
def get_rad_factor(rad, emission, solar_irr, emissivity=None): """ Return radiance factor (I/F) given observed radiance, modeled emission, solar irradiance and emissivity. If no emissivity is supplied, assume Kirchoff's Law (eq. 6, Bandfield et al., 2018). Parameters ---------- rad (num or ...
5d02a0e31012e4116e048e0a23e273824d926664
579,434
def shouldProcess(app): """ Check if an app should be downloaded and analyzed. """ if not 'internet' in app: return False if not 'unchecked' in app: return False return app['internet'] and app['unchecked'] and app['price'] == u'Free'
eae66c33549dc1233074a1e1d5fd5d732f3f5da8
579,436
def class_name(obj): """get fully qualified class name of object""" return ".".join([obj.__class__.__module__, obj.__class__.__name__])
0b11a023691b1f31174b059d391c7b7aae59677f
579,437
def HRneuron_model_single(Y,t0, a=2.8, alpha=1.6, c=5, b=9, mu=0.001): """ Criado por Luis A. Aguirre, adaptado para Python por Leonardo L. Portes. xyz_dot=HRneuron([x,y,z],t) Simulates the HR neuron model published in A MODEL OF NEURONAL BURSTING USING 3 COUPLED 1ST ORDER ...
84b56ea28f5b73bedd3972fe4f95da6557ca9a6c
579,439
def filesizeformat(bytes, sep=' '): """ Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 B, 2.3 GB etc). Grabbed from Django (http://www.djangoproject.com), slightly modified. :param bytes: size in bytes (as integer) :param sep: string separator between number and a...
ca202d97b0264268d3eccc39452717b5e1cfdd62
579,440
from typing import Optional from typing import List from typing import Tuple import re def get_ports(buffer: str) -> Optional[List[Tuple[str, str, str]]]: """Parses entity ports out of an input string The input is expected to be a string representing vhdl file content. If an entity is defined within this...
af4148dc4e7cb3d313ceff6d2a7ddbd7942edfb7
579,441
import re def parse_trained_models(argv): """Parse @syntax for specifying trained models on the command line. """ names = [] for part in argv: if re.match("^@[a-zA-Z0-9_-]+$", part): names.append(part[1:]) else: break rest = argv[len(names):] return name...
437d482d779b266fe421740ff6152fb66e3055ef
579,446
import re def convert_ellipses(text): """ Convert ``...`` in *text* into ellipsis HTML entities >>> print(convert_ellipses('Huh...?')) Huh&#8230;? """ text = re.sub(r"""\.\.\.""", '&#8230;', text) text = re.sub(r"""\. \. \.""", '&#8230;', text) return text
aab19f30a2092e6dd69ac6c8fd91e1a3225108e3
579,450
def _gaspr_input(endfin, pendfin, pendfout, **kwargs): """ Write gaspr input. Parameters ---------- endfin : `int` tape number for input ENDF-6 file pendfin : `int` tape number for input PENDF file pendfout : `int` tape number for output PENDF file ...
70f7208816b37469eb59346e98c43339e5a443c9
579,453
def is_package(item): """Does this string describes a package""" if "/" not in item and "\\" not in item: return True else: return False
70a699a71aedc8de4cc421d9d09cb6add9520fa7
579,457
import math def isolation_thermal_resistance(D, lambda_is, delta): """ :param D: Outer diameter of pipeline or diameter of the last layer if pipeline has many layers of isolation, m :param lambda_is: heat conductivity of isolation, W/(m*K) :param delta: Thickness of isolation, m :return: Therm...
92a098a476f6fe533e06739727d45d577ca22692
579,464
def get_total_pageviews(df, column_key): """ Return sum of numeric column from dataframe based on column title """ total_views = df[column_key].sum() return total_views
ab4fe6a195fa15d340c36667c296789cc78da720
579,468
def pair_in_collection(pair, pair_collection, have_direction=True): """ Check if a pair is in a collection or not. :param pair: A tuple :param pair_set: A collection of tuple :param have_direction if true (a,b) is different from (b,a) otherwise consider them as same one :return: boolean """ ...
bce927721f19b6992ae2a83a575cc54ac9d9764d
579,469
def _extract_img_data(path, run, count_per_run): """ Expects the image name to be encoded like: "<img_num>_<label>.png". Calculates the number of this image across all runs. Args: path: Path of the image. run: In which run index this image was rendered. count_per_run: How many ...
1566175145dfc7aeed16235ec787785452da5c44
579,470
import re def code_split(line): """split code line into atom Args: line (str): The code line Return: tokens (list): The list of atom token for code line """ return list( filter(lambda x: x and x not in [' ', ''], re.split(r'(\W|\s)', line)))
b1f4918c9a620c305df1287bc1cdd676e0055da4
579,473
def calc_merge_track_num(num_tracks: int, max_tracks: int) -> int: """Calculate the number of tracks to concatenate so that the final number of tracks generated is less than MAX_TRACKS Args: num_tracks (int): The number of tracks max_tracks (int): The maximum number of tracks possible ...
4744b5f2017bd5e364e452938fa2f33420de0b63
579,474
def test_home_path(tmpdir_factory): """ Makes a home directory for testing Args: tmpdir_factory (tmpdir_factory): Defined in pytest to make a temporary directory Returns: str: The path to the directory """ home_path = tmpdir_factory.mktemp("home") return home_pa...
5d2dc4ea5932b51e3ccc28f8d95f1aa2a66371f5
579,475
def nonlin_softsign(x): """Softsign activation function.""" return x / (1.0+abs(x))
d894376b10e85bdbda38c68ac6c72fe3f256527a
579,476
def rating_format(rating): """Return an integer equal to the string represented sum. Cast a string expressing a sum of integers delimited by a plus sign, e.g. 81+3, into an integer equal to a sum of the two numbers and return the integer. Parameters ---------- rating : str String r...
d772a97ba6ec967faab597a09b1316bfa95305aa
579,477
def calculate_distances(gs1, gs2): """ Calculates the distance (ellipsoidal) between to GeoSeries :param gs1: GeoSeries1 :param gs2: GeoSeries2 :return: The GeoSeries of distances """ return gs1.distance(gs2)
455040bb6952b0b74ee55105c8b87c910f051758
579,478
import shutil def check_commands(commands: list) -> list: """ Checks if all commands in the list exist in the system / environment returns a list of all missing commands """ missing = [] for cmd in commands: if shutil.which(cmd) is None: missing.append(cmd) return missi...
8a12880e2fded7f8f98a0458da937b59eb68482e
579,480
from typing import Callable import inspect def arity(func: Callable) -> int: """Returns the arity(number of args) Given a callable this function returns the number of arguments it expects >>> arity(lambda: 5) 0 >>> arity(lambda x: x) 1 :param func: :return: """ return len(insp...
20391334ca88fbf3c5fafe1d49b84bf68c96b042
579,481
def matches(item, *, plugins=None, subregions=None): """ Checks whether the item matches zero or more constraints. ``plugins`` should be a tuple of plugin classes or ``None`` if the type shouldn't be checked. ``subregions`` should be set of allowed ``subregion`` attribute values or ``None`` if...
bed1c1515489799f8695bfa50aedab2888f67407
579,482
def overlap(indices1, indices2): """Returns a boolean indicating whether two pairs of indices overlap.""" assert (len(indices1) == 2 and len(indices2) == 2) indices1 = sorted(indices1) indices2 = sorted(indices2) if (indices2[0] <= indices1[0] <= indices2[1]) or \ (indices2[0] <= indices1[1] ...
94ca141bd7320a617a51d0baf8a7f99f4e5231d4
579,490
def create_domains(prefix: str, n: int): """ Arguments: prefix: string - The prefix for all the domains created. n - How many domains to create. Returns: A list with all the domains """ s = [] for i in range(n): s.append(prefix + str(i)) return s
789f56f7183a680abc989ea53f9d7c3157eac939
579,492
def ansiSameText(s1:str,s2:str)->bool: """Compare two strings case insensitive""" return (s1.lower()==s2.lower())
2faad19d93fc60377418b9f6f0b56778f07b46be
579,495