content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def parse_argparser(parser): """Parse the argparser. Parameters ---------- parser : argparse.ArgumentParser Returns ------- dict """ args = parser.parse_args() config = vars(args) return config
ba7ea0623039f491405b49976569a7b1a680c47f
665,220
def enthalpyVaporization(T, eVP): """ enthalpyVaporization(T, eVP) enthalpyVaporization (kJ/mol) = A*(1-T/critT)^n Parameters T, temperature in Kelvin eVP, A=eVP[0], critT=eVP[1], n=eVP[2] A and n are regression coefficients, critT: critical temperature Returns ent...
cca3e061d884d95833d5adf833de29940b822d55
665,226
def metricresample(metric, samples): """ Resample a metric vector using random resamples computed using indexresample. Parameters: - - - - - metric: array of scalar values describing mesh samples: indices to sample from """ resamples = metric[samples] return resamples
b5a894dc56a2841ab4eda4396ab2719306633892
665,227
def get_reader_pairs(reader): """Return the set of alphabetically-sorted word (str) tuples in `reader` """ return {tuple(sorted([w1, w2])): score for w1, w2, score in reader()}
8e38bcbe58d5377d8fc171857390c1e836ecc9b3
665,229
from typing import Callable def _node_not_implemented(node_name: str) -> Callable[..., None]: """ Return a function that raises a NotImplementedError with a passed node name. """ def f(self, *args, **kwargs): raise NotImplementedError(f"'{node_name}' nodes are not implemented") return f
69d8d1df08e4896962cef981fd758271e09c4d32
665,230
def sorted_options(options): """Sort a sequence of options into canonical order. Return a list with the same elements as *options* sorted using the option :attr:`number<UrOption.number>` as the key. The sort is stable: options with the same number remain in their original order. This operation is...
9b7cd3b2a5e88b160dd30f1bd4253269b93d4a26
665,231
def GenerateLibraryDescription(lib_name): """Generates a library description consisting of its full name and version. Args: lib_name: The name of the library for which a description is to be generated. Returns: A string description of the given library. """ tmp_lib = __import__('adspygoo...
6a3046f7c45b90f3b6e45d1a32fb5da8c365dad3
665,235
from typing import Counter def term_freq(tokens) -> dict: """ Takes in a list of tokens (str) and return a dictionary of term frequency of each token (doc = a list of tokens) """ #counting occurrences of each unique token term_count = Counter(tokens) #total number of tokens n_tokens = ...
175763a993e4097a82b70635cca95eb5a1eaee64
665,236
def inverseTransform(tran): """ An SVG transform matrix looks like [ a c e ] [ b d f ] [ 0 0 1 ] And it's inverse is [ d -c cf - de ] [ -b a be - af ] * ( ad - bc ) ** -1 [ 0 0 1 ] And, no reasonable 2d coordi...
79a5edc7a0387838d5cab42b52e6ec303c20a98b
665,237
def element(a): """ Return the element """ return a.GetSymbol()
d2e335aff22978da0ae4627c8cae25f6b80cd602
665,238
def get_class_plural_name(cls): """Convert class name to it's plural form""" base = cls.__name__.lower() for ending in ('s', 'z', 'x', 'ch', 'sh'): if base.endswith(ending): return base + 'es' if base.endswith('y'): return base[:-1] + 'ies' else: return base + 's'
f7df342b440da1ec6f4d3c2b9d8bc0df35bca075
665,240
def drop_col(df, col): """ If a pandas.DataFrame has a particular column, drop it. args ---- df : pandas.DataFrame col : str returns ------- pandas.DataFrame, same DataFrame without column """ if col in df.columns: df = df.drop(col, axi...
7ea9fd416ba04a1d6dfa160c68407347819d31e2
665,241
def print_deps_stdout_arg(request): """Argument for printing deps to stdout""" return request.param
63d735cd08b71bf12bef624c187ca9e128621ae6
665,243
def read_map_file(file_name): """ reads a map file generated by TI's ARM compiler. the function expects a file of a form similar to: . . . GLOBAL SYMBOLS: SORTED BY Symbol Address address name ------- ---- 00000000 __TI_static_base__ 00000000 g_pfnVectors 00000200 __S...
553fb838402220424a94335d3ad566c2a93a224f
665,244
from typing import Union from typing import List def process_dorms(dorms: Union[str, None] = None, size: Union[int, None] = None, default_dorm: str = 'Unknown', dorm_separator: Union[str, None] = None) -> List[List[str]]: """Process the dorms. Args: ...
848c7bee5a5701465ac791c3196f5253ecfd50f8
665,247
def N_bar(tree): """ Returns the $\bar{N}$ statistic: the average number of nodes above a terminal node. """ leaf_count = 0 nbar = 0 for leaf_node in tree.leaf_node_iter(): leaf_count += 1 for parent in leaf_node.ancestor_iter(inclusive=False): nbar += 1 retur...
d80bcc320ab50fec946562389f0a4bccb5077677
665,248
def osm_area_sql(grid, osm, cat): """ Returns a sql fragment that sums the total area by category of a grid cell coverd by OSM polygon features Args: grid (string): a PostGIS table name containing the grid osm (string): a PostGIS table name containing the OSM polygon features ca...
5d3898dd8434cc3481dde3d43f6e957100550e94
665,249
from typing import Any def get_record_code(record: dict[str, Any]) -> str: """Returns the concatenated codes for a taric record.""" return f"{record['record_code']}{record['subrecord_code']}"
11e438fbee7a831494ce47fcd59dce8c3840adcb
665,252
import requests from bs4 import BeautifulSoup def get_soup(request, element, class_value): """ Uses the BeautifulSoup library to retrieve the HTML text for a given webpage request. :param request: The webpage request for which the HTML text is to be retrieved. :param element: The element of the webpag...
c93d82b978394119af240fcafdc6c9e5050751e5
665,253
def _write_url_file(images, separator=" "): """ ImageNet generally uses a specific format to store the URLs of images. This converts a set of images into this format. Args: images: The set of images to write. It should contain tuples with image WNIDs and URLs. separator: Default string used to separat...
4e67aebdc59d2e72a95e6435f4550c0aaf95dca5
665,255
import pathlib from typing import Union def _should_granule_be_processed( filename: str, save_dir: pathlib.Path, order_number: Union[str, int] ) -> bool: """ Return True iff the given granule should be processed (i.e. has not yet been saved) Args: filename (str): Name of the granule `.h5` fil...
f8693f2dd1052c09ea9718f14040e76e2a9bf051
665,257
def _merge_keys(dicts): """Return the union of the keys in the list of dicts.""" keys = [] for d in dicts: keys.extend(d.keys()) return frozenset(keys)
221289bf8697d63edb32f1405e324d2d05376931
665,261
def is_list_of_dict(value): """ Check if value is a non-empty list of dictionaries """ return isinstance(value, list) and len(value) > 0 and all(isinstance(elem, dict) for elem in value)
a99d91a9ecbc92e203a001b94a413c757fa25ffb
665,263
def nav_active(context, item): """ Returns 'active' is item is the active nav bar item, and '' otherwise. """ default = '' try: url_name = context['request'].resolver_match.url_name except: return default if url_name == item: return 'active' return default
1c2db3e1a829cf74106d7771078c0e6fa5a1e951
665,264
from typing import IO from typing import Any from pathlib import Path def containing_directory(file_object: IO[Any]) -> Path: """Return the directory containing the given file.""" return Path(file_object.name).parent.absolute()
9bcc5669e7377bbb919ec9f979ae83f4e6905a4c
665,265
import re def GetVersion(path): """Get the version of this python tool.""" version_str = 'XWalk packaging tool version ' file_handle = open(path, 'r') src_content = file_handle.read() version_nums = re.findall(r'\d+', src_content) version_str += ('.').join(version_nums) file_handle.close() return vers...
7a8283021aedcd3d0788ef5c857a133d1be3726f
665,267
import re def find_ip(url): """ Find IP address in string (code from dusty 1.0) """ ip_pattern = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\s') # pylint: disable=W1401 ip_value = re.findall(ip_pattern, url) return ip_value
00dc6dbff6cee52bca91fac33d6e35a4c3025dfe
665,276
from typing import List def l2s(inputs: List) -> List[str]: """ Transforms a list into list of strings. :param inputs: objects :return: list of str(object) """ return [str(inp) for inp in inputs]
26a250ca0ae499281621a619e96c22414fa65d54
665,277
def readIdentificationFile(infile, sep="\t"): """ read lines from a peptide identification file and store the column split version of those lines (without header) in a list. (return: list of peptide identifications as list of identification ) infile: file containing identification lines (like output of I...
867f87b5e3daf46911e1c1b0d0b54fbc9e9c958e
665,281
from typing import Dict def parse_node_id(node_id: str) -> Dict: """ 解析节点ID :param node_id: 节点ID "host|instance|host|123" :return: { "object_type": "HOST", "node_type": "INSTANCE", "type": "host", "id": 123, } """ object_type, node_type, _type, _id = node_id...
bb2d34f715a363dbbb8ef188491898095e9c966e
665,282
def intsqrt(x): """ Return the largest integer whose square is less than or equal to x. """ if x == 0: return 0 # invariant: l^2 <= x and x < r^2 l = 1 r = x while r-l > 1: m = l + (r-l)//2 s = m*m if s <= x: l = m else: r =...
bd9927beba0ffaa79af6df39fd6f71e8e3fa13d5
665,284
def _rchild(i): """ Returns the right child node of the given node. """ return 2 * i + 2
63f64c3438501e3f1cb11a53ef43d4b80884f4c8
665,288
def make_list(string): """Make a list of floats out of a string after removing unwanted chars.""" l1 = string.strip('[] \n') l2 = l1.split(',') return [float(c.strip()) for c in l2]
acdf9342b8147a6db2ff316eaecf8c83f261b9b4
665,289
def vcross(self, labxr="", labyr="", labzr="", labx1="", laby1="", labz1="", labx2="", laby2="", labz2="", **kwargs): """Forms element table items from the cross product of two vectors. APDL Command: VCROSS Parameters ---------- labxr, labyr, labzr Label assigned to X, Y, and Z-...
ed40fd87eebfae617c1a3406b07d0ec7261c83e5
665,295
def get_last_lines_from_file(file_localtion, x=50): """ returns an array of the last x lines of a file """ with open(file_localtion, "r") as the_file: lines = the_file.readlines() last_lines = lines[-x:] return last_lines
40c4ef64d9aac05299f9543d160ff6f57dfc609c
665,297
def memoized_triple_step(step): """Find number of step combinations for maximum of three steps at a time :param step Number of steps left :return Number of step combinations """ if step < 0: return 0 elif step == 0: return 1 return memoized_triple_step(step - 3) + \ ...
bf1ef8fba952a73ce9160fc123d5cb4b263866a3
665,300
def get_action(mod_line): """Function to return the type of action requested by the user for a given module, using the pavilion configuration syntax. The string can be in one of three formats: 1) '[mod-name]' - The module 'mod-name' is to be loaded. 2) '[old-mod-name]->[mod-name]' - The...
170471eee01d3b974a9bf50785dfaa0d4bd44083
665,304
def qualified_name_tuple(cls): """ Get the module name and the thing-name for a class. e.g. ('instakit.processors.halftone', 'FloydSteinberg') """ mod_name = getattr(cls, '__module__') cls_name = getattr(cls, '__qualname__', getattr(cls, '__name__')) return mod_name, cls_name
2726dbe46db342193aca4f33c4164be57abe97fd
665,309
def recursive_node_count(sll): """Solution to exercise R-7.3. Describe a recursive algorithm that counts the number of nodes in a singly linked list. """ def recurse(node, count): if node is None: # Base case, found tail of linked list return count return recurse(node....
ac26733203639c1be575dc8a739504dad9a7f041
665,310
def with_lock(lock, fn): """ Call fn with lock acquired. Guarantee that lock is released upon the return of fn. Returns the value returned by fn, or raises the exception raised by fn. (Lock can actually be anything responding to acquire() and release().) """ lock.acquire() try...
d8ed4c4a933483ac0aa5291c815b8afa64ca3957
665,311
def dailyLow (lowTemps, date): """Finds the low temperature for date in question. .. warning: Assumes date has been validated using dateValidation and that data exists for date in question using dataAvailable. :param list lowTemps: Low temperatures for given month :param date: Date (Mo...
78db75edc2af96b8bb80b344ed6f04f83506e1f9
665,312
def byte_to_gb(byte): """Convert bytes to GB""" return byte / (1024.0 * 1024 * 1024)
7bfd1dd1bcd2808e7189af185baa93d36774c6e2
665,313
def accesskey(request): """Get the accesskey from command line. Arguments: request: Gives access to the requesting test context. Returns: A accesskey from command line. """ return request.config.getoption("--accesskey")
aebf5c58fdfc9b279d6d1662fe25eee46abafa18
665,316
def b2b_ipv4_devices(b2b_raw_config, tx_port, rx_port): """Returns a list of ipv4 tx device and rx device objects Each device object is ipv4, ethernet and vlan """ tx_device, rx_device = b2b_raw_config.devices.device().device() tx_device.name, rx_device.name = "Tx Devices Ipv4", "Rx Devices Ipv4" ...
48d4629c519a7881bd3226ff472a8e3cde870aa9
665,319
from typing import Dict def timestamp_as_number_formatter(row: Dict, field: str): """ Useful for JQGrids where we want to send down time as a timestamp so we can put it in the user's timezone :param row: JQGrid row object :param field: field to access row (row[field] should be a timestamp) :return...
1a27356aef164959d64cd6195fbf606a6f62b6c4
665,321
def safe_union_two_by_name(df1, df2): """Combine common fields from two dataframes rowwise. Note we do not use the ``pyspark.sql.DataFrame.unionByName`` function here because we explicitly reorder columns to the order of ``take``. Parameters ---------- df1 : pyspark.sql.DataFrame f...
82a341c995c9158010d1576b2e2c4c6faadfe606
665,324
def filter_labels_by_occlusion(obj_labels, occlusion): """Filters object labels by truncation. Args: obj_labels: List of object labels occlusion: Maximum occlusion Returns: obj_labels: List of filtered labels occ_mask: Mask of labels to keep """ occ_mask = [obj_labe...
8cf7493030a6541b9045fb11ffba4a56ef0daeae
665,332
def _mpi_command(nprocs, mpi_exec): """ Generate a string for shell execution of MPI. If the number of processors is 1 or the executable path is empty, the returned value is simply an empty string. Args: nprocs (int): Number of processors to use. mpi_exec (str): Path to MPI executable. ...
17e0b265e5a265a90d8a112ffe635e7b2a4fc6cd
665,339
def get_dimensions(partitioning_config): """Retrieve the list of partition dimension names. Args: partitioning_config (dict): Dictionary of partitioning variables. Returns: List of dimensions. """ dimensions_dict = partitioning_config.get("dimensions") dimensions = [] types...
27cc326359194b4351bc31156e920c59bb65ce74
665,342
def _safe_conversion(value, converter, default=None): """Pipes a value through a converter function and returns the converted value or the default value if there was an exception during the conversion. Args: value: the value to convert converter (callable): a callable that converts the valu...
97891a0d7f1d68772428dc981d28405ceb161d08
665,347
import torch def l1_normalize(x: torch.Tensor, eps: float = 1e-12) -> torch.Tensor: """Normalizes the input tensor using L1-norm. Args: x: Tensor to be normalized. eps: Small value to avoid division by zero. Returns: Normalized tensor. """ return x / (torch.norm(x, p=1, ...
a084e9776cb1b568474ebbc2211d0926269f3c94
665,349
def _estimate_crosscovar(cweights, proppts, mean, sigpts, mpred): """See BFaS; p.88. Parameters ---------- cweights: np.ndarray, shape (2*dimension + 1,) Constant kernels weights for unscented transform. sigpts: np.ndarray, shape (2*dimension + 1, dimension) Sigma points mpred: ...
ab1db3cbdd59ae58458be6dc12d5c6e4d114d035
665,350
def _matplotlib_list(interval_list): """ Returns lists for matplotlib ``fill`` command from a list of bounding rectangular intervals """ xlist = [] ylist = [] if len(interval_list): for intervals in interval_list: intervalx = intervals[0] intervaly = intervals...
ae4be41634cdb2910c168cd4b6ec10433308c898
665,353
def fp_boyer_freqs(ups_r, ups_theta, ups_phi, gamma, aa, slr, ecc, x, M=1): """ Boyer frequency calculation Parameters: ups_r (float): radial frequency ups_theta (float): theta frequency ups_phi (float): phi frequency gamma (float): time frequency aa (float): spin pa...
0c2e0ad84b0bf0211b7e7fdade0b42b05d391940
665,356
def float_eq( a, b, err=1e-08): """ Check if floats a and b are equal within tolerance err @return boolean """ return abs(a - b) <= err
d30b6b3cbd04bd351e1d28774d2cb0d20733c19b
665,357
def _make_type (vendor, field): """ Takes an NXM vendor and field and returns the whole type field """ return (vendor << 7) | field
1ed42367e1ca4b8dcbba22f54195e99dba0e6d62
665,358
def naming_convention(dic, convert): """ Convert a nested dictionary from one convention to another. Args: dic (dict): dictionary (nested or not) to be converted. convert (func): function that takes the string in one convention and returns it in the other one. Ret...
e149528712e7e2fbc63f3ac6d835294ba638192a
665,360
def _check_filter(filter_, stix_obj): """Evaluate a single filter against a single STIX 2.0 object. Args: filter_ (Filter): filter to match against stix_obj: STIX object to apply the filter to Returns: True if the stix_obj matches the filter, False if not. """ # Fo...
737c1184ff59a723f5f5d316d9db500f2bf37235
665,368
def gen_query_filters_mock(mocker): """Mock _apply_general_query_filters""" def return_search_arg( search, *args ): # pylint: disable=missing-docstring,unused-argument return search return mocker.patch( "search.api._apply_general_query_filters", side_effect=return_search_arg ...
bf72f03b19113bd0fbdb8a4b98977ddd16e8a6fb
665,370
def get_etr(etr_t, R_dash_vnt_rtd, V_rtd_SA, V_rtd_RA): """定格条件における補正風量比での熱通過有効度 Args: etr_t(float): 熱交換型換気設備の温度交換効率 R_dash_vnt_rtd(float): 定格条件における補正風量比 V_rtd_SA(float): 定格条件における給気風量 V_rtd_RA(float): 定格条件における還気風量 Returns: float: 定格条件における補正風量比での熱通過有効度 """ # (12) ...
477f326098b4198994ac52ad72b4e5485a600b04
665,372
def botcommand(*names): """Mark function as command. (for extensions) Parameters ---------- *names : str Name/s to invoke the command. Default: name of function. """ def decorator(func): command_names = names if names != () else func.__name__ func.command...
a8e1821daa717e4ee0327ae8a857bd1b1475cb5a
665,373
def _return_slave(index, parsed_args): """Gives the slave index name.""" return index + parsed_args.suffix
c4780221a21c6f5d24d92381bee5310adab40b34
665,378
def arch_sampling_str_to_dict(sampling_str): """ Converts string representations of architecutre sampling methodology to the dictionary format that nas_searchmanager.SearchManager uses. Example: \"1:4,2:4,3:4,4:4\" is converted to {1.0 : 4, 2.0 : 4, 3.0 : 4, 4.0 : 4}. """ # Remove ...
a17bccbfccc18271df0972838a7ae90940acd059
665,384
def find_max_weight(regions): """Find the maximal weight in the given regions""" mw = 0 for r in regions: mw = max(mw, r.profEntry.weight) return mw
7c08f3334d1ec42400509df120dde95a1a05e26d
665,386
import pathlib import json def load_fixture(name: str): """Load a fixture from disk.""" path = pathlib.Path(__file__).parent / "fixtures" / name content = path.read_text() if name.endswith(".json"): return json.loads(content) return content
dfcaef65a7173037a557e45cc373e9963a7e4191
665,387
from typing import List import random def get_quote_funfact(text_list: List[str]) -> str: """ Utility to get random text from given list. """ return random.choice(text_list)
1b2563f28603dcce799e6eb52f4421758fd1aecf
665,389
def float_approximates(float_a, float_b, error=1e-6): """Returns whether float a is approximately b within error tolerance""" return abs(float_a-float_b) < error
4cd4f7a8fc90376c2e1dd5af6f122ce2b4cb1f43
665,390
def crop(x, area): """ * inputs: - x (torch.Tensor, required) A torch tensor of shape (N, C, H, W) is assumed. - area (sequence, required) A sequence of length 2 ((X, Y), (W, H)) is assumed. sequence[0] (X, Y) is the left corner of an area to be cr...
822b51b53744f0f6004343f67bf1624449a06ada
665,393
def seqs_from_dict(seqs, Alphabet=None): """SequenceCollection from dict of {label:seq_as_str}. This is an InputHandler for SequenceCollection. It converts a dict in which the keys are the names and the values are the sequences (sequence only, no whitespace or other formatting) into a SequenceC...
3b4fa34f83f66c023c7337d7ee127cca9d3d93c8
665,394
import torch def one_hot_embedding(labels, num_classes): """ 将标签嵌入成one-hot形式 :param labels: 标签,(LongTensor)类别标签,形状[N,] :param num_classes: 类别数, :return:(tensor)被编码的标签,形状(N,类别数) """ # 返回2维张量,对角线全是1,其余全是0 y = torch.eye(num_classes) return y[labels]
35d9b0e3afb9dc76291922b984b99ebc75bb0c90
665,395
def get_type(string): """Returns type of debit/credit card according to first number of card number""" initial_digit = string[0] card_type = { "3": "American Express", "4": "Visa", "5": "MasterCard", "6": "Discover Card"} if initial_digit not in list(card_type.keys()): ...
795422d2e2f77ce93008ce028d4fa91eca3e9456
665,399
from typing import Tuple def size2shape(size: int) -> Tuple[int, int]: """convert a plate size (number of wells) to shape (y, x)""" assert size in [384, 1536] return (16, 24) if size == 384 else (32, 48)
81795acc3992ff0d1b8b39997e8d60b19ea43db0
665,401
from datetime import datetime def prepend_timestamp(line): """Add ISO 8601 timestamp to line""" timestamp = datetime.now().replace(microsecond=0).isoformat() return "{} {}".format(timestamp, line)
926573337579084b67593204b5bb99171ab96b7c
665,403
def my_function(a: int, b: int) -> int: """Add two numbers together Parameters ---------- a: int first integer b: int second integer Raises ------ value errror if a == 0 Examples -------- >>> my_function(1, 2) 3 >>> my_function(0, 2) Tracebac...
d9ca51d57421569073268aad51c8f3a94f4a5dc8
665,405
from bs4 import BeautifulSoup import re def get_links(html_page, base_url): """gets all links from html Parameters ------ html_page (str): document html base_url (str): the original URL supplied Returns ------ list: list of all the links in the html document these could be fi...
f2e97ce2934e994787f3ef79d43558f3380c6722
665,409
def sizeof_fmt(num: int, suffix: str = "o") -> str: """ Human readable version of file size. Supports: - all currently known binary prefixes (https://en.wikipedia.org/wiki/Binary_prefix) - negative and positive numbers - numbers larger than 1,000 Yobibytes - arbitrary units ...
1b1f796637da484e6d1e3a51011782f6b4278bf1
665,410
def _get_total_citation_by_year(l, max_year=2015): """ Calculate the total citation by year :param l: list of (year, citation) tuple :param max_year: the maximal year :return: dict with the totatl number of citation in each year """ min_year = int(min([y for y, v in l])) total_citations...
84f114e0296d7ff3d83dcf2402153cdfc7787fc7
665,411
def _get_env_var(repository_ctx, name): """Find an environment variable.""" if name in repository_ctx.os.environ: return repository_ctx.os.environ[name] else: return None
8cd7567ba5eb1859bf596ff9966f23db1d376fd5
665,416
def prep_phrase(args, premise, verbose=True): """Check whether there is prepositional phrase in premise.""" # Collect prepositions preps = [t for t in premise.tokens if t.deprel == 'prep'] if preps: return True else: return False
c7d0c2dee424b84a2d035dd3df2f4edf8e36a675
665,419
def path_crawler(hm, path=['A'], paths=[]): """Given a matrix, return a list of all available paths It works similarly to Depth-First Search. Starting from a root element, it recursively iterates down a single path until it reaches the terminal. It returns the given path, and works its way back up...
279485737a5732f09ff164460cf6dde7b7ce5741
665,420
def get_fibonacci_sequence(length: int) -> list: """Return the fibonacci sequence to the specified length.""" fibonacci_sequence = [0, 1] if length == 1: return [fibonacci_sequence[0], ] elif length == 2: return fibonacci_sequence for _ in range(0, length - 2): second_to_las...
f324d2d848bf1b20f054e7b3dd1aeb450d1198f9
665,421
import re def edit_code(row, oc4ids_codes, source): """ If the row's "Code" is in the ``oc4ids_codes`` list, adds " or project" after "contracting process" in the row's "Description" and sets the row's "Source" to ``"OC4IDS"``. Otherwise, sets the row's "Source" to ``source``. """ if row['Code'] i...
643669c6a16e1e4f938ed142660fe98d063d1ba0
665,422
def coalesce(*args): """Return the first argument which is not None. If all arguments are None, return None.""" for a in args: if a is not None: return a return None
52ed39ff37c704579a157ef78b8330c384473c15
665,425
def get_hyphen_exp(text: str, nlp): """ Returns a list of all hyphen expressions contained in the text :param text: string :param nlp: spacy language model :return: list of hyphen expressions contained in text """ doc = nlp(text) token_list = [token.text for token in doc] hyphen_exp...
d80bc04a0cc47b5ebe4fdd8d318f607e0c353a55
665,427
def build_response_card(title, subtitle, options): """ Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons. """ buttons = None if len(options) > 1: buttons = [] for i in range(min(5, len(options))): buttons.appe...
eaa86530b88bc6340940576d5dbb8369740ccbef
665,432
def sum_fuel_enduse_sectors(data_enduses, enduses): """Aggregate fuel for all sectors according to enduse Arguments -------- data_enduses : dict Fuel per enduse enduses : list Enduses nr_fueltypes : int Number of fuetlypes Returns ------- aggregated_fuel_end...
d25b16f4cde787793eb3d4bfaad5698e62bc20be
665,435
def split_url(url): """split a zmq url (tcp://ip:port) into ('tcp','ip','port').""" proto_addr = url.split('://') assert len(proto_addr) == 2, 'Invalid url: %r'%url proto, addr = proto_addr lis = addr.split(':') assert len(lis) == 2, 'Invalid url: %r'%url addr,s_port = lis return proto,a...
0ebba51995517a0c0efc818ea8280be1b1f05591
665,437
def get_A_f(A_HCZ, r_Af): """敷設面積 Args: A_HCZ(float): 暖冷房区画の床面積 (m2) r_Af(float): 床暖房パネルの敷設率 Returns: float: 敷設面積 """ return A_HCZ * r_Af
07f95b2ef3f4aab9c8f441bd21eec7e388e21ca2
665,438
def is_topk_evaluator(evaluator_keys): """Are these evaluator keys from TopK evaluator?""" return (len(evaluator_keys) == 5 and evaluator_keys[0] == 'top_1' and evaluator_keys[1] == 'top_2' and evaluator_keys[2] == 'top_3' and evaluator_keys[3] == 'top_4' and evalua...
77b0d446118497bb1cb7be6c559f3193722eaf9c
665,439
def get_dataset_mean_std(kind): """Get mean and std of a dataset for normalization.""" if kind == "epic": mean = [0.412773, 0.316411, 0.278039] std = [0.222826, 0.215075, 0.202924] elif kind == "gtea": mean = [0.555380, 0.430436, 0.183021] std = [0.132028, 0.139590, 0.123337]...
e947a3776e473b36a349181c9c94d8c485492644
665,442
def check_for_take(string: str) -> bool: """ Helper Function that checks to see if clapperboard elements follows set of rules to be identified as a "take" element Parameters ---------- string: String (The string thay will be checked Returns ------- Boolean True if ...
2b86829a8d1a05bcc72b1766e39bac6f7a832080
665,444
import ast def parse_source_file(filename): """Parse source file into AST node Parameters ---------- filename : str File path Returns ------- node : AST node content : utf-8 encoded string """ # can't use codecs.open(filename, 'r', 'utf-8') here b/c ast doesn't ...
8064b132c055d0d9c7663333836b006e35f5de82
665,445
def fibonacci(n): """Returns n fibonacci numbers Args: n: number of fibonacci numbers to return Returns: List that contains n fibonacci numbers Raises: ValueError when n is not a positive integer """ if n < 1: raise ValueError("n must be a posit...
ef8e26e63327a3fce20bd36f3d14bc9902cb44b8
665,449
def to_tuple(d): """ Expects dict with single key, returns tuple. >>> to_tuple({'a': 1}) ('a', 1) """ return next(iter(d.items()))
a30ee0db94179e125dab96ab8efa38e28456c343
665,450
def slice_list(list_a: list, start: int, end: int): """Problem 18: Extract a slice from list. Parameters ---------- list_a : list The input list start : int The start of the slice end : int The end of the slice Returns ------- list A slice of the ini...
853088bb218666771e6024953e9956524b139443
665,452
def merge(d1, d2): """Merges d2 into d1 without overwriting keys.""" left = d1.copy() right = d2.copy() for key in right.keys(): if key in left: left_is_dict = isinstance(left[key], dict) right_is_dict = isinstance(right[key], dict) if left_is_dict and right...
568254522547b47687cdfaab54bfc21e0b535f93
665,456
def multiply(value, multiplier): """ Multiplies two values together. Usage: >>> multiply(5, 2) 10 """ return value * multiplier
bbc055bcc91b3ec82f5e9a7f3e5dcda3d8db0bab
665,460
def provider2network(provider): """ Convert a MADIS network ID to one that I use, here in IEM land""" if provider in ['KYMN']: return provider if provider == 'MesoWest': return 'VTWAC' if len(provider) == 5 or provider in ['KYTC-RWIS', 'NEDOR']: if provider[:2] == 'IA': ...
71374cda7b66c043d3993f878644602db2e5c5ae
665,462
def match_code(code:str, raw_line:bytes)->bool: """returns True if code is met at the beginning of the line.""" line = raw_line.decode("ascii") return line.startswith(code + " ") or line.startswith(code + ";")
88b10075e302d9d9bb1db591fead4f8db2829c40
665,464
def get_linked_info(issue): """ for the given issue, if "[Dd]uplicates: <org>/<repo>#XXX exists in PR body, returns the parsed org/repo/number Else return None """ body = issue["body"].lower() if "\nduplicates" in body: _, url_string = body.split("\nduplicates ") next_newlin...
b883482b52f226c591c1d623daaa2472f98245c8
665,465