content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def clean_matrix_U_invalid_object_id(_U): """ in pipeline object_ids that couldn't be processed and end up having no OBJID ('') should be removed :param _U: :return: invalid records from _U where OBJID missing """ return _U[_U.OBJID != ""]
9945e6aedee60a8a76572670cba77ee1c78a8889
646,371
import re def parse_timezone(timezone: str) -> float: """Parse timezone to offset.""" match = re.match( r"^(?P<sign>[-+])(?P<hours>\d{1,2}):(?P<minutes>\d{1,2})$", timezone ) if match: if match.group("sign") == "-": sign = -1.0 else: sign = 1.0 r...
0916ece008c16d0149c2238a7ed5069c1c572505
646,374
def _confirm_no_logfile_not_web_flac(params): """ Gazelle trackers require a logfile for lossless releases If no logfile is indicated, ask if the user wants to change the release type to "web" (no logfile required), ignore the lack of logfile and continue the upload or cancel it :returns conti...
7a1bbe051954d243e213a1dbc1a0a233eb6faf22
646,376
def roc_to_common_era(date: str): """Turn ROC era string to common era e.g. 105/01/01 -> 2016/01/01 """ year = int(date[:3]) + 1911 return f"{year}{date[3:]}"
745a5fcd377f17c44d53c0778a2ae355b310d006
646,378
def inv_min_max_norm(x, min_x, max_x): """ Computes the inverse min-max-norm of input x with minimum min_x and maximum max_x. """ return x * (max_x - min_x) + min_x
e9889e5dc22f9a7c47a95b31bcf0cf758732ef1c
646,379
def is_top(module_index): """Returns True if module is in the top cap""" return ( (module_index>=736)&(module_index<832) )
c89d7050cad257fa6f826e41c03ae96e6a95c38c
646,381
from typing import List from typing import Dict from typing import Any def prepare_queue_details_get_output(records: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """ Prepares context output for queue_details_get command. :param records: List containing dictionaries of queue records. :return: prepar...
884d6c1cf6d841c68338e41d852e80f607150986
646,386
def _get_histogram_settings(agg): """ Get the settings for a histogram aggregation :param agg: the histogram aggregation json data :return: dict of {setting_name: setting_value} """ histogram_settings = dict(field=agg['field']) settings = agg['settings'] histogram_settings['interval'] ...
fbc7e844be3dbb1196c3d0a0ccce30128aebaee5
646,388
def escaped(val): """ escapes a string to allow injecting it into a json conf """ val = val.replace('\\', '/') val = val.replace('"', '\"') return val
6f8b6b66bf78b175042a268b85df275a3eafd2e2
646,390
def calc_an_sparsity(L, q, K): """Calculates sparsity of Adjacent Neighborhood scheme""" return 1 + L*(q-1)*q**(K-1)
0fc6f63a1f417c46a26721fcf82e9dc0c827cc6c
646,391
def rightjustify(linetext, linecount, max_countwidth): """Justify ordered line to the right Arguments: linetext {str} -- a text to justify linecount {int} -- a line count (1-based) max_countwidth {int} -- a maximum count width Returns: str -- a justified line """ fi...
4ed7ecb2fe4c26fe944496d8b50e44889b4cb29e
646,394
def getInputs(tx): """ The getInputs function is a small helper function that returns input addresses for a given transaction :param tx: A single instance of a Bitcoin transaction :return: inputs, a list of inputs """ inputs = [] for input_addr in tx['inputs']: inputs.append(...
2ee5de01006242c6339c32c463b3f92795e1900e
646,397
import json import codecs def write_json(filename, obj): """Write JSON.""" fail = False try: j = json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': ')) with codecs.open(filename, 'w', encoding='utf-8') as f: f.write(j + "\n") except Exception: fail = Tr...
25b4ea17887d541644adbdc87af70f8d245df922
646,401
import re def remove_amp_references(txt: str) -> str: """Remove references to amp.""" txt = re.sub("^amp/", "", txt, flags=re.MULTILINE) txt = re.sub("/amp/", "/", txt, flags=re.MULTILINE) txt = re.sub("/amp:", ":", txt, flags=re.MULTILINE) return txt
7fee823504caf3bffb76540764a83ea2e4699950
646,406
from pathlib import Path def list_run(dname): """List all .dat files in a directory.""" path = Path(dname) return sorted(list(path.glob('*.dat')))
d9d9e6485f04aab9e69c8ca3b596d8fb87771596
646,408
def residue_points(m): """Return a dictionary with each residue and the numbers that produce it""" D = {} for i in range(m): r = (i**2) % m if str(r) in D: D[str(r)].append(i) else: D[str(r)] = [i] return D
9ecdf64f20f53119bbbf1af3af790251cac9de9b
646,410
def transpose(matlist, K): """ Returns the transpose of a matrix Examples ======== >>> from sympy.matrices.densetools import transpose >>> from sympy import ZZ >>> a = [ ... [ZZ(3), ZZ(7), ZZ(4)], ... [ZZ(2), ZZ(4), ZZ(5)], ... [ZZ(6), ZZ(2), ZZ(3)]] >>> transpose(a, ZZ) ...
2f3909e6c7bd0d554520c8d240d7630e0620f3f5
646,412
def _block_len_in_section(block, section): """Return the length of a block in a section [start, end].""" len_start = max(block.start, section.start) len_end = min(block.end, section.end) return len_end - len_start + 1
2cdb004d6d4ed70dd267d9fe9f37753bb5e7d95c
646,414
def wrap(command: bytes): """ Wrap the given command into the padding bytes \x02 and \x03 :param command: bytes :return: padded command: bytes """ start = b"\x02" stop = b"\x03" return start + command + stop
bc31e05edecde7a95042e52c3ac9f7fd15957356
646,421
from typing import Any import yaml from functools import reduce def get_config_value(keys: str) -> Any: """Retrieves a configuration value from the Pavo configuration file. Args: keys (str): The string of (nested) dictionary values. Note: You can find nested keys by introducing '.' in yo...
2b760613e463b38ec0aceba8aa57c5c678f5208c
646,422
import random def get_exponential_backoff_interval( factor, retries, maximum, full_jitter=False ): """Calculate the exponential backoff wait time.""" # Will be zero if factor equals 0 countdown = min(maximum, factor * (2 ** retries)) # Full jitter according to # https://www.awsarch...
c3b26aeed4267218a0698a431239f57dcbfbcf45
646,423
def split_namespace(tag): """returns a tuple of (namespace,name) removing any fragment id from namespace""" if tag[:1] == "{": namespace, name = tag[1:].split("}", 1) return namespace.split("#")[0], name else: return (None, tag)
e144cc7e693bbe2abdac26d567dbe706f40759ff
646,424
import re def replace_unescaped_utf_8_chars(input_text): """ Unescapes characters like "&#x00c3;&#x00a4;" with their equivalents, e.g. "ö". Only necessary to support Python 2.7+. """ pattern = re.compile(r"&#x00(\w{2});&#x00(\w{2});") def replace(match): byte_array = bytearray(map(lam...
c5cc78e62e01dcda4343261e840ab38aff375660
646,427
def make_dnp(pid: int, gid: int, team: int) -> list: """Player was labeled DNP (Did Not Play) :param pid: (int) Player ID :param gid: (int) Game ID :param team: (int) Team ID :return: (lst) Player Stats """ player_stat = [] player_stat.append(pid) # Player ID player_stat.app...
4ec4fa14747e361b3728c8fa472387426298db4f
646,428
from typing import List def get_substr_index(ls_string: List[str], substring: str) -> int: """ Parameters ---------- ls_string : list of strings to find the substring in substring : the substring Returns ------- int of index of the first substr match in the list, -1 if the substr does...
0e25f99e824829234dcf11259e2b8fc4ae3866d3
646,434
import heapq def find_k_largest_numbers(nums: list[int], k: int) -> list[int]: """ Complexity: Time: O(nlogk) Space O(k) Args: nums: array of numbers for which to find the largest k elements k: num largest elements to find Returns: the k largest elements in `nums` ...
291923a5ea9be157e599666922d6c8c69530b394
646,435
def valid_age(person, i, min_age): """Verify age requirement of person in given iteration.""" return person["birth"] <= (i - min_age) and person["death"] >= i
691083b293c4537ee1dcbf65448104c366dfd575
646,436
def narrow(checked, DASHRlut): """Returns dictionary mapping selected DASHRs to local drives. :param checked: array of integer pins :param DASHRlut: dictionary mapping of all locally detected DASHRs :returns: dictionary mapping only user-selected DASHRs """ for_harvest = {} for pin in check...
d34d579a687c77c4c33d1b4fa064002e4e9e51f7
646,437
def factorial_pythonic(number: int) -> int: """Factorial with reduce function (pythonic approach). Examples: >>> assert factorial_pythonic(0) == 1 >>> assert factorial_pythonic(1) == 1 >>> assert factorial_pythonic(2) == 2 >>> assert factorial_pythonic(3) == 6 """ return...
b5b9aa022f454b0f371d9108691f91b17d50588a
646,441
import re def camelcase_to_snakecase(_str: str) -> str: """camelcase_to_snakecase. Transform a camelcase string to snakecase Args: _str (str): String to apply transformation. Returns: str: Transformed string """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', _str) return re.sub...
bdad95ef8e16c0197cf764656bbf739a5dafa165
646,442
def assign(domino_set): """Assigns 7 domino pieces to each player and returns each players set of tiles and the list of remaining tiles""" player_hand = [] computer_hand = [] for _ in range(7): player_hand += [domino_set.pop()] computer_hand += [domino_set.pop()] return player_hand,...
61bdfaaf5ecc8a0fa6caee6a84b8257702da11d6
646,444
def order_slaves_on_gtid(slaves): """Function: order_slaves_on_gtid Description: Take a Slave array and sort them on their GTID positions, with the top(first) slave being the best Slave. Arguments: (input) slaves -> Slave instance array. (output) slave_list -> List of slaves in ...
07fdc77dea153dd02efa0bdd0cb7b71a5c223835
646,461
def clean_sheet_value(value): """ Takes a spreadsheet cell value and returns a cleaned version Args: value (str): A raw spreadsheet cell value Returns: str or None: A string with whitespace stripped, or None if the resulting value was an empty string """ stripped = value.strip(...
ff6b2da6f0ce3d718e71b43794e0a224e7f7b072
646,464
def my_formatter_1f(x,p): """Format tick marks to have 1 significant figure.""" return "%.1f" % (x)
ff89e72a071c609e6a363dc8fa4ba648c1d05031
646,465
def scurve(start,end,n,s): """Return an S-Curve with a constant velocity section from start to end with n points. The start and end S-curves each have s points""" ys,ye = start,end s1 = [ (ye-ys)*(x*x-s*s)/(2*s*float(n-1))+ys for x in range(0,s) ] cv = [ (ye-ys)*(x-s)/float(n-1)+ys for x in range(s,s+n) ] s2 = [ ...
a16ba1143cdeff9a8392a2c993b88918dff82350
646,470
def sort_files(files): """Sort a list of file names. Parameters ---------- files : list of str List of file names, to sort. Returns ------- list of str Sorted list of files. """ return sorted(files)
390684ba6292a2d1f898dcb512e429efaad39806
646,475
def convert_to_99_percent_confidence(margin_of_error): """ Converts a margin of error from the U.S. Census Bureau to the 99% confidence level. Args: margin_or_error (float): A margin of error at the bureau's standard 90% confidence level Returns: The adjusted margin of error (float). ...
8bb872c84bdda9a6943c9402f61a18df3e84e889
646,480
def awk(s: str, n: int, d: str = ' ') -> str: """Act like awk and select the nth element Args: s: string to split up n: the element to select d: the delimiter between elements Returns: """ split = s.strip().split(d) if len(split) >= n: # awk is 1-indexed ...
2ba2cd0f6734384d699e4c2860a50c665d930549
646,482
import csv def ReadFile(f, tsv=False): """Read the CSV file, returning the column names and rows.""" if tsv: c = csv.reader(f, delimiter='\t', doublequote=False, quoting=csv.QUOTE_NONE) else: c = csv.reader(f) # The first row of the CSV is assumed to be a header. The rest are dat...
64cbfa3521487abeb1400be479ea64640cc5cb86
646,483
def _DegreeDict(tris): """Return a dictionary mapping vertices in tris to the number of triangles that they are touch.""" ans = dict() for t in tris: for v in t: if v in ans: ans[v] = ans[v] + 1 else: ans[v] = 1 return ans
0626c2019aa2d4f46f5267ed8e19f7d69fe1fc48
646,484
def escape_path(path): """ Adds " if the path contains whitespaces Parameters ---------- path: str A path to a file. Returns ------- an escaped path """ if ' ' in path and not (path.startswith('"') and path.endswith('"')): return '"' + path + '"' ...
6f3122532fa2590d43e9ad537d07f005d05c54fa
646,486
import json def get_json_value(value): """ Get value as JSON. If value is not in JSON format return the given value """ try: return json.loads(value) except ValueError: return value
672f8d79aef23ee8f639ce87860029d54bf78ca3
646,487
import sqlite3 def get_columns(cxn, table): """Get a list of columns from a table""" sql = f'PRAGMA table_info({table});' cxn.row_factory = sqlite3.Row columns = [r[1] for r in cxn.execute(sql)] return columns
b3b33d52d644409cda497e1a71c873d6470fa93c
646,490
def find_row(table, row): """ Return row index with row header in table or -1 if row is not in table """ for idx in range(len(table)): if table[idx][0] == row: return idx return -1
64f7cab3a9f7d9829a40c993185d5ccc9689d1c8
646,495
def map_severity(meta_severity): """ Map scanner severity to Carrier severity """ severity_map = { "INFO": "Info", "WARNING": "Medium", "ERROR": "High", } return severity_map.get(meta_severity, "Info")
a7126a332820db07e0deed52194def3c0a11fe12
646,496
def get_zip_perms(zipinfo): """Get file/dir permissions from zipinfo Args: zipinfo (zipfile.Zipinfo): information about one component file of a zip-file Returns: int: file permissions for file in octal """ # Windows zip files with no permissions seem to sensibly default ...
7321b95dee6aedcf5771b19eabc09977fd9333ed
646,497
def imap(imap, vmin=None, vmax=None, cmap='YlGnBu_r', length_unit='cm'): """ Convenience base function to plot any IntensityMap2D instance Parameters ---------- ratemap : IntensityMap2D Intensity map to plot cmap : Colormap or registered colormap name, optional Colormap to use f...
fbc19e21f7740bb2965f99398090eb24929b4e52
646,498
def weighted_average(values): """Calculates an weighted average Args: values (Iterable): The values to find the average as an iterable of ``(value, weight)`` pairs Returns: The weighted average of the inputs Example: >>> weighted_average([(1, 2), (2, 3)]) 1...
5f6e08bb90d2325e346b62519272c562d174fa06
646,503
def set_staff_object(context, object): """ Assign an object to be the "main object" of this page. Example:: {% set_staff_object page %} """ request = context["request"] request.staff_object = object return ""
ac2b6d3642f1fbe9b707dcbee0f27edb1bdcd72f
646,505
import math def standard_deviation(times): """ Calculates the standard deviation of a list of numbers. """ mean = sum(times) / len(times) # Sum the squares of the differences from the mean. result = 0 for time in times: result += (time - mean) ** 2 return math.sqrt(result / len(times))
6e46feb09ffc6bf0a3ecc960adfeec9c95269754
646,509
import copy def get_value_from_str_dotted_key(d, dotted_key): """Get value from python dict via dotted notation. :param d: dictionary :param dotted_key: :return: str """ keys = dotted_key.split('.') temp = copy.deepcopy(d) try: for key in keys: temp = temp[key] ...
33a97ae9ea842f5cace8baf71dba039770e69af2
646,511
from typing import OrderedDict def parse_headers(text): """Parse a string of headers (copied from Firefox) into a dict used in requests.""" return OrderedDict(line.split(': ') for line in text.splitlines() if line)
474501f99f464a7b7af6e326a83f32e3ca96a8a2
646,512
def compose_key(instance): """Given an instance, returns a key :arg instance: The model instance to generate a key for :returns: A string representing that specific instance .. Note:: This uses the id attribute of the model instance. That's good enough for my needs, but we might need ...
728696720af1d94adf69e664d2da1ab9d248a563
646,515
import re def parse_bind_address(address, default=('localhost', 8080)): """ >>> parse_bind_address('80') ('localhost', 80) >>> parse_bind_address('0.0.0.0') ('0.0.0.0', 8080) >>> parse_bind_address('0.0.0.0:8081') ('0.0.0.0', 8081) """ if ':' in address: host, port = addres...
5e4275e361bec09a517a2b8c78c77f7e285c5054
646,517
def to_identifier(key): """Converts given key to identifier, interpretable by TaskJuggler as a task-identifier Args: key (str): Key to be converted Returns: str: Valid task-identifier based on given key """ return key.replace('-', '_')
3ebd320a40761ca85a8d564e27754621a5c9c1e6
646,519
def compute_kmp_fail(P): """Utility that computes and returns KMP 'fail' list.""" m = len(P) fail = [0] * m # by default, presume overlap of 0 everywhere j = 1 k = 0 while j < m: if P[j] == P[k]: # k + 1 characters match thus far fail[j] = k + 1...
ebf7008d05b46f49e0aaecd236c74406b2963677
646,520
def _parse_text(res, path): """Parsing text from response by path. """ value = None node = res.find(path) if node is not None: value = node.text value = value.strip() return value
d4cfa89412c968a2c1a1737bfc2051dc2e621712
646,523
def clean_texmath(txt): """ clean tex math string, preserving control sequences (incluing \n, so also '\nu') inside $ $, while allowing \n and \t to be meaningful in the text string """ s = "%s " % txt out = [] i = 0 while i < len(s)-1: if s[i] == '\\' and s[i+1] in ('n', 't'...
95741f1f3cc84a7c7ae6479cc49ace350a6ba40d
646,526
import math def days_frac_to_dhms(days_frac): """Convert a day float to integer days, hours, minutes and seconds. Returns a tuple (days, hours, minutes, seconds). >>> days_frac_to_dhms(2.5305) (2, 12, 43, 55) """ days = math.floor(days_frac) hms_frac = days_frac - days hours = ma...
82a8b85dcadef3e279637fb514d6a926231df18f
646,527
def yes_or_no(question): """ a utility tool to ask the user yes/no question Parameters ---------- question : str the text for the question Returns ------- value : bool True or False """ while True: answer = input(question + ' (y/n): ').lower().strip() ...
6bbc7da97e3af17ae1689a2bd88665b6e1ff1356
646,528
def keyboard_data_signals_an_interrupt( keyboard_data, stop_signal_chars=frozenset(['\x03', '\x04', '\x1b']) ): """The function returns a positive stop signal (1) if the character is in the `stop_signal_chars` set. By default, the `stop_signal_chars` contains: * \x03: (ascii 3 - End of Text) * \...
ac395bd2ccc690e6f1b40565db297087d3a1738b
646,530
def get_metric(mod, obs, fun, dim='time', verbose=False): """Calculate a metric along a dimension. Metrics implemented: name * correlation > corr * mse > mse * rmse > rmse * mean percentage error > mpe * stan...
f70caba77a464f8ed55da0daa2c4b4eb5a45a4e6
646,536
def remove_spaces(st): """ Removes spaces from a string :param st: (str) input string with spaces :return: (str) string without any spaces """ return st.replace(' ', '')
3419571854077e2365c94d96394be0edfbe8912d
646,539
import itertools def Powerset(iterable): """powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3).""" s = list(iterable) return itertools.chain.from_iterable(itertools.combinations(s, r) for r in range(len(s)+1))
a904a9cf7c4a62238f114dc877080e20bcf78d92
646,541
def update_leases(transform, persistence_service): """ Update the leases configuration in the persistence service. :param transform: A function to execute on the currently configured leases to manipulate their state. :param persistence_service: The persistence service to which the updat...
bd99ef43d452a520061305e0ac8bb6e21326b2a6
646,542
def pkg_key(pkg, type_): """ generate a package key for a given type string Generates a compatible "package key" for a unsanitized package name ``pkg`` of a specific key ``type``. The package string is "cleaned" to replaces select characters (such as dashes) with underscores and becomes uppercase. ...
c61ff00db34d0d838bd95ff011679a1ec523a3af
646,545
import re def generate_node_id(node, data): """Generate a node ID from the node label, extracts data from: [$ID]. Return the extracted node ID and the label, without the ID part, so it can be the expression if one isn't specified in the description.""" pat = r"\[(?P<node_id>\w+)\]" m = re.search(...
65826d73028d3f5fc7107b7f540e698d5f8739f5
646,546
def normalize(msg): """ Normalizes the plain text removing all invalid characters and spaces :param msg: Plain text to be normalized :return: the normalized message without invalid chars """ return "".join([let.lower() for let in msg if let.isalpha() or let.isdigit()])
d0bea7e7a813196d49cda8873d756849ec61b36d
646,550
import json def load_json(filename): """Load dictionary from JSON file.""" with open(filename, 'r') as f: mybooks = json.load(f) return(mybooks)
3edd21661886ea783e1e9d9c4f4c65561e35f060
646,551
def update_nested_dictionary(old, new): """ Update dictionary with the values from other dictionary. Recursively update any nested dictionaries if both old and new values are dictionaries. :param old: Old dictionary that will be updated :type old: dict :param new: New dictionary that contains t...
9960cab305508a38b7b245c2db468db263c413d5
646,552
def fisbHexErrsToStr(hexErrs): """ Given an list containing error entries for each FIS-B block, return a string representing the errors. This will appear as a comment in either the result string, or the failed error message. Args: hexErrs (list): List of 6 items, one for each FIS-B block. Each entry ...
7f81dc250b6e780f384720d98bb53574b1da86f9
646,553
def wing(Sw,bw,cw,Nwr,t_cw,Nwer,nult,GW): """ Compute weight of human-powered aircraft wing Assumptions: All of this is from AIAA 89-2048, units are in kg. These weight estimates are from the MIT Daedalus and are valid for very lightweight carbon fiber composite structures. This may n...
be00ec0cc3580fb2446b5bbb9fca391845da6855
646,554
def read_lines(file_name): """ Read lines from given file and return as list """ with open(file_name, 'r') as fobj: lines = fobj.readlines() return lines
d5fbf26b61029a6cfd1738b8d3f44b71bbf6e0a2
646,561
def count_frequency(my_list): """ count the frequency of elements in a list using a dictionary Args: my_list (list): List Returns: dict: Dictionary containing unique item and frequency Example:: >> my_list = ["happy", "neutral", "happy"] >> count_frequency...
8db1b58f429fe596e73094e0ae100a38251acf86
646,564
def _ensure_list(item): """ Ensures that the given item is a list. :param item: :return: """ if item is None: return [] if isinstance(item, list): return item if isinstance(item, tuple): return list(item) return [item]
35f5fffdf8cdcac5d2ecd1f2291395a633ceddc7
646,565
def header_exists(header_name, headers): """Check that a header is present.""" return header_name.lower() in (k.lower() for (k, _) in headers)
bf0dd31a9febbed20efb7e8078bc085b5fe4f792
646,576
def pre_process_expressions(expressions, variable_templates): """ This one is pretty simple - pass in a list of expressions which contain references to templates and pass a dictionary of the templates themselves. Strings will only be evaluated which are prepended with $. Parameters ---------- ...
ae9a418215380d5804de9ad339af12601f29abc1
646,577
import torch def neigh_square(position_diff: torch.Tensor, sigma: torch.Tensor) -> torch.Tensor: """ Square-shaped neighborhood scaling function based on center-wise diff `position_diff` and radius `sigma`. Parameters ---------- position_diff : torch.Tensor The positional difference aroun...
abebe4bbcbb348d45b396867b833fcb0714cb0ca
646,578
def join_strings(strings, glue=" AND "): """ Returns the non-empty strings joined together with the specified glue. @param glue separator used as glue between strings @return (joined string, number of strings actually used) """ strings = list(filter(None, strings)) return glue.joi...
18a786d7f74cc07a3645036dfbd012c3268c0d07
646,580
def custom(datacells, ncells, value): """Calculate percent of total""" x = float(datacells.GetUnformattedValueAt(ncells-1,2)) # total return float(value) / x
f65190bd2680f5a2adc8065d1e5d75630ccd2136
646,583
def shape(x): """Change str to List[int] >>> shape('3,5') [3, 5] >>> shape(' [3, 5] ') [3, 5] """ # x: ' [3, 5] ' -> '3, 5' x = x.strip() if x[0] == '[': x = x[1:] if x[-1] == ']': x = x[:-1] return list(map(int, x.split(',')))
554d2c3f7572b10a897d03c679420a8afed56a0a
646,584
def max_value(tab): """ Brief: computes the max with positiv value Args: tab: a liste of numeric value exepcts at least one positive valus, raise expection Return: the max value Raises : ValueError if no positive value is found """ if not(isinstance(tab, list)): rai...
82a6e83df070a8e32ecce6f12a7e0a03307b81ce
646,588
def calc(x, y, serial): """ Find the fuel cell's rack ID, which is its X coordinate plus 10. Begin with a power level of the rack ID times the Y coordinate. Increase the power level by the value of the grid serial number (your puzzle input). Set the power level to itself multiplied by the rack I...
f3aac2bbb2e3180716773c7751678dbb4335890c
646,589
def make_snapshots(frame, ignore): """Extract a subset of atoms from a given frame.""" snapshot = { 'header': 'Removed.', 'box': frame['box'], 'residunr': [], 'residuname': [], 'atomname': [], 'atomnr': [], 'x': [], 'y': [], 'z': [], } ...
e2356bdad3c8fe7633d598ea6e49825e90daf671
646,593
def calculate_difference(dsm_array, dtm): """Calculate the difference between the dsm and dtm""" dtm_array = dtm.read(1, masked = True) difference = dsm_array - dtm_array difference.data[difference < 0] = 0 # We set to 0 anything that might have been negative return difference
962078fe055b27189472fceb4008665aa946b038
646,606
def norm_colname(colname): """Given an arbitrary column name, translate to a SQL-normalized column name a la CARTO's Import API will translate to Examples * 'Field: 2' -> 'field_2' * '2 Items' -> '_2_items' Args: colname (str): Column name that will be SQL normalized Return...
623eef718a6f74d374250a32f291b499fae0d9fa
646,607
def makesafe(s): """Makes the given string "safe" by replacing spaces and lower-casing (less aggressive)""" def rep(c): if c.isalnum(): return c.lower() else: return '_' ret = ''.join([rep(c) for c in s]) return ret
13d8b683c348c991007ee2463e976ac1da394d29
646,611
def _get_empty_lines(text): """Get number of empty lines before and after code.""" before = len(text) - len(text.lstrip('\n')) after = len(text) - len(text.strip('\n')) - before return before, after
e9125dc8039ebe4208c8358fb11dd33e58ee8506
646,614
def _get_db_table_for_model(model): """ Return table name in database server for passed model. """ return model._meta.db_table
14607fd11ae308b371af45232467bbe13fe907ac
646,617
def INT_ICART(a, b, c): """Given a, b, and c, return a cartesian offset. #define INT_ICART(a, b, c) (((((((a)+(b)+(c)+1)<<1)-(a))*((a)+1))>>1)-(b)-1) """ return ((((((a + b + c + 1) << 1) - a) * (a + 1)) >> 1) - b - 1)
9547d9a9de2bfde2a19144c1be314d23cdef173e
646,618
def walk(path, container): """ Recurse over the ActBlue JSON object, and get the values that we need, based on the settings file. Returns a single value for each path. """ if not container or isinstance(container, str): return None key = path[0] if len(path) == 1: if key...
5fe569bc6b15d29fe8761900383a6cd46b17f9b8
646,622
def sparse_mimmax(A, B, type="mim"): """Return the element-wise mimimum/maximum of sparse matrices `A` and `B`. Parameters ---------- A: The first sparse matrix B: The second sparse matrix type: The type of calculation, either mimimum or maximum....
922bd5a7a3d3651347b59e7c2f05b6e8983410bb
646,625
def format_literal(raw): """Format a literal into a safe format. This is used to format the flont:Literal IRI. """ return "_" + raw.replace(" ", "_")
87a6d4b0eb0d162f178ebba4d628d09133c6ed84
646,631
def make_PEM_filename(cert_id: str) -> str: """Create a filename for PEM certificate""" return cert_id + '.pem'
48fe918f64822b74f580303ac022dbfda07468fd
646,632
def is_in_list(num, lst): """ >>> is_in_list(4, [1, 2, 3, 4, 5]) True >>> is_in_list(6, [1, 2, 3, 4, 5]) False >>> is_in_list(5, [5, 4, 3, 2, 1]) True """ if not lst: return False else: return lst[0] == num or is_in_list(num, lst[1:])
891e6727ffe88f682f55bea5553df1ddc1558d90
646,634
def get_investigation_data(investigation_response): """Get investigation raw response and returns the investigation info for context and human readable. Args: investigation_response: The investigation raw response Returns: dict. Investigation's info """ investigation_data = { ...
0caedeb4581a6fc5493b0c2fa7953b670a9c3008
646,635
def wraps(wrapped, fun, namestr="{fun}", docstr="{doc}", **kwargs): """ Like functools.wraps, but with finer-grained control over the name and docstring of the resulting function. """ try: name = getattr(wrapped, "__name__", "<unnamed function>") doc = getattr(wrapped, "__doc__", "") or "" fun.__d...
b3fa0464bdde8518eeed626dab5fcfaf38beac5a
646,636
import re def keyvault_name(name: str) -> bool: """Validate the name of the keyvault. Args: name (str): Name of the keyvault. Returns: bool: True or False depending on the name validity. """ regex = "^[a-zA-Z0-9-]{3,24}$" pattern = re.compile(regex) return pattern.match(...
db648c1d1c507f652ebd4e589c1b37ea9459e746
646,637
import torch def has_gpu() -> bool: """Detect if the runtime has GPU. This function calls torch function underneath. To mask an environment to have no GPU, you can set "CUDA_VISIBLE_DEVICES" environment variable to empty before running the python script. Returns: bool: True i...
694e86cfd2d94dc5d9cf2a626a5675f444d31f17
646,642
import logging def parse_device_list(device_list_str, key): """Parses a byte string representing a list of devices. The string is generated by calling either adb or fastboot. The tokens in each string is tab-separated. Args: device_list_str: Output of adb or fastboot. key: The token that signifies a...
c893b496f92d89692c120e3674325cec2752be18
646,643