content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Sequence def string_list_to_html(string_list: Sequence[str]) -> str: """ Converts a string list to an HTML bullet list. """ if not string_list: return "<p>None</p>" item_list = [f"<li><code>{item}</code></li>" for item in string_list] return "<ul>" + "".join(item_lis...
c4891a8fb0317d6fd9b5ca14240894e4f30ad15f
648,216
def wrap(node, tag): """Wrap the given tag around a node.""" wrap_node = node.ownerDocument.createElement(tag) parent = node.parentNode if parent: parent.replaceChild(wrap_node, node) wrap_node.appendChild(node) return wrap_node
82126216ebfd0bcd008f27eb24fb0361934bb2c2
648,218
def square(x): """ Return x squared. >>> square(3) 9 Extra tests: >>> square(1) 1 >>> square(0) 0 >>> square(-4) 16 """ return x * x
d431c12ca3d3270e97f6679d139406d8524594fc
648,219
import re def part1(parser): """ count the number of imputs that complete match rule zero """ rule_count = 0 for line in parser.inputs: match = re.match("^"+parser.rules['0']+"$", line) if match: rule_count+=1 return rule_count
3a7730f816f147220412de683ab8fc58773b4804
648,220
def net_gains(principal,expected_returns,years,people=1): """Calculates the net gain after Irish Capital Gains Tax of a given principal for a given expected_returns over a given period of years""" cgt_tax_exemption=1270*people #tax free threashold all gains after this are taxed at the cgt_ta_rate cgt_tax_r...
623b6c1126ad2486ba94c3b02f1a8ed335fed74b
648,228
def is_unitless(ds, variable): """ Returns true if the variable is unitless Note units of '1' are considered whole numbers or parts but still represent physical units and not the absence of units. :param netCDF4.Dataset ds: An open netCDF dataset :param str variable: Name of the variable "...
8574327f657e67d2165f247a8892c38eab89784f
648,232
def int_to_base(val, bdgts): """ Convert an integer into a string with a given base. Args: val: Integer value to convert bdgts: List of base digits Returns: String corresponding to the integer """ # Check zero if val == 0: return bdgts[0] # Check negative n...
56ac66dff33f01a9f3524458a268203f8a58cb1f
648,233
def average(values): """Averages the values in an iterable. values: iterable containing numbers """ return sum(values) / float(len(values))
50f9cc821d1423a79ce90f2a3f143119f110b1c8
648,235
from typing import Match def replace_one_decorated_callable_start(m: Match) -> str: """Define the replacement function used in `correct_all_decorated_callable_starts`.""" start = int(m[5]) + int(m[6]) # number of decorators + line number of the first decorator return f"{m[1]}/_type={m[2]}{m[3]}{start}:{m...
819079d96e2aa60b745f16488dae916880dc0ba6
648,236
def _GetFailureTestRefs(test_summary): """Gets a list of test summaryRef id of all failure test. Args: test_summary: dict, a dict of test summary object. Returns: A list of failure test case's summaryRef id. """ failure_test_refs = [] if 'subtests' in test_summary: for sub_test_summary in test_...
47c8e7e5af7c2e5847983d1f492617e061eb1e19
648,237
import warnings def check_consecutive_ranks_on_same_nodes(mpi): """ Check that consecutive MPI ranks are on the same nodes, and return a corresponding boolean. Print a warning message if it is not the case, this this can affect performance. """ # Skip this function if there is only one MPI ran...
fbfb7319c7da4bb19cb605eaebf0d1cc7270bb96
648,238
def printBondedAtoms(bond, shiftdummySerial): """Generate bond atoms line Parameters ---------- bond : Bond Object Bond Object shiftdummySerial : int Shift to remove structural dummy atoms and get index (should be 4) Returns ------- bondLine : str Bond line data...
0315b36368df927d6789b3306e8193a77227547f
648,239
import json def to_json(context) -> str: """Convert the selected Selection Sets of the current rig to JSON. Selected Sets are the active_selection_set determined by the UIList plus any with the is_selected checkbox on.""" arm = context.object active_idx = arm.active_selection_set json_obj =...
2bf65df6d1e158331a043f89c2083cc1c260267a
648,242
def spaces(x, spa): """ spaces(x, spa) Returns an array of the spacings from the original point given the distance and the number of spaces. """ return list(map(lambda y: y * (x/spa), range(1, spa + 1)))
00649fd53fa727ff4a5674972a6540ad740bbae2
648,246
import random import string def random_string(length=8): """Generate a random string of letters and numbers. Args: * *length* (int): Length of string, default is 8 Returns: A string (not unicode) """ return "".join( random.choice(string.ascii_letters + string.digits) for...
d2eec1fc58ead99e877fdfc84dca14788ffa794f
648,247
import json def pretty_print(js): """ try to convert json to pretty-print format """ try: return json.dumps(js, indent=4, separators=(",", ":"), sort_keys=True) except Exception as e: return "%s" % js
58c9751975bb8e4cc4b1f4bbbf681b5ddd392f21
648,255
def traditional_constants_icr_equation(tdd): """ Traditional ICR equation with constants from ACE consensus """ a = 450 return a / tdd
e4ad065665481978e52a6f82a986a51e2af1c659
648,256
import re def get_matching_columns(dataframe, *args, **kwargs): """ Filter column whose names match the regular expressions defined in ``args``. Args: dataframe (pandas.DataFrame): Input DataFrame \*args (List[str]): List of regular expressions matching column names Keyword Args: ...
b5cbcb3c21c7004436865164ed6351fd8c1233a1
648,264
def _clean_sample(sample, fields=None): """ Clean a sample resource from unnecessary fields :param sample: the sample to clean :type sample: dict :return: Sample cleaned from unnecessary params :rtype: dict """ if fields is None: fields = ['_links', 'releaseDate', 'updateDate',...
6e8987dbf7376f58ce75786ef3cec184a3598e8e
648,266
def train_network(net, epochs, training_data, validation_data, batch_size, callbacks, verbose=1): """ train a network on data for a fixed number of epochs parameters: net: network to train epochs: number of epochs training_data: training data under the format of numpy arrays (inputs,...
d89704adc14bf2b609fa7bdb2300d59c4b2b5b1f
648,267
def rgb(minimum, maximum, value): """Convert value within range to RGB.""" assert value <= maximum assert value >= minimum minimum, maximum = float(minimum), float(maximum) r = 2 * (value - minimum) / (maximum - minimum) b = int(max(0, 255 * (1 - r))) r = int(max(0, 255 * (r - 1))) g = 2...
3c611cda74f12d87d3a603f1a88d2e6255d17495
648,270
def binomial(n, k): """ Return binomial coefficient ('n choose k'). This implementation does not use factorials. """ k = min(k, n - k) if k < 0: return 0 r = 1 for j in range(k): r *= n - j r //= j + 1 return r
7786725d8b8aeb1511a69d7dd373ccfe21143beb
648,272
def getConvergents(coeffs: list) -> list: """Calculates convergents of the continued fraction Details: https://en.wikipedia.org/wiki/Continued_fraction Parameters: coeffs: list coefficients of continued fractions Returns: result: list list of tuples (nomina...
490b104cbfb03b770d4933cecca01029b7b78fea
648,276
def reverse_int(integer: int) -> int: """Reverse an integer.""" reversed_int = int(str(abs(integer))[::-1]) if integer < 0: reversed_int *= -1 return reversed_int if -(2**31) < reversed_int < 2**31 - 1 else 0
5af0fd4da0fdf262b63fda0eeaba406a7bc534a0
648,278
def dekatrian_week(dek_day: int, dek_month: int) -> int: """Returns the Dekatrian week day from a Dekatrian date. Here we can see the elegance of Dekatrian, since it's not necessary to inform the year. Actually, barely it's necessary to inform the month, as it's only needed to check if that is an Achron...
14cbc62546fe4bf5ffc4234b8d892ae94f28256b
648,279
from typing import List def add_sos(token_ids: List[List[int]], sos_id: int) -> List[List[int]]: """Prepend sos_id to each utterance. Args: token_ids: A list-of-list of token IDs. Each sublist contains token IDs (e.g., word piece IDs) of an utterance. sos_id: The ID of the...
779912dee80879b0f1def915264b2135b4661925
648,281
from typing import Dict import pkg_resources def get_pip_packages() -> Dict[str, str]: """ Returns a dictionary of pip packages names and their versions. Similar to `$ pip freeze` """ return { package.project_name: package.version for package in pkg_resources.working_set }
1869cb0a0f5b2f5d62f0f540f23efc7ad8468df1
648,283
def dominate(s1, s2): """ Returns true if S1 dominates S2. S1 dominates S2 if S1 is better (it our case lower) in the two fitness functions """ score1 = s1.get_fitness_score() score2 = s2.get_fitness_score() return False if (score1[0] > score2[0] or score1[1] > score2[1] or (sco...
ab3a7df8a55fe451ffa5ecda85935aeada70a829
648,285
from typing import Dict import operator def argmax(dict_: Dict): """ Get the argmax. Parameters ---------- dict_ : dict Returns ------- argmax : tuple Example ------- >>> argmax({'a': 10, 'b': 70, 'c': 20}) 'b' """ return max(dict_.items(), key=operator.itemg...
c88541f7da4cd61ef63d7ad11932ed69d83a1971
648,286
def field_cleaner(field: str) -> str: """Convert field string from an html response into a snake case variable. Args: field (str): A dirty field string. Example: |Input | Output | |------------------|------------------------| |Previous Close |...
005438e5990e492249c93023d0de758acc6bdda0
648,287
import math def multinomial(i_s): """Compute the multinomial (i_1 + ... + i_n)!/(i_1! ... i_n!).""" itot = 0 denom = 1 for i in i_s: itot += i denom *= math.factorial(i) return math.factorial(itot) / denom
4f4a6e86ab3d55fd33498f83d5a00cd397605b23
648,288
from typing import Any def build_where(**conditions: Any) -> str: """ Build WHERE statement with several `conditions` If no `conditions` passed return `WHERE 1 = 1` In case if a value has primitive type it will be an equal condition and in case if it is an iterable it will be an include condition...
ec2d7c2aebe4798a7cb06b20f9d2c06259afdadd
648,289
def build_user(first, last, **user_info): #The double star tells python to make an empty dictionary #so we can mix-and-match data types (e.g., string and int) """Build a dictionary containing user information""" user_info['first'] = first user_info['last'] = last return user_info
c17141259260fd3d59154dbd90e749ce8fc4ad7f
648,290
def _is_hd(release_name): """ Determine if a release is classified as high-definition :param release_name: release name to parse :type release_name: basestring :return: high-def status :rtype: bool """ if "720" in release_name or "1080" in release_name: return True return False
eac085e5de4a5edd63d1960cb1b3a8ef79b7fd58
648,295
def assign_orchestrator( self, orchestrator: str, ssl_enabled: str = "false", keepalive_count: int = 0, port: int = 0, ) -> bool: """Assign an Orchestrator to the appliance .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint *...
c689ba7a635394a1b0807c1fa026bad29ea630e8
648,298
import random def random_password(choices, length): """ Create Random strings The random string is created out of the set of `string.ascii_letters` and `string.digits`. Args: length -- the length of the new random string Returns: A random string cosisting out of ascii letters and th...
5d7065ebfd1ef1df5d91fabe0708c087540ecd2b
648,301
from typing import OrderedDict def _set_table_column_names(names=None): """Define the table data columns to use in the html header. Parameters ---------- names: collections.OrderedDict The dictionary of string column header names and their types Their types are the accepted google typ...
15f5afc4f4efaf81e0380de90adaed83a6001d3d
648,310
import re def clean_ne_records(record: str): """Base cleaning for ne records""" record = record.replace("\t", " ").replace("|", " ").strip() record = record.replace("\u200c", " ") # Nim-fasele record = re.sub(" +", " ", record) # space cleaner return record
5c1a7c5854511d97c38c191e9ffbd7abe9ef520f
648,316
import json def json_validation(template): """ Json validator :param template: json template :type template: object :return: bool """ try: json.loads(template) except ValueError: return False return True
84cd9cf6ccdd9bf7b01031ac9f7f88ddea10b375
648,317
def simpleSubtractDictionaries(d1,d2): """ Subtract the elements of the second dictionary from the ones in the first dictionary. Assumes both share the same keys. """ assert set(d1.keys()) == set(d2.keys()) return dict([ (key, d1[key]-d2[key]) for key in d1])
a102f1a19658f03316d743c8568ccc9bd188c2a4
648,322
from datetime import datetime def make_sim_exp_names(config, n_exp): """Helper to create simulator directory names using datetime and config""" # Pull out some metadata date = datetime.now().strftime('%Y%m%d_%H%M%S') n_nonmot = config['exp_params']['n_non_motile'] n_mot = config['exp_params']['n_...
56269cfad20775e8c83eb88a099bb3a9fe41ad5d
648,326
from typing import Any def as_kafka_configuration_bool(value: Any) -> bool: """ Convert a value to a Python boolean, using the same conversions used by the librdkafka configuration parser. """ # https://github.com/edenhill/librdkafka/blob/c8293af/src/rdkafka_conf.c#L1633-L1660 if isinstance(va...
61f63b2f6dadc997290b454fc6d3cdcef81a5e9b
648,328
def calc_charge_trans(m_potential, x_potential, iv, elec_affinity_non_metal, d_mx_avg): """ Calculate the estimated charge transfer energy (eV) of a structure :param m_potential: Float, the metal site Madelung potential in V :param x_potential: Float, the non_metal site Madelung potential in V :par...
563b677492ce13928262347e7ba8352d11aa44f7
648,329
import re def _extract_failed_ps_instances(err_msg): """Return a set of potentially failing ps instances from error message.""" tasks = re.findall("/job:ps/replica:0/task:[0-9]+", err_msg) return set(int(t.split(":")[-1]) for t in tasks)
b7cf036584dde71bfdb0bf0ead9017b94b7280e3
648,330
def init_vault(client, shares=1, threshold=1): """Initialise vault. :param client: Client to use for initiliasation :type client: CharmVaultClient :param shares: Number of key shares to create :type shares: int :param threshold: Number of keys needed to unseal vault :type threshold: int ...
24f410289861da6545f244d7993daf88ef8b2055
648,331
def rw_at_form_temp(rw, rw_temperature, temperature_units, new_temperature): """ Converts formation water resistivity from a known temperature to formation temperature. Parameters ---------- rw : float Water Resistivity (ohmmm) rw_temperature : float Temperature Rw was measured ...
844d0deaa81ec2ccda055384ccf5fd8d63ba2c56
648,332
def decimal2dm(decimal_degrees): """ Converts a floating point number of degrees to the equivalent number of degrees and minutes, which are returned as a 2-element list. If 'decimal_degrees' is negative, only degrees (1st element of returned list) will be negative, minutes (2nd element) will always be p...
198f587b8467d5c8720e8d8544e31a042b76fa02
648,335
def sort_by_username(user): """Sort students by their username""" return user['username']
d4e5dd7a5d682dfd67140632f9de419dc9c813f1
648,336
def _sanitize_str_to_list(dim): """Make dim to list if string, pass if None else raise ValueError.""" if isinstance(dim, str): dim = [dim] elif isinstance(dim, list) or dim is None: dim = dim else: raise ValueError( f"Expected `dim` as `str`, `list` or None, found {di...
94ed147b8d5b1762e987813362e7d5b7a112d22a
648,340
def prepare(link:str): """A function to check if the link is complete (it includes the protocol) and that it can be used by the library (it should not end with a slash) Args: **link (str)**: The link to check/prepare Raises: **Exception**: Thrown if the protocol is not present in the URL Returns: **str...
c26c0f1a50a95188721b33044dd434b466318bad
648,344
def to_pandas_adjacency(G): """ Returns the graph adjacency matrix as a Pandas DataFrame. The row indices denote source and column names denote destination. Parameters ---------- G : cugraph.Graph Graph containing the adjacency matrix. """ pdf = G.to_pandas_adjacency() retur...
96ae061c25d536c0b98d1923f9e4a9a3cb00c726
648,347
def parse_response_item(item_response_list): """ The function parses GetItemsResponse and creates a dict of ASIN to AmazonProduct object params: *item_response_list* List of Items in GetItemsResponse return Dict of ASIN to AmazonProduct object """ mapped_response = ...
5a676e4c7c336f3334d860402ce2600d9a90f86d
648,349
from typing import Iterable def to_lower(text_docs_bow: Iterable[Iterable[str]]) -> Iterable[Iterable[str]]: """Converts all letters in documents ("bag of words" format) to lowercase. Args: text_docs_bow: A list of lists of words from a document Returns: A generator expression for all of...
939e2ff1d4ff8b14c1bd785e7cb7e086444ad4f8
648,351
def is_parameter(value): """Returns True if the given value is a reference to a template parameter. Parameters ---------- value: string String value in the workflow specification for a template parameter Returns ------- bool """ # Check if the value matches the template par...
03e402ca07affe4cecc550d8aa27365660e74ee5
648,354
import math def get_average_color(x, y, x_len, y_len, image, skip=1): """ Returns a 3-tuple containing the RGB value of the average color of the given square bounded area of length = n whose origin (top left corner) is (x, y) in the given image""" i = image.load() r, g, b = 0, 0, 0 count = 0 ...
506f8dd794fe58d543e50fdaeb326bc285a0f1c6
648,356
import datetime def convertfrom_epoch_time(epoch_time: "int | float"): """Takes a given epoch timestamp int or float and converts it to a datetime object. Examples: >>> now = get_epoch_time()\n >>> now\n 1636559940.508071 >>> now_as_dt_obj = convertfrom_epoch_time( no...
6aabd4ef1ceabcc522b7585dcd91938c9d4cfd4d
648,360
def is_prime(number): """checks if a given number is prime""" prime = True for n in range(2, number): if prime and number % n == 0: prime = False print("The number is not prime") if prime: print("The number is prime") return prime
a6119b54e3ff16d7e94ad4ac06e224c623ee5dd1
648,361
def distance_from_origin(position): """ Get the 'taxicab geometry' distance of a position from the origin (0, 0). """ return sum([abs(x) for x in position])
71975e73ed0192fce6cace6c4bcf3c5c23f47e8d
648,366
import json def extract_aws_policies(action: str, client, managed: bool): """ Call the AWS IAM API to retrieve policies and perform an action with them. :param action: what action to take with the IAM policies (list, dump) :param client: the boto client to use :param managed: (boolean) if true, i...
5bf99bd20fbdde1accf2cbd00c99e83882c08104
648,376
def preprocess(matrix, index): """ Takes as list of lists (in other words a matrix), and returns a list of preprocessed sentences for all elements at the index specified for the inner list. For BERT models, dropping punctuation affects accuracy. See https://www.aclweb.org/anthology/2020.pam-1.1...
4b2ccc1075da4e54b04735a6a7ba578008dbc6a7
648,380
def one_hot(i, n): """ Makes a one-hot vector of length n with 1 in position i. """ one_hot = [0 for x in range(n)] one_hot[i] = 1 return one_hot
2c482899b68c547ca235e7f561ea4b676553f27c
648,387
def convert36ToAscii(start, chs): """Convert decimal address to ascci address :param start: NBP adress in decimal reverse:Big Endian Byte Order: The most significant byte (the "big end") of the data is placed at the byte with the lowest address :param chs:tsring of all digits and ascii upper :return:NB...
e8b00d5d0a49d4f128b84a4c874e268b5d92ca9e
648,390
def read_all_commits(filename): """Read all commits from the given GIT log file.""" commits = [] with open(filename) as fin: for line in fin: splitted = line.strip().split(" ", 1) commits.append(splitted) commits.reverse() return commits
fa56a84b0d5f6684fbcf362299b773d1d3939fa0
648,392
def DetermineType(value): """Determines the type of val, returning a "full path" string. For example: DetermineType(5) -> __builtin__.int DetermineType(Foo()) -> com.google.bar.Foo Args: value: Any value, the value is irrelevant as only the type metadata is checked Returns: Type path stri...
40154c8e9c678d8d2effa68584aeb058ef13a98f
648,394
def optional(args, key): """If the given key is in args, return the corresponding value, otherwise return None """ return key in args and args[key] or None
23f3f158aa1ee473fb09e1a90650223f571d299e
648,395
def get_correlation_metrics_from_args(args): """ Extract a list of correlation metrics to use from the program arguments. """ correlation_metrics = [] if args.pearson: correlation_metrics.append('pearson') if args.spearman: correlation_metrics.append('spearman') if args.kenda...
39c8eb0aaad5f9a8c63c02a41157aab3149fb955
648,397
import math def distance_calculation(homeLattitude, homeLongitude, destinationLattitude, destinationLongitude): """ This function returns the distance between two geographiclocations using the haversine formula. Inputs: 1. homeLattitude - Home or Current Location's Latitude ...
8cbe8df1e771f180cc61293c44f3ed46f98a42d2
648,399
def get_authors_by_publisher(data, ascending=True): """Returns the authors by each publisher as a pandas series Args: data: The pandas dataframe to get the data from ascending: The sorting direction for the returned data. Defaults to True. Returns: The sorted data as a pand...
757efc92aa8b1446971c917387d7cc6b6c34bd2c
648,401
import torch def temporal_iou(spans1, spans2): """ Args: spans1: (N, 2) torch.Tensor, each row defines a span [st, ed] spans2: (M, 2) torch.Tensor, ... Returns: iou: (N, M) torch.Tensor union: (N, M) torch.Tensor >>> test_spans1 = torch.Tensor([[0, 0.2], [0.5, 1.0]]) ...
45d033a3bdb6fe615feb1c1fe09ab063dd45a266
648,406
def regular_plural(noun: str) -> str: """English rule to get the plural form of a word""" if noun[-1] == "s": return noun + "es" return noun + "s"
5b2ef7924fe93fb26b20639816032f6c85071bf0
648,410
def get_requested_roles(settings): """Retrieve any valid requested_roles from dict settings""" if ('requested_roles' in settings and settings['requested_roles'] not in ['None', None]): return settings['requested_roles'].split(',') else: return []
8e31dc039172650be85a8ce9a33f722e31d0e90a
648,412
import pickle def decode_pickle(data): """ Restore original object using Pickle. """ return pickle.loads(data, fix_imports=False)
3030c89191e293210acea52b651edddc2b724f2f
648,413
import csv import io def splitStr(delimiter, escapeChar, s): """ Splits s based on delimiter that can be escaped via escapeChar """ # Let's use csv reader to implement this reader = csv.reader(io.StringIO(s), delimiter=delimiter, escapechar=escapeChar) # Unpack first line for x in reader: ...
1fb07495aa712df39bff00f5b7f2fbeaef5046b6
648,416
def updated_querystring(request, params): """Updates current querystring with a given dict of params, removing existing occurrences of such params. Returns a urlencoded querystring.""" original_params = request.GET.copy() for key in params: if key in original_params: original_params....
85112c6ca8cc18e70f89cf75699201d47a8cfd14
648,420
def get_name(pbs_file): """ Extract the model name from a `CMIP5-compatible file name <https://cmip.llnl.gov/cmip5/output_req.html>`_. Parameters ---------- pbs_file : str A filename that obeys the CMIP5 standard. Returns ------- str The name of the model. """ ...
0011bd0dcdb0cd2249300ceb5e1ec7e56ad15e3d
648,422
def get_rn_freqs(core): """ Get red noise frequency array from a core, with error message if noise array has not been included. """ if core.rn_freqs is None: raise ValueError('Please set red noise frequency array in ' ' the core named {0}.'.format(core.label)) el...
93059b12ed995ffc9356624232a9c5d8a7526e45
648,425
def repeat_along_dimension(array, number, dim=0): """Return a view into the array with a new, repeated dimension. Parameters ---------- array : torch.Tensor number : int The number of repeats. dim : int The dimension along which to repeat. Returns ------- array : to...
bc45cf653a6f61de381fcd0b586711235a3554b0
648,428
def get_tableblocks(page): """Get all the TableBlocks for a given page. TableBlocks can be stored either directly in page's content, or in a FullWidthText item. So we must check both. """ try: data = page.specific.content.raw_data except Exception: return [] tableblocks = lis...
7831201f6b2ecc63f35fbaec1927597c3d0baafb
648,429
import six def hostport(scheme, host, port): """ Returns the host component, with a port specifcation if needed. """ if (port, scheme) in [(80, "http"), (443, "https"), (80, b"http"), (443, b"https")]: return host else: if isinstance(host, six.binary_type): return b...
b07388cf3fa9cc53e0bfc3dc3619dd69f8969ae5
648,430
def format_embed_length(data: list) -> list: """ If the length of the data is greater than 1024 characters, it will be shortened to that amount. Parameters ---------- data : list The list containing the description for an embed. Returns ------- list The shortened descri...
dcc843f64788cc7be122f36556aa57576173fe95
648,432
def renamed_prefix(cfg, old, new): """ Returns a new dictionary that has all keys of `cfg` that begin with `old` renamed to begin with `new` instead. """ renamed = dict(cfg) for k in cfg.keys(): if k.startswith(old): renamed[new + k[len(old):]] = renamed.pop(k) return ren...
efca0995d82c287e53b3b70b89f2317864ba64bd
648,433
def get_rec_names(study_folder): """ Get list of keys of recordings. Read from the 'names.txt' file in study folder. Parameters ---------- study_folder: str The study folder. Returns ---------- rec_names: list LIst of names. """ with open(study_folder / 'na...
ab9c7eddc0ce593ddcea129c2122e753a94432bf
648,436
def flatten_manifests(root_manifest, only_with_entries=False, recursion=0): """ Convert a tree-structure Manifest into a flat list structured list of Manifests. :param root_manifest: :type root_manifest: Manifest :param only_with_entries: Switch to filter result to only those manifests with ...
759783d2fb8046c198831fda33edf4d7f6034d44
648,439
def split_list(doc_list, n_groups): """ Args: doc_list (list): is a list of documents to be split up n_groups (int): is the number of groups to split the doc_list into Returns: split_lists (list): a list of n_groups which are approximately equal in length, as a necessary step...
b6191f91773c1ae22157a2dcc2c57c02acd858be
648,445
def insert_breaks(s, min_length, max_length): """Inserts line breaks to try to get line lengths within the given range. This tries to minimize raggedness and to break lines at punctuation (periods and commas). It never splits words or numbers. Multiple spaces may be converted into single spaces. Args: ...
ca202f3e3c86ac7b13f62ae057583cfe54e06e0b
648,447
def srun(arg_dict,qos=True,time=10,mem=4): """Return srun call, with certain parameters appended. Arguments: ---------- arg_dict : dict Dictionary of arguments passed into this script, which is used to append parameters to srun call. qos : bool, optional Quality of service, set to ...
7769b4023a2caa9a3b0bfe47ea12af48ecf930f6
648,451
def split_unique(df_data, field): """ Split the DataFrame based on unique value from field Parameters ---------- df_data : pandas DataFrame Original data to split field : String Column name to split data on unique value Returns ------- df_split : dict A dic...
e062b5721b80e29c0871b43fe1ae2081e04c9569
648,454
def get_edge_vertex_ids(g, sort=True): """get_edge_vertex_ids Returns a list of tuples containing the source and target for each edge in the graph. Parameters ---------- g : :obj:`graph_tool.Graph` A graph with edges. sorted : :obj:`bool`: Determines whether...
8d942e7ff62213510de7ebefc53faeef0f4de07b
648,455
def logistic(x, r): """Logistic map, with parameter r.""" return r * x * (1 - x)
cea604f4bac55d9229add831fd3c3f36a0bcf212
648,457
def get_emotion_dict(emo_metrics): """Returns a dictionary in which keys are emotions and values are confidences. Args: emo_metrics: A list of dictionaries, which each have the keys 'name' and 'confidence', describing emotions detected from FeelNet. Returns: A dictionary as described above. """ ...
911f317ac6a63318f8fe1366251edb84d6feb1b1
648,459
def encode_int(i): """Encode an integer for a bytes database.""" return bytes(str(i), "utf-8")
96f405d02c1fd53316ad9b81cfc8e5eceac453f1
648,463
from typing import List from pathlib import Path from typing import Set def get_cl_tags(files: List[Path]) -> List[str]: """ Come up with descriptive tags given a list of files changed. For each path, use the first rule that applies in the following order: 1) Pick the path component right after the last "li...
bb274802e7e9f00af3c76c36b8ba48b085266db2
648,466
def get_tuner_submodel_name(output_model_name="tuned_climpp", num_years=10, margin_in_days=45): """Returns submodel name for a given setting of model parameters """ return f"{output_model_name}_on_years{num_years}_margin{margin_in_days}"
33b64040446de89387fd85bd58c47873712a3bd6
648,472
def test_nan(dataframe): """ Test if dataframe contains nan value Parameters ---------- dataframe: pandas dataframe Raises ------ ValueError If contains nan, raise ValueError Returns ------- is_valid: boolean True if did not contain nan, False if contain ...
1dcc96521fbbff2f95d7e4395367f50882c3b96b
648,477
def hits(service): """Returns metric 'Hits'.""" return service.metrics.select_by(**{'system_name': 'hits'})[0]
001ff6efcc1e3027d0c1c2ab1d39f0c3e04d4643
648,483
def parse_field(field_string): """ Get a tuple of the first entries found in an psimitab column (xref, value, desc) :param field_string: :return: A tuple (xref, value, desc) - desc is optional """ parts = field_string.split(":") xref = parts[0] rest = parts[1] if "(" in rest: ...
2e8454b29bd9be18601460a293b8ff0d72580b75
648,484
def get_package_name(package, customer=None, python="2.7"): """ returns the egg filename (without the fs path), e.g. nexiles.gateway.appservice-1.0.0-py2.7-customer.egg """ if customer: return "{}-{}-py{}-{}.egg".format( package.import_name, package.version, ...
e0a5801cfe9e2ea0bf62cab9aa89f08a0394c612
648,485
def d1d2_index(det_df,d1,d2): """ Return the index of a given detector pair from det_df. Parameters ---------- det_df : pandas dataFrame dataFrame of detector pair indices and angles d1 : int detector 1 channel d2 : int detector 2 channel Returns ---...
540ef78b15ab8d5e85efd3b9528c199a1e21ad43
648,486
def load_from_file(ids, data_path = "."): """ Takes an array of ids or single id and loads that srt file and returns the srt files in a dictionary with IDs as keys. """ if type(ids) is int or type(ids) is str: with open(data_path+str(ids)+".srt","r") as f: data = f.read() ...
55b7eda06e6d7a2e928745e3ab3bba273bfb9723
648,490
from datetime import datetime def parse_time(s='2016-03-16T17:31:14Z'): """ Converts Piazza Date-time format into a pythonic construct. Examples of Piazza Datetime: - 2016-03-16T17:31:14Z """ format = "%Y-%m-%dT%H:%M:%SZ" return datetime.strptime(s,format)
c8f2c7d31f091b2d0470a23eafc81e36bf09d685
648,491