content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def test(test_cases, function): """Given a dictionary of test_cases containing inputs and their expected results after a function has been run on them, returns True if all passed, returns False if any fail with a print statement on each failure.""" successful = True for test_case in test_cases: ...
41407be59ea0933f122cfe0f1dd7aadee0433e58
642,023
from pathlib import Path import logging def get_most_recent_run_id(run_recovery_file: Path) -> str: """ Gets the string name of the most recently executed AzureML run. This is picked up from the `most_recent_run.txt` file. :param run_recovery_file: The path of the run recovery file :return: The r...
e36041ccebfd146997142bd03d610b246888f46f
642,024
def nested_get(dic, path, delimiter='.'): """Get from dictionary by path :dic dict Source dictionaly. :path string Path withing dictionary :delimiter string Path delimiter :return: Value at path :rtype: unknown """ try: keys = path.split(delimiter) for key in keys[:-1]: ...
7ce38dfff407c286d38634d11b00b384ea1d69de
642,031
def str2num (text:str)->float: """ Convert string to number. Keyword arguments: text -- number in string format Output: number -- number converted """ assert text.isnumeric(),"Error: The string can not be converted to a number" number = float(text) retu...
22db18949633092f12e1cafc7470f07e821fd4a4
642,032
def apply_func_to_ast_helper(ast, func, acc): """Recursive helper function for "apply_func_to_ast". Args: ast: The AST instance. func: The function applied to the AST elements. acc: A list of values accumulated during application. Returns: The adapted AST. """ if is...
3a3a55540186b4b19876942423f165a2be4aa54c
642,041
def upper_section_score(die_value, final_dice, scorepad, ): """Evaluate dice from a roll for a given value and multiply the count by that value. E.g. for a die value of 3 and a count of two dice with that value the total score is 6 (die...
488d64cb1dcaf2810ae2a5cb0c8e535c1da375a1
642,043
def letterize(bytes_): """ Canonicalize a byte sequence. Removes non-alphabetic characters and converts to lower case. """ return bytes(b for b in bytes_ if chr(b).isalpha()).lower()
4eedae64acc020781af0c3005b7c0aea949da47c
642,049
def evalt(t): """ Evaluate tuple if unevaluated >>> from logpy.util import evalt >>> add = lambda x, y: x + y >>> evalt((add, 2, 3)) 5 >>> evalt(add(2, 3)) 5 """ if isinstance(t, tuple) and len(t) >= 1 and callable(t[0]): return t[0](*t[1:]) else: return t
6214f6c3e35be0556e04d5994d6f2e730756917a
642,052
def reverse_transcript_rna_char(base_char: str) -> str: """ A function that reverse transcripts mRNA char into DNA char returns '' when base char is not one of RNA bases :param base_char: :return rna_char: """ dict_of_rna_to_dna_base = {'A': 'T', 'U': 'A', ...
c4d4debdf21cf25f2045ddb64642a034b4fda2a5
642,053
from typing import Tuple def rotation_plane(xyz: Tuple[int, int, int]) -> Tuple[int, int, int]: """ Rotation des Punktes xyz um 90° im Uhrzeigersinn um eine z-parallele Achse durch den Punkt (2,2.0). :param xyz: Diesen Punkt rotieren. :return: Die Koordinaten nach der Rotation. """ return ...
1eae0cd066cff54d2f7c25d5aa41d046e2f363c4
642,057
def bond_or_stake(bond_price, ohm_price, reward_rate, n_rebase_to_fully_vested=15, claim_interval=1): """ Assumptions ----------- * Constant APY over vesting period: reward_rate == reward_yield, i.e. the amount of staked OHM doesn't change over the vesting period. * No trans...
4187ad7574a132d9cf0114e965200fd547ae5e2b
642,061
def change_ext(input_fn, new_ext, no_dot=False, remove_player=False): """ Return the input path `input_fn` with `new_ext` as extension and the part after the last '-' removed. If `no_dot` is True, it will not add a dot before of the extension, otherwise it will add it if not present. `remove_pla...
6f0563dbb72def59034f37feeffa6574b3e7b428
642,063
def get_atoms_for_flow(flow, persistence_backend): """ Gets all atoms for a flow :param obj flow: A TaskFlow flow :param obj persistence_backend: A connection to the persistence backend :return iter[obj, ..] all_atoms: An iterable of atom objects """ return persistence_backend.get_atoms_for_...
f42fb5d71b7bcb061cb1cf1559781e3140622188
642,065
import typing def calcNthTerm(a_1: typing.Union[float, int], r: typing.Union[float, int], n: typing.Union[float, int]) -> typing.Union[float, int]: """ Calculates the nth term of a geometric progression (an = a1 * r^(n-1)). :param a_1: First term. :param r: Common ratio. :param n: Number of desire...
e6dce78e4aad43333819a0db07c265fc00b237d3
642,066
import torch def eye(m, dtype=None, device=None): """Returns a sparse matrix with ones on the diagonal and zeros elsewhere. Args: m (int): The first dimension of corresponding dense matrix. dtype (`torch.dtype`, optional): The desired data type of returned value vector. (default i...
21d4f5a2460b07d75f4e7ffed9a8ee89c2e220d7
642,067
def get_tag(record, name, default=None): """ Loks in the XML tag 'record' for other tags named 'name', and returns the value of the first one. If none is found, it returns 'default'. """ tag = record.getElementsByTagName(name) if len(tag) and len(tag[0].childNodes): return tag[0].chi...
77631e4788e1d8cc0deba0e27e41be0b3a56fd56
642,070
def BuildIdToBuildStatus(db, build_id): """Fetch a BuildStatus (with stages) from cidb from a build_id. Args: db: cidb.CIDBConnection object. build_id: build id as an integer. Returns: build status dictionary from CIDB with 'stages' field populated. """ build_status = db.GetBuildStatus(build_id)...
3d38d040d834e4d41afc99edfb9226f234347724
642,071
from io import StringIO def to_XML_string(Coalesce_object, indent_level = 1, pretty_print = True): """ Assigns the XML representation of a Coalesce object to a string. :param Coalesce_object: a Coalesce object with an "export" method :param level: multiply by 4 to determine the number of spaces for...
e981dd7efb18b2254b6b12af8bd32a748c6774fd
642,072
def average_of_factors(n): """ n (int): number Returns the average of the positive divisors of n """ # Initialize the sum total = 0 # Initialize the number of factors count = 0 for i in range(1, n+1): # Check if i is a divisor of n if n % i == 0: total += ...
622f5793685c03ec0b367c23313327264a79b9b2
642,078
def is_valid_read(read): """Check if a read is properly mapped.""" if (read.mapping_quality >= 20 and read.reference_end and read.reference_start): return True return False
1ad54406c86a5375b880d6cc00afad3a173fda58
642,079
def calc_time_axis(df): """Returns the number of minutes between midnight of the earliest date and midnight of the day after the latest date in the dataset""" time_min = df.Timestamp.min() time_max = df.Timestamp.max() diff_in_days =(time_max.date() - time_min.date()) diff_in_minutes = (dif...
d7d5ef397381815405e38e018a01a8618db9c348
642,081
def filter_cds_utr_ncrna(df_in): """Filter regions CDS, UTR5, UTR3 and ncRNA by size and trim.""" utr5 = df_in.region == "UTR5" cds = df_in.region == "CDS" utr3 = df_in.region == "UTR3" ncrna = df_in.region == "ncRNA" size = df_in.end - df_in.start >= 100 df_out = df_in[(utr5 & size) | (cds ...
41ff9d99d6ac318c88aa19262b06798172a75e69
642,084
def url_joiner(url, path, trailing=None): """Join to sections for a URL and add proper forward slashes""" url_link = "/".join(s.strip("/") for s in [url, path]) if trailing: url_link += "/" return url_link
888abf4917fbcb476f39a6cda7cc46880bd9aa4e
642,085
def check_for_code(module): """ Check if there's at least one class or one function in the module. """ fd = open(module, 'r') for line in fd: if line.startswith('def ') or line.startswith('class '): fd.close() return True fd.close() return False
12161a25b2d09d2626e478f406745cadd67ae8ab
642,094
def bytes_endswith(x: bytes, suffix: bytes) -> bool: """Does given bytes object end with the subsequence suffix? Compiling bytes.endswith, with no range arguments, compiles this function. This function is only intended to be executed in this compiled form. Args: x: The bytes object to examine....
5d81c0b9dd37f2a0938c428e6bf2676f6b17b969
642,096
def find_allocas(func): """ Find allocas that can be promoted to registers. We do this only if the alloca is used only in load and store operations. """ allocas = set() for op in func.ops: if (op.opcode == 'alloca' and all(u.opcode in ('load', 'store') for u in func.uses[...
e7ca08ebf07b9822b7d4480abf5bfe3ef300a3b8
642,097
from typing import List def search_word_from( db: List[str], query: str, split_token: str = "", ingore_case: bool = True ) -> List[str]: """Search str qurey from list of str db. If split_token is given, split each str in db by split_token and check for exact match. If ingore_case is True, ignore case....
18b54bff51686601a5f1bd4eb8c61e538c0328d4
642,100
def currency(value=0.0, currency='R$'): """ #EN-US: → Formats the value to display it as a monetary value. :param value: the value to be formatted. :param currency: (Optional) the currency symbol that will be used for formatting. The default is Real (R$). :return: the value formatted with th...
a8da828a65ad04043a6f6c77c046999666b3c877
642,103
def filters_logical_and(f1, f2, f3): """ given three filters, returns the logical and of these filters in the order: f1 AND f2 AND f3. Parameters: ----------- f[1/2/3]: `dict` filter expression to be combined. Returns...
b1fb288219a475b2807804af22dcf1989aa67689
642,107
import json def generate_ctx(row, input_lifespan=0, output_lifespan=2): """ Generates json objects for the input and output contexts, containing their names and lifespans, from a dictionary corresponding to a row in a dataframe. Example format: {"name": "await_18", "lifespan": 0} : param row...
05c2c4c102e5c71f77aa8182e57ccaf42da9d49d
642,109
def get_model_fields(model): """ Retrieves all non-auto- and non-relation- fields from the supplied model and returns as a list """ return list( filter( lambda x: x.get_internal_type() != "AutoField" and not getattr(x, "is_relation"), model._meta.get_fields(),...
a4caf70abdb7aded4f0a4cef7d17f547b631e8ec
642,111
def calculate_stats(array): """Return min, max, avg in the given array. """ _count = 0 _max = _sum = 0.0 _min = None for number in array: _count += 1 if _min is None or number < _min: _min = number if number > _max: _max = number _sum += nu...
73c727de560a9cdb0355c4b77d9ae134805b0843
642,117
import random def choose_from_options(options, name, selection="user"): """ Prints out options from a list, and returns the requested option. :param options: dict or Array, options to choose from. If dict, the value entries are assumed to be docstrings explaining the individual options :param...
2edbd17da2fb2ddb4034983ded4fc6c367a8494d
642,119
def flatten(items): """Flattens a potentially nested sequence into a flat list. :param items: the sequence to flatten >>> flatten((1, 2)) [1, 2] >>> flatten([1, (2, 3), 4]) [1, 2, 3, 4] >>> flatten([1, (2, [3, 4]), 5]) [1, 2, 3, 4, 5] """ retval = [] for item in ite...
be48b6481bf47c9d80902b0f3df7f25a533d6814
642,121
def __is_dunder(attr_name: str) -> bool: """ check if a given attr_name is `double underscored` one. """ return ( attr_name.startswith('__') and attr_name.endswith('__') )
a6ed2aa725c7835d2bbb9c20913245afcdfbc5bd
642,123
def barcode_header(date, price): """Format barcode header info line date: datetime object price: float barcode_header takes a datetime object and a float, representing the price and formats them as so: MSTAR YYYY-MM-DD DAY P.p Example: MSTAR 2016-11-12 SAT 1.2 """ ...
e079ba68511242ba92600a4364a476502abe5411
642,126
def is_guc_configurable(cursor, guc): """Check if guc is a preset parameter https://www.postgresql.org/docs/current/static/runtime-config-preset.html """ cursor.execute(""" SELECT EXISTS (SELECT 1 FROM pg_settings WHERE context <> 'internal' AND...
ca01a26c7cd276eabc44414820cb8c10dd837a18
642,127
def init_filter(df, report=False): """Keep relevant subset of topics""" keep_topics = ['economy', 'europe', 'health', 'crime', 'education', 'immigration', 'law'] groups = df.groupby('topic') sub_df = df[df['topic'].isin(keep_topics)] sub_groups = sub_df.groupby('topic') if report: print(...
40f1b09f3e1bda21b2a28d31303250c19a437b71
642,129
import re def parse_gtf_attr_line(attr_line): """parse a GTF attributes line""" if len(attr_line) == 0: return {} attr_line = [x.split(' ') for x in re.split('; +', attr_line.replace('"', ''))] attr_line[-1][-1] = attr_line[-1][-1].rstrip().replace(';', '') return dict(attr_line)
e338dc12476abd5560ea828fb9bf1b5259ef47b2
642,130
import six def is_string(value): """Return a boolean value indicating whether the value is a string or not. This method is compatible with both Python 2.7 and Python 3.x. NOTE: 1. We can't use isinstance(string_value, str) because strings in Python 2.7 can have "unicode" type. 2. We can't use isi...
809e4d43390219f08cf81e9389b38e045aae0e0c
642,132
def iterative_lcs(var1, var2): """ :param var1: variable :param var2: 2nd variable to compare and finding common sequence :return: return length of longest common subsequence examples: >>> iterative_lcs("abcd", "abxbxbc") 3 >>> iterative_lcs([1, 2, 4, 3], [1, 2, 3, 4]) 3 """ ...
838b9592ce9bf27cf4f5854dd66ff13110da8cc0
642,134
def color_amount(accel_component): """Convert acceleration component (x, y, or z) to color amount (r, g, or b)""" standard_gravity = 9.81 # Acceleration (m/s²) due to gravity at the earth’s surface accel_magnitude = abs(accel_component) # Ignore the direction constrained_accel = min(accel_magnitude, s...
487f1c66426bc1c69f86781c46906d2631aedf17
642,135
from typing import Iterable from typing import Any def pretty_function(name: str, args: Iterable[Any]) -> str: """Produce a pretty textual description of a function call. Produce a string describing a function call. This is of the form: name(args[0], args[1], ...) Arguments: name: Name of fu...
b9c7147f1d7e0500da1037c44e049c12998e17e2
642,138
def insertFace(bm, v): """ insert face using an array of vertices indices :param bm: :param v: list of vertices indices """ a = [] for k in range(len(v)): a.append(bm.verts[v[k]]) f = bm.faces.new(a) bm.faces.ensure_lookup_table() return f
c02b2ca52d4aa3bfc89daeb84579e66bc55b1310
642,140
def accuracy_calculation(actual_label, predicted_label): """计算准确率 :param actual_label: 真实类标 :param predicted_label: 模型预测的类标 :return: 准确率(百分制) """ correct_count = 0 for i in range(len(actual_label)): if actual_label[i] == predicted_label[i]: correct_count += 1 return c...
ae788ab2aa9fb9c1ad111cf749d9bc047c372319
642,141
def conv_8to16(v): """ Conversion d'une variable 8 bits en 16 bits :param v: var (8b) :return: 16bit conversion """ return ((v << 8) + v) & 0xFFFF
1f9f1c764ca91c175d8d69de3878247b6c35c5ca
642,142
from typing import Tuple from pathlib import Path def endswith(path, suffixes: Tuple[str, ...]) -> bool: """ Returns whether the path ends with one of the given suffixes. If `path` is not actually a path, returns True. This is useful for allowing interpreters to bypass inappropriate paths, but alw...
0feae633bede862ac839b95ebe0a9b3ffd16949d
642,147
def decode(param): """Decodes the given param when it is bytes.""" if isinstance(param, (float, int)): return param return param.decode("utf-8")
566ec8ff60c88b18e42a432b10a512e20ba007fe
642,150
def good_response(response): """ Returns True if the response is HTML. """ resp_type = response.headers['Content-Type'].lower() return response.status_code == 200 and \ resp_type is not None and resp_type.find('html') > -1
3c0613258ae92196488d9c2b474d83f63aa24699
642,155
import re def capital_case_without_symbols(name: str) -> str: """ Determine the name of the output file by stripping all special characters and capital casing the words. :param name: Deck name (unsanitized) :return: Sanitized deck name """ word_characters_only_regex = re.compile(r"[^\w]") ...
71d11f7ba41244f05e407fd38b708987c58a5012
642,157
def LineColour(argument): """Dictionary for switching line colours where appropriate""" switcher = { 'Black': 'k', 'Red': 'r', 'Green': 'g', 'Blue': 'b' } return switcher.get(argument, argument)
6a45aa61641143125b2bae24989721324a3bbe35
642,161
def getNetwork(networks, name): """ Get the network with a specific name. This method does not create a network if no network exists with the given name. Arguments: networks -- Network objects for searching. name -- Name the network shall have. Returns: network object on s...
2c84f24fa839fad86d82dc56a6484659fa259226
642,165
def getTag(read, tagId): """ Returns the specified tag or None from an AlignmentRecord """ for i in read.tags: if i[0] == tagId: return i[1] return None
55c5d6b4f6d2a6e1d6920f44e9b61464970e3818
642,166
def merge_lists(results_from_fc): """ Function for merging multiple lists """ combined_list = [] for li in results_from_fc: combined_list.extend(li) return combined_list
812c48ea055225b8a5f056469ebc31d5c6f7615d
642,169
import math def zr2uv(zr, wavelength, sinalpha, refr_index, magnification=1.0): """Return u,v in optical units from z,r given in units of the wavelength. For excitation, magnification should be 1. Examples -------- >>> numpy.allclose(zr2uv((1e3, 1e3), 488, 0.9, 1.33), ... (13....
c475eb622b02fe347d6c035e059159564790abe9
642,171
def set_convolution_options(opts, convolution_options=None): """Set the IPU convolution options for the session. .. code-block:: python # Set "availableMemoryProportion" flag to "0.1" opts = create_ipu_config() opts = set_convolution_options(opts, convolution_options={"availableMemoryP...
102dd191af47dd1e971d423a0c5e5a3ea8b34532
642,174
def select_all_reads(conn): """ Query all rows in the reads table :param conn: the Connection object :return: """ cur = conn.cursor() cur.execute("SELECT * FROM reads") rows = cur.fetchall() return rows
60ce7f30d48de0a661b01f4f9185a434128b5059
642,176
def check_equals(generated_value, expected_value, **kwargs): """Check that generated_value is equal to expected_value.""" return generated_value == expected_value
722f79878c6e9874e24cb6bcefcaee63f8a5f0db
642,184
async def auto_increment_mongo(client, database, collection): """Retrieve the next _id for a given Mongo collection that's based on _id being a simple integer.""" db = getattr(client, database) collection = getattr(db, collection) last_id_list = list( collection.aggregate([{"$group": {"_id":...
3fe058f9cd1421070e608dd66f90d4d92c86f81d
642,188
import configparser from pathlib import Path def get_path_setting(name=''): """ Gets a path specified in the Files section of the settings.ini file. :param name: One of the variable names in the FILES section of settings.ini :return: Path object from the pathlib library """ config = configpars...
5338a0335d00be1ec05b5f63c1f1c1f7555e7005
642,189
def int_32_lsb(x: int): """ Get the 32 least significant bits. :param x: A number. :return: The 32 LSBits of x. """ return int(0xFFFFFFFF & x)
afca818f3c7eadc201770bb02a3538bb533b5bb4
642,190
def __index_query(query, key: str) -> float: """ Returns a property of the query class, keyed by a string. The key must be one of: ['Memory', 'Duration', 'Bytes Processed', 'Bytes Billed'] Args: query (BigQueryResult): A BigQuery result class key (string): A key ...
6550d6985b6cffe71101a4a0f8a89a3391650296
642,195
def readiter(fi, names, sep=' '): """ Return an iterator for item sequences read from a file object. This function reads a sequence from a file object L{fi}, and yields the sequence as a list of mapping objects. Each line (item) from the file object is split by the separator character L{sep}. Se...
29339e354f782d60d1f88851152a066c3550294c
642,202
def mapSeries(requestContext, seriesList, mapNode): """ Short form: ``map()`` Takes a seriesList and maps it to a list of seriesList. Each seriesList has the given mapNode in common. .. note:: This function is not very useful alone. It should be used with :py:func:`reduceSeries` .. code-block:: none ...
689a5630f4288e03dbb03417b49a1eb70ff041c8
642,204
import itertools def arbitrary_string(size=4, base_text=None): """ Return size characters from base_text, repeating the base_text infinitely if needed. """ if not base_text: base_text = 'test' return ''.join(itertools.islice(itertools.cycle(base_text), size))
ad430683fa0a98ecddaf96f288f96a54ef39d576
642,205
def is_sequence(x): """Algorithmically determines if x is a sequence.""" try: len(x) x[0:0] return True except: return False
175e9ffbda72559796386a2e44479ac409bfe280
642,206
def getWebImgType_file(filename): """ Get image file type of an image stored in disk. Can be used to verify if an image is available for web. :param filename: The file you want to verify. :return: Image file type. If image is invalid, returns False. """ data = open(filename,'rb').read(11) #...
8e196b94314cc03d724de6844c120f709560502d
642,207
import requests import json def get_token(keyword, timespan): """ Retrieves a token from Google Trends, based on the keyword and timespan. This function is a deritative of a function within Pytrends by github.com/GeneralMills. Licensed under the Apache license, version 2.0. Changes made by githu...
670806ff76689bbe5e20619241f3aefce97bdcde
642,209
def _toolkit_get_topk_bottomk(values, k=5): """ Returns a tuple of the top k values from the positive and negative values in a SArray Parameters ---------- values : SFrame of model coefficients k: Maximum number of largest positive and k lowest negative numbers to return Returns -...
811d700a9c6d0f465567892783f9ecc1ded3bdec
642,217
import socket def get_ip_using_standard_if(host='8.8.8.8'): """ Gets the ip of the 'standard interface' Source: https://stackoverflow.com/a/7335145 Args: host (str): optional ip of a host to connect to. Default is '8.8.8.8' Returns: own ip address on standard interface """ s = so...
965fb8c19b212b6a5be746c2d5932e55fb951100
642,220
from datetime import datetime def load_timestamps(timestamp_file): """Load timestamps from file.""" # Read and parse the timestamps timestamps = [] with open(timestamp_file, 'r') as f: for line in f.readlines(): # NB: datetime only supports microseconds, but KITTI timestamps ...
87b6cfab557d097c257a21a01b15473fa01290ff
642,222
def get_sum(value1, value2): """Return the sum of two values.""" return value1 + value2
b2abe7de3f0b0d842bc901827aeb824aebc5d538
642,225
def total_hazard_perceived_by_town(hazards: list, town_id: int, facilities: list) -> int: """ For the specified town retrieve the total risk caused by opened facility :param hazards: list of list, describe every hazard for the couple (town,facility) :param town_id: the town of interest :param facil...
1f3a1da00c84f965b3dcb939c84d4e28fd2462cc
642,229
def find_single_number(arr: list[int]) -> int: """Finds the single number in a non-empty array of integers where every number appears exactly twice, except for one which appears exactly once. Complexity: Time: O(n) Space: O(1) Args: arr: array of numbers with all but a single eleme...
a10f5f8cbb49968073c4a28d4eca883c128fb542
642,233
def calc_iou(box_a, box_b): """ Calculate the Intersection Over Union of two boxes Each box specified by upper left corner and lower right corner: (x1, y1, x2, y2), where 1 denotes upper left corner, 2 denotes lower right corner Returns IOU value """ # Calculate intersection, i.e. area of overlap between the 2 ...
c330af6b6b213c5086fa8df079228ee214407455
642,234
def LeapYear(year): """Leapyear returns 1 if year is a leap year and 0 otherwise. Note that leap years famously fall on all years that divide by 4 except those that divide by 100 but including those that divide by 400.""" if year%4: return 0 elif year%100: return 1 elif year%400: return 0 else: return 1
a494b28ed7eda9800a9be99edc1149a4421eb318
642,238
def FormatTimestamp(timestamp): """Returns a string representing timestamp in RFC3339 format. Args: timestamp: A datetime.datetime object. Returns: A timestamp string in format, which is accepted by Cloud Logging. """ return timestamp.strftime('%Y-%m-%dT%H:%M:%SZ')
7c4acf42bf9fbf8151611d63fa6c2f116a121a1b
642,239
def _split_version_id(full_version_id): """Return server and version. Args: full_version_id: Value in the format that is set in the 'CURRENT_VERSION_ID' environment var. I.e. 'server:server_version.minor_version'. Returns: (server, server_version) tuple, or (None, server_version) if this is the ...
8c373703a89c5cc4f437e61a0f74a633979df006
642,240
def _g_theta(theta,p): """ :param theta: dimensionless electron temperature :param p: electron power law slope :return: correction term for power law electron distribution """ aa = (6.0 + 15.0 * theta) / (4.0 + 5.0 * theta) gamma_m = 1e0 + aa * theta gtheta = ((p-1.0)*(1e0+aa*theta)/((p-...
65975c654d1eff7efa7c7ae409bde695b9ec4c72
642,246
def metadata_key(config): """ Build a key to a file in the 'metadata' directory of the published dataset. """ def func(filename) -> str: return f"{config.s3_publish_key}/metadata/{filename}" return func
3bb870841595f0521b0d02968cad655296e604c3
642,250
def _tostr(x): """ Convert a value to the native string format. Parameters ---------- x : str or bytes value to convert to a native string. Returns ------- str """ if isinstance(x, bytes): return x.decode() else: return str(x)
de8705895bc528b755a3c809b34fd24801a23999
642,255
import sqlite3 def db_connector(filepath): """ Creates an SQLite server from the given filepath :param filepath: the location of the SQLite database :return: An SQLite connection """ print("Initiating connection to database") return sqlite3.connect(filepath)
b207321f32c7a57c8d52a382b851835cef8375af
642,257
from pathlib import Path import json def load_params(model_dir: Path) -> dict: """ Load params from json Args: model_dir (Path): model directory path Returns: dict: dictionary of params """ file_name = model_dir / 'params.json' with open(file_name, 'r') as f: para...
40d146ed612f5fc39ef870367f4f626e2a0da3c4
642,258
def count(rdd, field_name): """Perform a word count on the specified field of the input rdd by tokenizing the text. Return an rdd of dicts with "word" and "count" fields. """ # Split the text in the records into lowercase words words = rdd.flatMap(lambda r: r[field_name].lower().split()) # Gen...
2bf6a8bcd53ce7ca2a7280401b03e5bff330395c
642,259
from typing import Dict from typing import Any from typing import Union from typing import List def get_kernel_shape(attributes: Dict[str, Any]) -> Union[List[float], None]: """ Get the kernel shape from a dictionary of a model's attributes :param attributes: a dictionary of a model's attributes :ret...
29864e00ebd9e20dcfed94c6309f50c7d0eff7d4
642,261
def _create_id(data_set_id, record_id): """ The record_ids are not necessarily globally unique, because they're user provided and are only guaranteed to be unique within a collection. So that we have a unique primary key we're joining them with a colon. >>> _create_id('foo', 'bar') 'foo:bar' ...
d6b317bb5366d66fe62b94cdaa324a08fcf697ea
642,265
def all_none(*args): """Return True if all arguments passed in are None.""" return all(a is None for a in args)
5d7c695b64f82f15b86be9cef64430f93ac8e14e
642,268
import gzip def read_file(filepath): """ Read normal or gz file (based on their extension .gz) """ data = None if filepath.endswith(".gz"): with gzip.open(filepath, "rb") as f: data = f.read() else: with open(filepath, 'r') as myfile: data = myfile.read(...
10fcf2abd8fb9a696bfb7206a8dd441d2fe86dc1
642,269
import math def _is_external(a, b): """ Check if blob b is outside blob a :param a: first blob. This is larger than b. :param b: second blob. This is smaller than a. :returns: if b is outside the radius of a """ ay, ax, ar = a by, bx, br = b d = math.sqrt((ax - bx)**2 + (ay - by)**2)...
b5ff7c93f8bd0929404105432cce817de4501c17
642,277
def find_complete_faces(indices, faces): """ Given a set of vertices, find the ones that make complete faces. Parameters ---------- indices : list of integers indices to connected vertices faces : list of lists of three integers the integers for each face are indices to vertices...
78097e380ffec9326f892e2d54f9722e811af907
642,278
import re def year_grabber(year_str: str): """ From a string containing a year, possibly more than one, pull out the first. >>> year_grabber("1948194819491949195019501951") '1948' >>> year_grabber("abs1987") '1987' >>> year_grabber("1987a") '1987' >>> year_grabber("<y>1916&#821...
dbb429f74ebfabd7715be0298099f7be0ddbfec1
642,280
def subsumed(id, s_visited_id, STKMAX): """Helper for is_term_id and is_surv_id --- If id is (q,in_str,stk_str) and exists a member (q1,in_str1,stk_str1) in s_visited_id then subsumed is True if q==q1, in_str==in_str1 and stk_str1 starts with st...
6f4e6acf398ba966037032b33f70028e013e28e6
642,281
def get_number(s): """ Check that s is number If s is a number, returns it as a float. If not, returns s without modification. Inputs: s - An input string or number Outputs: value - Either float(s) or False if s cannot be cast to float """ try: return float(s) e...
0df8f0225b443079670c83a5dee9e3b56787aeb8
642,282
import re def get_github(text): """ Fetches GitHub and GitHub's gist urls from the text obtained from the resume. :param text:(unicode string) parsed text from the resume. :return: a list of GitHub and Gist urls """ github_url = [] githubs = re.findall('.*[\w\.-]*github[\w\.-]*.*', text) ...
1a9ad9af2298bbbcb3a49cc340337e18080890bf
642,283
def get_files(folder, restrict_to_folder=False): """ Gets all files in a folder + subfolders :param folder: pathlib.Path object :param restrict_to_folder: bool. If false also the files in the subdirectories are found """ if not restrict_to_folder: return [x for x ...
ff65b266bd7970e9086a6be930dfc8064fb63c88
642,288
def post_process_human_data(human_data): """Remove unwanted space and solves double shad(ཉིས་ཤད་) split cases Args: human_data (str): human segmented data Returns: str: clean human segmented data """ human_data = human_data.replace('། །', '།།') human_data = human_data.replace(...
ea4624b47a068d2de2b7f85e0bf8132bbb91e06e
642,289
def tempo(msg): """Returns the usec tempo value from a tempo meta message.""" return (msg[3] << 16) + (msg[4] << 8) + msg[5]
0b282dec32180c991513f32a664352594bb9ba29
642,295
def load_wordlist(filename): """Load a list of word from a file (one word per line)""" words = [] with open(filename, 'r') as f: for line in f: words.append(line.strip().lower()) return words
d2fef472ad7cb5a7c77d614183f4a47970fff38e
642,296
import json def __convert_json(string): """ Converts a string into JSON format. If the conversion fails, returns None. """ try: return json.loads(string) except: return None
e6d5d6c848a42d1fe5e722d1ae3d1ae8cf429df3
642,297
def divisors_to_string(divs): """ Convert a list of numbers (representing the orders of cyclic groups in the factorization of a finite abelian group) to a string according to the format shown in the examples. INPUT: - ``divs`` -- a (possibly empty) list of numbers OUTPUT: a string represe...
10d236d585c59d25661300d737940485a0398124
642,298