content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import logging def validatePid(pid, patientDict, hrDict): """ Validates patient id input for checking tachycardic :returns: -1 if not successful, 1 if successful """ if(not isinstance(pid, type(""))): logging.error("didn't pass in string") return -1 if pid not in patientDict.k...
e6e8fa7a5e6902fe0de81f9e08651f1ef435d524
688,674
def compute_proportion(data, target_column, resize=None): """ :param data: pd.DataFrame indexed by [spatial_index, temporal_index] :param target_column: The target value of interest :param resize: if None, there is no resizing, and the proportion sum to one , otherwise to resize to sum the proportion...
6816b1f3fed180e37d5f94a101fcaf18cd499f02
688,675
def commutator(expr1, expr2): """Returns [expr1, expr2] = expr1 * expr2 - expr2 * expr1. Args: | expr1 (Expr, Term or Pauli operator): Pauli's expression. | expr2 (Expr, Term or Pauli operator): Pauli's expression. Returns: Expr: expr1 * expr2 - expr2 * expr1. """ expr1 = e...
38a847059968e4651f7df0cd17b5d45525f369c5
688,676
def _format_time(time_us): """Defines how to format time in FunctionEvent""" US_IN_SECOND = 1000.0 * 1000.0 US_IN_MS = 1000.0 if time_us >= US_IN_SECOND: return '{:.3f}s'.format(time_us / US_IN_SECOND) if time_us >= US_IN_MS: return '{:.3f}ms'.format(time_us / US_IN_MS) return '{...
c57feca13b599b0fdd99f34b615ce19b8ea49e60
688,677
def product_turnover(units_sold_in_period, average_items_stocked_in_period): """Return the product turnover (or sell through rate) for a product based on units sold versus items stocked. Args: units_sold_in_period (int): Number of units of product X sold in the period. average_items_stocked_in_...
4603628db9cfbc7558d4838015faa22b3b2cee86
688,678
def within_n_sds(n, series): """Return true if all values in sequence are within n SDs""" z_score = (series - series.mean()) / series.std() return (z_score.abs() <= n).all()
cb48dc5f6c33a9f7c574ae5a2eb7113bc1c8b94c
688,679
def fib_n_efficient(n): """Efficient way to compute Fibonacci's numbers. Complexity = O(n)""" a = 0 b = 1 for i in range(n - 1): c = a + b a = b b = c print(b) return b
c203681738d1ba71eff91920194f1a8bf5d4258a
688,680
def set_default_crud_kwargs(method): """ Set default crud operation kwargs""" kwargs = {} if method in ['show', 'update', 'delete']: kwargs['name'] = 'foo' if method in ['create', 'update']: kwargs['config'] = {'foo': 'bar'} return kwargs
7844104c380242a8394983a5f08599fb4d769f62
688,681
def _get_single_reg(asm_str): """returns a single register from string and check proper formatting (e.g "r5")""" if len(asm_str.split()) > 1: raise SyntaxError('Unexpected separator in reg reference') if not asm_str.lower().startswith('r'): raise SyntaxError('Missing \'r\' character at start...
d01f7e3e9c73ff48ed13386c5aa8c602595fcd39
688,682
def inversion(r, g, b): """ Эффект негатива. :param r: значение канала Red. :param g: значение канала Green. :param b: значение канала Blue. :return: RBG с эффектом негатива. """ return 255 - r, 255 - g, 255 - b
bbee4e6cce98439f05c17029eb5e0442900ad8eb
688,683
def GaussQuadRule(i): """ We need no modification for Gauss rules, as we don't expect them to be nested. @ In, i, int, level desired @ Out, i, int, desired quad order """ return i
238644f2370fc0ce267afd0f0a989b034a6430f5
688,684
def is_valid_boolean(val): """ Checks if given value is boolean """ values = [True, False] return val in values
0491c1565e96ca7349137eacd4551fb75bed97ee
688,685
def reduce2(f, a): """ My implementation of the reduce() function itself. """ if len(a) == 0: raise ValueError("Reducing an empty list") if len(a) == 1: return a[0] if len(a) == 2: return f(a[0], a[1]) return f(a[0], reduce2(f, a[1:]))
77e564b73ef7caec4d67a74d55bb3935eec5ade8
688,686
def parse(stdin): """Parse "FBFBBFFRLR" to "0101100101", then to (44, 5).""" return [ ( int(line[:7].replace("B", "1").replace("F", "0"), 2), int(line[7:10].replace("R", "1").replace("L", "0"), 2), ) for line in stdin.readlines() ]
4dd860031194a1d9d75bf6356fa0b15564904ce1
688,687
def massage_data(raw_data): """ Preprocess the data for predictions """ raw_data.rename(index=str, columns={"whether he/she donated blood in March 2007": "label"}, inplace=True) # generate features for year for time columns for x, y in zip(['time_years', 'recency_years'], ['Time (months)', 'Recen...
4950d59f628be33b5cf319636faa11c5d5936644
688,688
def process_query(file): """(file open for reading) -> query dictionary precondition: the twitter data file(parameter 'file') is already opening for reading. This function aims to read the twitter data file and then return data in the file to query dictionary format. """ twitter_query_dict ...
bffaed197e1cb8d60130bbaf3a0eb61ecdab7c63
688,689
def test_NN(hist,X_test,y_test): """ Test a NN model with test data set for accuracy hist: A History object generated by the Keras model fitting process """ score=hist.model.evaluate(X_test, y_test,verbose=0)[1] return score
9136b77af6196a891dd8adb51a33806edc4dbda1
688,690
def parse_number(string, numwords=None): """ Parse the given string to an integer. This supports pure numerals with or without ',' as a separator between digets. Other supported formats include literal numbers like 'four' and mixed numerals and literals like '24 thousand'. :return: (skip, value...
6a517205cf3d7b3c52678189dc3ffa91501cf1a4
688,692
def extract_size(hdfs, name): """ Extract size of a HDFS file. :param hdfs: :param name: :return: """ file_size = hdfs.get_file_status(name)['length'] return file_size
a2eefce2df74a99ce1e588cff8073cd37d7c857c
688,693
import numpy def unison_shuffled_copies(a, b): """Shuffles a dataset with corresponding labels Returns: shuffled trainX and trainY """ assert len(a) == len(b) p = numpy.random.permutation(len(a)) return a[p], b[p]
d2c7e07e362122ad6757fee4b9cb162d04c975e9
688,694
def remove_multiedges(E): """Returns ``(s, d, w)`` with unique ``(s, d)`` values and `w` minimized. :param E: a set of edges :type E: [(int, int, float)] :return: a subset of edges `E` :rtype: [(int, int, float), ...] """ result = [] exclusion = set() for...
e6156259ee8f5714bfef0fab8a92aed117c6149c
688,695
import copy def _deepcopy(config): """When using YAML anchors, parts of configurations are just references to an other part. CLG parameters (like the 'short' parameter of an option or the title of a group) are deleted from the current configuration, so theses informations are lost in parts of configur...
d26417abc1b37f328ef307e2b72248c61350767b
688,697
import re import numpy def _read_zone(f, variable_names): """Read ZONE data from a Tecplot file. """ zone = {} print("Reading zone header...") line = f.readline() while line: # zone_header and line: # Read the zone header. # Break up the line at commas and read individually. ...
dd750b35b733bb0a75dd94c85e07ba107004a0ee
688,698
import six import importlib def load_class(requested_class): """ Check if requested_class is a string, if so attempt to load class from module, otherwise return requested_class as is """ if isinstance(requested_class, six.string_types): module_name, class_name = requested_class.rsplit(".",...
ae3c212d84b0cbe409babfc2f77e7c6b2dc62b12
688,699
def parse_floats(s): """parse_floats :param s: """ if isinstance(s, str): if "/" in s: # parse a ratio to its float value num, den = s.split("/") return [float(num) / float(den)] elif "," in s: # parse a csv variable into multiple new colu...
a4b6eb7e52fae0895059fe0a2fbf9532e9949286
688,700
def normalize_text(text): """ Standardize text so that curly apostrophes and normal apostrophes have the same representation and html entities match their representations """ pass symbol_replace = { "&amp;": "&", "&quot;": '"', "&apos;": "'", "&#8217;": "'...
82a121aba82559695387fcfb65ad6b401a1666e5
688,701
def convert_code(code): """指数代码小写转大写""" if code.endswith('sh'): return code[0:6] + '.SH' elif code.endswith('sz'): return code[0:6] + '.SZ' else: return code
75a4cd4025840bf7a2175425dbdd00b05b8150fd
688,702
def calc_tristimulus_array_length(data_array): """ calcurate the array length of tristimulus ndarray. Parameters ---------- data_array : ndarray tristimulus values Returns ------- int length of the tristimulus array. Examples -------- >>> data_1 = np.ones((...
a301bb3e0f048fdc62c73f45a5b764f948ad0f0c
688,703
def extend_position_embedding(model, max_position): """This function extends the position embedding weights of a model loaded from a checkpoint. It assumes the new max position is bigger than the original max length. Arguments: model: required: a transformer model max_position: required: an...
ed9ca2979295ee8b2c219655e63de362108066e6
688,704
def ascii6_to_bin(data) -> str: """ Convert ASCII into 6 bit binary. :param data: ASCII text :return: a binary string of 0's and 1's, e.g. 011100 011111 100001 """ binary_string = '' for c in data: if c < 0x30 or c > 0x77 or 0x57 < c < 0x60: print("Invalid char") ...
b48efe9a67b0f22c93637e87a3f5e99b676dfcac
688,705
from typing import Mapping from typing import Any from typing import Optional from typing import Dict def _parse_runtime_parameters( runtime_config_spec: Mapping[str, Any] ) -> Optional[Dict[str, Any]]: """Extracts runtime parameters from runtime config json spec. Raises: TypeError: if the parame...
8ae93c9934226bbf409f3db600f2de529e079bf2
688,706
def formFeed(): """ Form feed go to next page """ return b'\x0C'
3f5fe6c2a05a1041b24eeef19b9241988c58b8a1
688,707
import json def read_user_ips(file): """Read in the JSON file of the user-IP address mapping.""" with open(file, 'r') as file: return json.loads(file.read())
a00171d82edc59bbea902e6bd356543093d1a05e
688,708
import re def get_read_group(list_of_names): """Extracts the correct group name for the group containing the read_id""" for name in list_of_names: if re.search(r'Read_\d+$', name): return name
44f8aa6ddd05f03760a114dcb911063033e3e5d8
688,709
def version(): """ Return the current version string for the vampyre package. >>> version() '0.0' """ return "0.0"
d8415f18f9b129f5700756cbdce8d9b81526328a
688,710
def word_value(word): """ Compute the value of word """ return sum([ord(c) - ord('A') + 1 for c in word])
44199b8b18a0bd38670141e0a7752cff1f4bede6
688,711
def reloc_exit_patch(patch_data, relocs, start_address): """Relocate a piece of 6502 code to a given starting address.""" patch_data = bytearray(patch_data) for i in relocs: address = patch_data[i] + (patch_data[i + 1] << 8) + start_address patch_data[i] = address & 0xFF patch_data[i...
24ef61eeb5db23c41e4cea99e47826462775551c
688,713
def fingerprints_as_string(fingerprints): """ Method to formatting fingerprints list to human readable string value :param fingerprints: fingerprints set as list :type fingerprints: list :return: fingerprints set as string :rtype: str """ all_fingerprints_string = [] # loop all fin...
1ed23026b4a930110a86fc2922543f62794e4427
688,715
import math def haversine(lat1,lon1,lat2,lon2,radius=6371000.0): """ Haversine function, used to calculate the distance between two points on the surface of a sphere. Good approximation for distances between two points on the surface of the Earth if the correct local curvature is used and the points are ...
58125250e0d1a01bcc7a48e2d2a015e4610ed7be
688,716
def get_coords_from_line(line): """ Extracts atom coordinates from a PDB line based on chain ID, residue number and PDB atom name. Input line: str - PDB line Output string of coordinates extracted from the PDB line """ return line[30:54].split()
5ea7d6857693ea18bd1621774d013e570a03fbd2
688,717
from pathlib import Path def get_version(): """Parse package __version__.py to get version.""" versionpy = (Path('detect_secrets') / '__version__.py').read_text() return versionpy.split("'")[1]
422775601c12657e1a3f3a28066664e2badcd0f5
688,718
def no_blending(rgba, norm_intensities): """Just returns the intensities. Use in hill_shade to just view the calculated intensities""" assert norm_intensities.ndim == 2, "norm_intensities must be 2 dimensional" return norm_intensities
350c2f8c235de6552165f4eb482aee1600fcabdf
688,719
import os def resolve(path): """ Returns path string with user/tilde and environmental variables converted """ return os.path.expandvars(os.path.expanduser(path))
2665c39413e59c962f2dfa044816611bc6194b29
688,720
import sys def exit_failure(msg, status=1): """Write a message in stderr and exits :param msg: the msg :type msg: str :param status: exit status (!=0) :type status: int """ sys.stderr.write(msg) sys.stderr.write('\n') return sys.exit(status)
886b23e1cd6e30c09978ab00114b8e3ef220c548
688,721
def feature_fixture(request): """Return an entity wrapper from given fixture name.""" return request.getfixturevalue(request.param)
2f5b9164e34a9efc2a80ecea36cff226d04b5b7a
688,722
def absolute_value(num: int): """ This function returns the absoluate value of the provided number """ if num >= 0: return num return -num
0711239c1e6523934ad46deb50dfb802dae7f8a2
688,723
import os def get_temporalROI(roi_dir_path): """ 获取检测帧的范围 :param roi_dir_path: dataset/baseline/baseline/highway :return:['470', '1700'] [起始帧,结束帧] """ roi_path = os.path.join(roi_dir_path, 'temporalROI.txt') with open(roi_path, 'r') as f: avail_frames = f.read() return avail_f...
71a4ad1ea8f62788ae89044ae39f8b0296eb7758
688,724
def _filter_cols(dataset, seed): """Mapping function. Filter columns for batch. Args: dataset: tf.data.Dataset with several columns. seed: int Returns: dataset: tf.data.Dataset with two columns (X, Y). """ col_y = f'image/sim_{seed}_y/value' return dataset['image/encoded'], dataset[col_y]
29831bbd4231d35cd666e45350140d7b763f47ea
688,726
def shorten_text(text: str) -> str: """ Truncate the text if there are over 3 lines or 300 characters, or if it is a single word. The maximum length of the string would be 303 characters across 3 lines at maximum. """ original_length = len(text) # Truncate text to a maximum of 300 characters ...
37c79d3c0d309b0ddffe9099d0911df32753fccb
688,727
def extract_results(file_path): """ Extract the Java/Python dependency reports and return a collection of out-of-date dependencies. Args: file_path: the path of the raw reports Return: outdated_deps: a collection of dependencies that has updates """ outdated_deps = [] try: with open(file_path)...
4dddfa1e790b4403f49b006e3c26574c5bdce5b2
688,728
def find_sum(inputs, target): """ given a list of input integers, find the (first) two numbers which sum to the given target, and return them as a 2-tuple. Return None if the sum could not be made. """ for i in inputs: if i < target // 2 + 1: if target - i in inputs: ...
8961cb6dd02ef65afa14c1ac46280055960ed6a0
688,729
from typing import Type def concretize_abstract_wrangler(abstract_class: Type) -> Type: """Makes abstract wrangler classes instantiable for testing purposes by implementing abstract methods of `BaseWrangler`. Parameters ---------- abstract_class: Type Class object to inherit from while ov...
1bd2f3a2016d4ad51b2d0d87fc1746a5b90a9314
688,730
import os import time import re def update_filename(filename, add_date=True): """Update the file number and date.""" basename, _ = os.path.splitext(filename) dirname = os.path.dirname(os.path.abspath(filename)) if add_date: date = time.strftime("%y%m%d") dirname = os.path.join(d...
5b10afeb8072f17295586978b82789dac87ca635
688,731
import inspect def is_static_method(klass, name: str) -> bool: """ Check if the attribute of the passed `klass` is a `@staticmethod`. Arguments: klass: Class object or instance to check for the attribute on. name: Name of the attribute to check for. Returns: `True` if the...
5ee84883d6ad52b6c0dd69f7123f80fd553313ea
688,732
def get_longest_jobs(db): """ :param db: a :class:`openquake.server.dbapi.Db` instance :returns: (id, user_name, days) tuples """ query = '''-- completed jobs taking more than one hour SELECT id, user_name, julianday(stop_time) - julianday(start_time) AS days FROM job WHERE status='c...
ae83b10c929d413558223c6917eb4b01389f61ad
688,734
def verify_readahead(readaheadkb): """ :type readaheadkb: str :param readaheadkb: Readahead KB to check :rtype: str :return: readahread :raises: ValueError: Invalid input """ if readaheadkb not in ['16', '64', '128', '256', '512']: raise ValueError('"{0}" is not a valid readahe...
79c45cd688c07a7f2b9cc2d5380c279c955919bb
688,735
import os def terminal_size(): """ Gets the Height and with of the Terminal. :return: Tuple of a Integer and Integer """ return os.get_terminal_size()
a07d81a8bd231dccbde00ebba363efe4b6481f25
688,736
from typing import Union def astuple(i, argname: Union[str, None]) -> tuple: """ Converts iterables (except strings) into a tuple. :param argname: If string, it's used in the exception raised when `i` not an iterable. If `None`, wraps non-iterables in a single-item tuple, and no exception...
6bf251b32223e80400e24f3658daebb0872159e2
688,737
def maze_as_array( m: int, n: int, floors: set[tuple[int, int]], ) -> list[list[bool]]: """Generates and returns maze in matrix form""" matrix = [] for y in range(n): row = [] for x in range(m): tile = True if (x, y) in floors else False row.ap...
5233ea52bcb377af54d3b40463cc8893fc29e753
688,738
def ms_to_hours(ms): """Convert milliseconds to hours""" return round(ms / 60.0 / 60.0 / 1000.0, 2)
0df04200eb35e44fbbc3050a61de8ac00e67d89e
688,739
def org_add_payload(org_default_payload): """Provide an organization payload for adding a member.""" add_payload = org_default_payload add_payload["action"] = "member_added" return add_payload
37def98da4c7fe3389177f3ef65ac1dc146def23
688,741
import re import unicodedata def strip_diacritics(input_string: str) -> str: """Return a copy of `input_string` without diacritics, such that strip_diacritics('skříň') == 'skrin' """ trans_dict = {} for char in input_string: if ord(char) < 0x80: continue match_lett...
b12c9e0f2e8a3101ecef3a711b455c0625289dcb
688,742
def test_cards(): """ Mastercard test cards """ return [ # Auth.Net test cards "5424000000000015", # Braintree test cards, "5555555555554444", "5105105105105100", # Stripe test cards "5555555555554444", "5200828282828210", "51051051...
191fcb818727a3fc7d869b0529f9069145ac00a8
688,743
def round(number, ndigits=None): """Round a number to a given precision in decimal digits (default 0 digits). :type number: object :type ndigits: numbers.Integral | None :rtype: float """ return 0.0
24a22c80d3f1c43ab1a04090f870b1126863931f
688,744
def load_rte(file_path, kwargs: dict = {}): """ Load RTE """ header = kwargs.get("header", True) is_train = kwargs.get("is_train", True) rows = [] cnt = 0 with open(file_path, encoding="utf8") as f: for line in f: if header: header = False con...
e14f4140db863273b65cebe7c26a668fb5a4ffac
688,745
import os def gfz_version(): """ return string with location of gfzrnx executable """ exedir = os.environ['EXE'] gfzv = exedir + '/gfzrnx' # heroku version should be in the main area if not os.path.exists(gfzv): gfzv = './gfzrnx' return gfzv
d10ddd8a7246a594e31e8885dfd40bd1cf7dbd1b
688,746
def cchunkify(lines, lang='', limit=2000): """ Creates code block chunks from the given lines. Parameters ---------- lines : `list` of `str` Lines of text to be chunkified. lang : `str`, Optional Language prefix of the code-block. limit : `int`, Optional The maxi...
68db7bfa9e781240ddde86dba559f1da84112ee8
688,747
def exist_unchecked_leafs(G): """Helper function for hierachical hill climbing. The function determines whether any of the leaf nodes of the graph have the attribute checked set to False. It returns number of leafs for which this is the case. Args: G (nx.DirectedGraph): The directed graph to be...
513fe0f7c1b61ee1063eda82d2b4720434cd7ae3
688,748
def graphicsmethodlist(): """ List available graphics methods. :Example: .. doctest:: queries_gmlist >>> a=vcs.init() >>> vcs.graphicsmethodlist() # Return graphics method list [...] :returns: A list of available grapics methods (i.e., 'boxfill', 'isofill'...
64baa088772999e9f6e0e4f2764e3758f8a53732
688,749
def num_edges(graph): """Returns the number of edges in a ProgramGraph.""" return len(graph.edges)
3ae188a25570fe9b0df1650e011efcfaa5d75080
688,750
def process_license(license): """If license is Creative Common return the zenodo style string else return license as in plan Parameters ---------- license : dict A string defining the license Returns ------- zlicense : dict A modified version of the license...
14a85a50ac194dadfc61388484bedc836a41d67e
688,751
def labels_to_int(labels): """Heuristic to convert label to numeric value. Parses leading numbers in label tags such as 1_worried -> 1. If any conversion fails this function will return None """ label_vals = [] for label in labels: if label == 'positive': label_vals.append(1) ...
408fd3efa23d5fbac85a307b680f68f551ff171d
688,752
def py3to2_imported_local_modules(content, unittest_modules): """ See function @see fn py3to2_convert_tree and documentation about parameter *unittest_modules*. @param content script or filename @param unittest_modules modules used during unit test but not installed, ...
ca387b9a97291d392fc599fa2ab53a520f6e2f34
688,753
def is_subset(hint, target): """Is subset""" h = set(hint) t = set(target) return h.issubset(t)
3efe8ebd8c585b4e6382b2705b7ee9b7ddce5644
688,754
def altz_to_utctz_str(altz: float) -> str: """As above, but inverses the operation, returning a string that can be used in commit objects""" utci = -1 * int((float(altz) / 3600) * 100) utcs = str(abs(utci)) utcs = "0" * (4 - len(utcs)) + utcs prefix = (utci < 0 and '-') or '+' return prefix ...
4fef9682f2958e965eabe6bd8e8bdcd82852bad4
688,757
def get_set_color(names, color): """ Returns an NLP search query to color neurons given a list of neurons. # Arguments names (list): List of neurons to color. color (str): Color to use. Refer to the color name list in https://en.wikipedia.org/wiki/Web_colors. # Returns str: NLP quer...
a5a80df0cecb9e6176bb6fbfab1b7dca8f221c69
688,758
import tempfile def simple_net_file(num_output): """Make a simple net prototxt, based on test_net.cpp, returning the name of the (temporary) file.""" f = tempfile.NamedTemporaryFile(mode='w+', delete=False) f.write("""name: 'testnet' force_backward: true layer { type: 'DummyData' name: 'data' top...
6d8107f638b0eff583c19bd691210e119520b4f9
688,759
def generate_level03(): """Generate the bricks.""" pi = [ [44, 27, 4], [70, 27, 4], [31, 33, 4], [44, 33, 4], [57, 33, 0], [70, 33, 4], [83, 33, 4], [44, 39, 0], [57, 39, 0], [70, 39, 0], [31, 45, 0], [44, 45, 0], ...
da3827c735a70d449de78041cda3810608dec590
688,761
import re def has_restriction_sites(seq, dict_restriction): """Former match restrictions. Check if there are any restriction site in the sequences, and if it have, return a list with the positions involved Paramaters ---------- :param seq (str); DNA sequence :param dict_restriction (l...
dfcc5bec40c38ccb4b2c27d74d70161251585f9f
688,762
def _is_pem_section_marker(line): """Returns (begin:bool, end:bool, name:str).""" if line.startswith('-----BEGIN ') and line.endswith('-----'): return True, False, line[11:-5] elif line.startswith('-----END ') and line.endswith('-----'): return False, True, line[9:-5] else: return False, False, ''
7d03b8a9c49068f9343f44a1b44bc4fec587dc2e
688,763
import re def get_fortfloat(key, txt, be_case_sensitive=True): """ Matches a fortran compatible specification of a float behind a defined key in a string. :param key: The key to look for :param txt: The string where to search for the key :param be_case_sensitive: An optional boolean whether to sea...
c0171ab82196f9cffc0b66dfeeb7a766ff73dfe9
688,764
def option_namespace(name): """ArgumentParser options namespace (prefix of all options).""" return name + "-"
0b79edea508216e61afe06750d5fbf7727546932
688,765
def ucfirst(string): """Implementation of ucfirst and \ u in interpolated strings: uppercase the first char of the given string""" return string[0:1].upper() + string[1:]
3e24f63d51da0b09f3d121ec09ab05b650888184
688,766
import os def create_path_decorator(motherPath): """Creates a decorator for the function `create_daughter_path`. The decorator appends the parameter ``motherPath`` to the ``daughterPath`` created by `create_daughter_path`. Furthermore, if ``motherPath`` is a relative path, it turns the resulting path ...
302c679814d54472acf095856647963844ec9c03
688,767
def find_latest_span(text_spans): """Finds the latest occuring span in given set of text_spans Args: text_spans (TextSpan): the span of text according to some document """ if len(text_spans) == 0: return None sorted_spans = sorted(text_spans, key=lambda s: s.end_index, reverse=...
c7464e78180d8f2a52a6676681981cbd95d24be6
688,768
def get_cached_translation(instance): """ Get currently cached translation of the instance. Intended for internal use and third-party modules. User code should use instance.translations.active instead. """ return instance._meta.get_field('_hvad_query').get_cached_value(instance, None)
4edef41ff2f952c5847b4cfbb2d4c1c8b7e65b36
688,769
import os def current_user() -> str: """Returns current user name""" try: # fails on WSL username = os.getlogin() except FileNotFoundError: # works on WSL username = os.environ["USER"] return username
49cf52e03f1d8ad29b411a2e7df99e833f74fabc
688,770
import os def encode_path(path: str) -> str: """Encode a path from `/` to `__` :param path: A path to encode :return: An encoded vector """ vec = [] while path: head, tail = os.path.split(path) vec.append(tail) path = head return '__'.join(filter(lambda x: x, vec[:...
93de3a469f275bb5fec6881d04a8fe54db240dc7
688,771
def is_verb(tok): """ Is this token a verb """ return tok.tag_.startswith('V')
a42e92596de719d55810bbe8012f7418cc7d9be8
688,772
def get_fuel_required(module_mass: float) -> float: """Get the fuel required for a module. Args: module_mass: module mass Returns: fueld required to take off """ return int(module_mass / 3.0) - 2.0
2dc7f2840e681fb1f74d4ef1f280a7727f14ccfd
688,773
def _agsmerge(args): """Internal functions.\n Merges lists/tuples.""" if not isinstance(args, (tuple, list)): return args a = [] for i in args: if isinstance(i, (tuple, list)): a.extend(i) else: a.append(i) return a
bea9c5f94512ef3fe934fb6b6b69b567749e05c3
688,774
def break_reference_time(cape_cube, precip_cube): """Modifies precip_cube forecast_reference_time points to be incremented by 1 second and returns the error message this will trigger""" precip_cube.coord("forecast_reference_time").points = ( precip_cube.coord("forecast_reference_time").points + 1 ...
dd08db28d8dd24160bd15f11de32686c9b444dd8
688,775
def getprop_other(getter): """getprop(property_or_getter) Used on getters that have the same name as a corresponding property. For Qt bindings other than PythonQt, this version will return the result of calling the argument, which is assumed to be a Qt getter function. (With PythonQt, properties override getter...
cf88a9ce9cd30268ae5fbe91eee4ad8c30e2489e
688,776
def uniq(xs): """Remove duplicates in given list with its order kept. >>> uniq([]) [] >>> uniq([1, 4, 5, 1, 2, 3, 5, 10]) [1, 4, 5, 2, 3, 10] """ acc = xs[:1] for x in xs[1:]: if x not in acc: acc += [x] return acc
d0c7b87970d25c29127676f6a78d2e2cd961deac
688,777
def lang(name, comment_symbol, multistart=None, multiend=None): """ Generate a language entry dictionary, given a name and comment symbol and optional start/end strings for multiline comments. """ result = { "name": name, "comment_symbol": comment_symbol } if multistart is no...
e1e89caf4bb595e61a94df1ee70d33c39e75f486
688,778
def listify(item) -> list: """ If given a non-list, encapsulate in a single-element list. """ return item if isinstance(item, list) else [item]
0f836bae02f59e659704360dffa8ebf22a45a0f9
688,779
import copy def copy_original_exchange_id(data): """Copy each exchange id to the field ``original id`` for use in writing ecospold2 files later.""" for ds in data: for exc in ds['exchanges']: exc['original id'] = copy.copy(exc['id']) return data
c8f9634762feb91fc173e080d585fbdfef86b9fb
688,780
def _strip_wmic_response(wmic_resp): """Strip and remove header row (if attribute) or call log (if method).""" return [line.strip() for line in wmic_resp.split('\n') if line.strip() != ''][1:]
7b235993aaa3bade533730e5698611163263740e
688,781
def guess_mode(args, config): """Guesses the mode (compose, read or export) from the given arguments""" compose = True export = False if args.decrypt is not False or args.encrypt is not False or args.export is not False or any((args.short, args.tags, args.edit)): compose = False export =...
f13c70880b4768ea8b9fda7a076378b93f4a2b51
688,782
def get_articles(cv): """Given an instance of the CollectionsView, it will loop through the table page view creating and returning a list of articles""" blog_posts = {} # {'title': 'page_id',] for row in cv.collection.get_rows(): blog_posts[f"{row.title}"] = row.id return blog_posts
765d80a6c7b7e77d3eafa3280080a43e31ccd64d
688,783