content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Optional from typing import List import pkg_resources def get_version( package_name: str, raise_on_error: bool, alternate_package_names: Optional[List[str]] = None, ) -> Optional[str]: """ :param package_name: The name of the full package, as it would be imported, to get...
da11011a40b4cdfb4a9ebfc302b3a76adc2ccff9
687,206
import re def is_valid_username(username): """Validate username.""" return re.search(r"^[a-zA-Z0-9]+([_-]?[a-zA-Z0-9])*$", username)
6ef303a5509980eaa5f2b0229b9f3ab76127c530
687,207
def application_package_reference_format(value): """Space-separated application IDs with optional version in 'id[#version]' format.""" app_reference = value.split('#', 1) package = {'application_id': app_reference[0]} try: package['version'] = app_reference[1] except IndexError: # No specif...
9687fe758ac3e9a7303c370748f0ad769780a6c0
687,208
import numpy def ParkerAIF(time): """ Function to determine the Parker AIF given a certain time array Parameters --------- time time array in seconds. AIF array of concentration values for whole blood citation: Parker et al. Magn Reson Med 2006 https://doi.org/10.1002/mrm...
10a0c1b21a5f7a41081d035327ee1b3513848665
687,209
def get_simulation(open_rocket_helper, ork_file_path, i_simulation): """Return the simulation with the given index from the .ork file. :arg open_rocket_helper: Instance of ``orhelper.Helper()`` :raise IndexError: If `i_simulation` is negative or >= the number of simulations in the ...
5b4d049a8437f3de4e2d5a2a0ff8786c392e6633
687,210
def within_time_period(t, time_period): """ Check if time is in the time period Argument: t = given time in format (half, min, sec) time_period = tuple of (start_time, end_time) in format (half, min, sec) Return: boolean """ start_time = time_period[0] end_time = t...
b996ed5b2d49c95faebae558bf064df02dde4867
687,211
def num_min_repeat(arr): """ Discuss the length of the longest increasing sequence. length = the number of distinct elements Use an end to store the last element's index of the seq. Loop the sorted array temp(monotonically increasing), and let index = arr.index(x). (interviewer helped me modif...
e5305a5e4e85526910782e6fda795ea47f964fc1
687,212
def compute_agreement_score(arcs1, arcs2, method, average): """Agreement score between two dependency structures Parameters ---------- arcs1: list[(int, int, str)] arcs2: list[(int, int, str)] method: str average: bool Returns ------- float """ assert len(arcs1) == len(...
a2f19101ea246ccd317d7519214d103842b83d33
687,213
def read_image(file_path): """ Read an image file """ with open(file_path, "rb") as ifile: return ifile.read()
47305d81ecc9c7086397c7def765b54b5bb0fca7
687,214
def manhattan_distance(params): """ Manhattan distance from current position to target Args: current (tuple): x, y coordinates of the current position target (tuple): x, y coordinates of the target Returns: (float): Manhattan distance from current position to target """ current, target, solution = par...
66550268523d07cf0595230648765eed917e8814
687,215
def numstr(number, decimalpoints: int) -> str: """ Add commas, and restrict decimal places """ fmtstr = '{:,.%sf}' % str(decimalpoints) return fmtstr.format(number)
cd67503483c09e6203c2968f97d22d99809a74d6
687,216
def row_normalize(x): """ Scale a matrix such that each row sums to one """ return x / x.sum(axis=1)[:, None]
f2d2361aba7a208d6e8a1939a28de9dff56c6cfc
687,217
def spiralOrder(matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ ans = [] if len(matrix) < 1: return ans row_start, row_end = 0, len(matrix) - 1 col_start, col_end = 0, len(matrix[0]) - 1 while row_start <= row_end and col_start <= col_end: # left...
dbe284cb5892314b4c4d265c74f07f5af0a8ad84
687,218
import re def error_has_gloss(value): """Checks if the value has at least a hyphen followed by two capital letters""" return bool(re.match(r'.*\-[A-Z]{2,}', value))
51b390d4a5b21577f305db1e68b436af37324d39
687,219
def argmin(arr, f): """Return the index, i, in arr that minimizes f(arr[i])""" m = None i = None for idx, item in enumerate(arr): if item is not None: if m is None or f(item) < m: m = f(item) i = idx return i
de833012061eddbdd25146be0fb447956eb76e11
687,220
import re def valid_hcl(entry): """Validate hair color entries""" if entry[0] == '#': if len(entry) == 7: check = re.match(r'[^a-f0-9]', entry[1:]) if check is None: return True else: return False else: return Fals...
5fad58c307cf5616b73e5e4a448e4d4087c3bdce
687,221
import os def exec_command_output(run_command): """执行shell指令, 并返回输出的文本信息 """ r = None try: r = os.popen(run_command) return r.read() except Exception as e: return None finally: if r and not r.closed: r.close()
4b4005f397fe8b56abc8500c8d4dbd93c0bb79e0
687,222
import subprocess def _find_library(libs_list): """Helper for locating native system libraries from the list""" try: process = subprocess.Popen(["ldconfig", "-p"], stdout=subprocess.PIPE, universal_newlines=True) stdout = process.communicate() lines = stdout[0].split("\n") for ...
81e3983590623adc954da4778fe17d1974bfb228
687,223
import os def _ensure_folder_for_file(filepath): """ Makes sure the folder exists for a given file. :param filepath: Path to the file we want to make sure the parent directory exists. :returns: The path to the file. """ folder, _ = os.path.split(filepath) if not os.p...
34bb38df671d18199f18eb83766b42a3306ae66f
687,224
def generate_data(data, samples, targeted=True, start=0, inception=False): """ Generate the input data to the attack algorithm. data: the images to attack samples: number of samples to use targeted: if true, construct targeted attacks, otherwise untargeted attacks start: offset into data to use...
1dc1332c6004600bc346b55ba59a6ae7b603c6b1
687,225
def ytdl_detail(title, duration, uploader, requester, date) -> str: """ :return: a detailed string repersentation of a youtube-dl audio source. """ try: duration = float(duration) except (TypeError, ValueError): length = '' else: hours, seconds = divmod(duration, 3600) ...
734d2fea474d197df9b1d62232c6850f0d3dc4d8
687,227
import subprocess import sys import shutil import os def ensure_host_system_can_install_tljh(): """ Check if TLJH is installable in current host system and exit with a clear error message otherwise. """ def get_os_release_variable(key): """ Return value for key from /etc/os-releas...
4a6a0de536fcf1c26bb1889efbfd5fe192763856
687,229
import math def exp(v): """ EXP num outputs e (2.718281828+) to the input power. """ return math.exp(v)
11a42dd530733d20ffcc4438e2f2102b50479602
687,230
def divide_toward_zero(x, y): """Divides `x` by `y`, rounding the result towards zero. The division is performed without any floating point calculations. For exmaple: divide_toward_zero(2, 2) == 1 divide_toward_zero(1, 2) == 0 divide_toward_zero(0, 2) == 0 divide_toward_ze...
87411f1916d8272cee4286ac1dc5ec42a40cf1ef
687,232
def comma_join(fields): """ Converts everything in the list to strings and then joins them with commas. """ return ",".join(map(str, fields))
f470fe43fce06edfab3ec715a1ea6bfa6a2e431f
687,233
def sort_x_by_y(x, y): """Sort the iterable x by the order of iterable y""" x = [x for (_, x) in sorted(zip(y, x))] return x
e026d1466b1bf6b7779dceb86627d169e86ef5a7
687,234
import psycopg2 def _execute_psyco(command, **kwargs): """ executes a postgres commandline through psycopg2 :param command: A psql command line as a str :param kwargs: will be forwarded to psycopg2.connect """ # Note: Ubuntu 18.04 uses "peer" as the default postgres configuration # which...
5529a000e2cb69cbc8fa6240b960405ceab59a47
687,235
def geojson_wenceslas_square(): """ Wenceslas Square has width 60m """ return { "type": "Feature", "properties": {}, "geometry": { "type": "LineString", "coordinates": [ [14.428870975971222, 50.080010634213316], [14.42955225...
61b3385c918024abeae0aba1ae5c87221a59bc25
687,236
def pair(s1, s2, track_id_pairs): """Returns pairs of tracks, i.e., tracks that can be compared. s1 -- all tracks of sensor 1. s2 -- all tracks of sensor 2. track_id_pairs -- ID pairs of tracks of s1 and s2. """ pairs = [] # collect available ids of the sensor's tracks for tid1, tid2 i...
839b03c2fbdaf46f129d8e5b6bb44e4ea70b56b2
687,237
import functools def lsp_rpc(f): """A decorator for LanguageServerProtocol-methods. This wrapper filters out calls that are made before initializing the server and after shutdown and returns an error message instead. This decorator should only be used on methods of LanguageServerProtocol-objects a...
7bfbdc99d283eb44716bde44fb86bf64a82f662a
687,238
def normalize_matrix2D(lst): """ Normalizes a given 2 dimensional list. :param lst: list of items :return: normalized list """ sz = len(lst[0]) max_val = max(map(max, lst)) if max_val == 0: return lst else: norm_list = list() for i in range(0, sz): ...
b1f395c8f3385edf8b82f52c7dd55e8b49fb217d
687,239
import json from typing import OrderedDict def validate_payload(payload): """Validate that the payload is of type OrderedDict. If the payload is of type str, then it assumes that the string is able to be parsed via json. Args: payload (str or OrderedDict): Payload object Returns: ...
373561d9ce7df14625e6f40201ccb1a5b81a80d7
687,240
def clean_cluster_seq_id(id): """Returns a cleaned cd-hit sequence id The cluster file has sequence ids in the form of: >some_id... """ return id[1:-3]
b690d7472b1fb90743be27fed9ce9ef7c3b06694
687,241
import time def currentUtcTime(): """ Returns the time in UTC string format""" return time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime())
c59124d4cca575609109c26bb5b969402feaea85
687,242
def get_int_storage_path(dev): """Return internal storage path """ if dev: return dev.get_int_storage_path() else: return None
8e563f3ced2ef6116aa7c4b505a8ad2b6c9c8106
687,243
def longVal(x): """ longVal(x): if 'x' is a z3 constant (i.e. function of arity 0) whose value is an integer, then return that integer as a python long else return 'None'""" if(hasattr(x, 'as_long')): return x.as_long() elif(hasattr(x, 'numerator_as_long')): if(x.de...
277b1abcc13a7223e723acd5e3694d87d8a8e831
687,244
def is_palindrome(x): """ Check whether or not given number is palindrome :param x: given number :type x: int :return: whether or not given number is palindrome :rtype: bool """ if x < 0: return False # for 32-bit integer, the maximum number of digits is int(log(2**31)) ...
4eddf7377660fc8b4e69e30de3925e13716ab99a
687,245
import math def distance(point, center): """ This function calculates the distance between 2 points (taken as a list). We are refering to Eucledian Distance. """ if len(point) != len(center): return -1 dummy = 0.0 for i in range(0,len(point)): dummy += abs(float(point[i]) - float(center[i])) ** 2 return ma...
f76ef99e3288d69fec01b9b8b7997cc7048dd0b4
687,246
import reprlib def _format_args_and_kwargs(args, kwargs): """Format function arguments and keyword arguments. Special case for a single parameter: ('hello',) is formatted as ('hello'). """ # use reprlib to limit the length of the output items = [] if args: items.extend(reprlib.repr(ar...
25527bc74992c67e3b249808eaf4e6aa328cf822
687,247
def bytes_to_str(bytes, base=2, precision=0): """Convert number of bytes to a human-readable format Arguments: bytes -- number of bytes base -- base 2 'regular' multiplexer, or base 10 'storage' multiplexer precision -- number of decimal places to output Returns: Human-readable string such...
5a00d58fa8149f44c41d0a1ab30535ff4c2c7d86
687,249
import json def dump_params(params, compact): """ Converts list of params to a GraphQL representation. """ SEP = ': ' if not compact else ':' if not isinstance(params, dict): return ['(', json.dumps(params), ')'] chunks = ['('] for k, v in iter(params.items()): chunk...
8d4a998551e076e820d406c92b0e86f65b315940
687,250
import textwrap def _wrap(content, indent_level): """wrap multiple lines keeping the indentation""" indent = ' ' * indent_level wrap_opt = { 'initial_indent': indent, 'subsequent_indent': indent, } lines = [] for paragraph in content.splitlines(): if not paragraph: ...
9defcc8b216fb8a15b6c796fbf5d5206510db117
687,251
def fwd_slash(file_path): """Ensure that all slashes are '/' Args: file_path (st|Path): The path to force '/' Returns: (str): Formatted path """ return str(file_path).replace("\\", "/")
750dab03c5d3a0783a60151c7d4a1c13fff92ef5
687,252
import os def get_package_location(package): """Get module directory from the module information. Original function taken from StackOverflow: https://stackoverflow.com/a/44436961/4855984 """ try: module_dir = next(package._get_metadata('top_level.txt')) package_location = os.path....
8b9d98a5ebdb501e10d6b1d3339d36db55cf4d1b
687,253
def masterLambda(numLams, numMaster, numNow, masterLams, numPoints, listLineLambdas): """//Merge continuum and line wavelength scales - for one line //This expects *pure* line opacity - no continuum opacity pre-added!""" #//int numCnt = lambdaScale.length; #//skip the last wavelength point in ...
e22f3593a029c8d3495a7a5609ec96c125ea23bc
687,254
def file_to_dict(files, uplink=True): """ Converts files to dictionary. This creates a new list of JSONable file dictionaries. :param files: list of TransmitFiles to convert :return: list of dictionaries """ current = [] for item in files: current.append({ "source": item....
a89a52d330cf84d9da53171f756761d055fab6a6
687,255
import argparse def parse_args(): """Parse arguments. Args: Returns: Raises: """ parser = argparse.ArgumentParser(description='Model training tool.') parser.add_argument("--model_dir", "-md", help="set path for the best model") parser.add_argument("--batch_size", "-b",...
e8d7d408ccea37bd2977c09da2ad6ca83032ade9
687,256
def flatten_sub(sub, game_id): """Flatten the schema of a sub""" sub_id = sub[0] sub_data = sub[1] return {'game_id': game_id, 'sub_id': sub_id, 'sub_type': sub_data['type'], 'time_of_event(min)': (sub_data['t']['m'] + (sub_data['t']['s'] / 60 )), 'team_i...
d6557b01f6f2f11c829e1094b318bf2587c74977
687,257
def remove_by_idxs(ls, idxs): """Remove list of indexes from a target list at the same time""" return [i for j, i in enumerate(ls) if j not in idxs]
65c3c604d188cb8c7ed1ccef55d25b49c5412797
687,259
def gcd(a, b): """ Find GCD(a, b).""" # GCD(a, b) = GCD(b, a mod b). while b != 0: # Calculate the remainder. remainder = a % b # Calculate GCD(b, remainder). a = b b = remainder # GCD(a, 0) is a. return a
5acf8086075dcd9e2d01b539d4abc9af6c98fe01
687,260
import argparse def parse_arguments(): """ Parse command line arguments. """ parser = argparse.ArgumentParser( description="Python script for building supercell that can be used with PBC in MD simulation." ) parser.add_argument( '--input', "-i", type=st...
b6e463e06ddc98e4816f8adc693b9dc80c688809
687,261
def string_join_helper(delimiter, *args): """ joins args on delimiter, skipping arguments which are either None or '' :type delimiter: str :type args: str | None """ return delimiter.join([ str(x) for x in args if (x is not None) and (len(str(x)) > 0) ])
ae7e75abe899f13fa57fc368a362d5c4235fc429
687,262
def _max_factor(n, factor, max_size): """ Return the largest factor within the provided max; e.g., the most images of size n thet can fit in max_size """ if max_size is None or n * factor <= max_size: return factor return max_size // n
f55e68ecba5ea3f47b7c644ab8e81182fcec6ccf
687,263
from typing import Tuple import math def get_new_coordinates(curr_x: float, curr_y: float, angle: float, speed: float) -> Tuple[float, float]: """ Works out the next x, y coordinate given the current coordinate, an angle (from the x axis in radians) and the speed (i.e distance of travel). :param curr...
17ba8f98c78ed998dc3fc325214c4bbd79ac6b31
687,264
def parse_name(ldap_entry): """Return the user's first and last name as a 2-tuple. This is messy because there's apparently no canonical field to pull the user's first and last name from and also because the user's surname field (for example) may contain a title at the end (like "Bob Smith, Assista...
7f616435128296515519bc828f8e40e33e3204f9
687,265
def move(cm, from_start, from_end, insert_pos): """ Move rows from_start - from_end to insert_pos in-place. Examples -------- >>> cm = np.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 0, 1], [2, 3, 4, 5]]) >>> move(cm, 1, 2, 0) array([[5, 6, 4, 7], [9, 0, 8, 1], [1, 2, 0, ...
0a6e8be192bddbd9771943424e189d66092e9605
687,268
import locale def decode(bytes): """ Decode and return a byte string using utf8, falling back to system's encoding if that fails. So far we only have to do this because javac is so utterly hopeless it uses CP1252 for its output on Windows instead of UTF8, even if the input encoding is specified as UT...
4794e7841b532de0472fef6676f09826119e9ae7
687,269
def evaluate_training_result(env, agent): """ Evaluates the performance of the current DQN agent by using it to play a few episodes of the game and then calculates the average reward it gets. The higher the average reward is the better the DQN agent performs. :param env: the game environment :p...
4492d7af64174483d63af610e19ac45c6c1c63a5
687,270
import re def checkBadFormat(pattern, id): """ Returns False if the format looks okay, True if it's not a match """ if (id == id): if re.match(pattern, id): return(False) else: return(True)
e3a7469817bb5428b02b9d33bc27d219cd618f06
687,271
def always_https(url): """ ensures that urls are always using HTTPS :param url: An URL (as string) :type url: str :return: The passed in URL with HTTPS :rtrype: str """ if not url.startswith('http'): return url elif url.startswith('https'): return url else: ...
033797fcf125d5dc5b47f133ae42ed47c238b9ca
687,272
def _write_cell_error(worksheet, row, col, cell_error, format=None): """Handler for xlsxwriter to write a CellError.""" return worksheet.write_string(row, col, str(cell_error), format)
37cd341ffc1ea47d3e746418457e140380940985
687,274
def get_default_living(rows, cols): """If number of intitial living cells is not specified for the game, calculate as a function of grid size.""" return round((rows * cols) / 4)
d9df2d820ab823f5ff9b675d3dc96bc8927bb2e5
687,275
def convert_temperature(val, old_scale="fahrenheit", new_scale="celsius"): """ Convert from a temperatuure scale to another one among Celsius, Kelvin and Fahrenheit. Parameters ---------- val: float or int Value of the temperature to be converted expressed in the original scale....
101725753efab755a78f77b96d74b5736e2ef21f
687,276
import numpy def get_minimum_nside_pixarea(pixarea): """Returns the minimum nside needed to achieve a certain pixel resolution. Parameters ---------- pixarea : float The pixel area in square degrees. Returns ------- nside : int The minimum nside that guarantees a pixel si...
ecdd1bafa72d3c8d32c413bd9546b064034a0e16
687,277
def percent(num, div, prec=2): """ Returns the percentage of num/div as float Args: num (int): numerator div (int): divisor prec (None, int): rounding precision Returns: p (float) p = 100 * num/div """ num = float(num) div = float(div) if div...
f8de7cb8a02ea3805774e0b7cc27086107f36a71
687,278
def slurp(path): """Returns the contents of the file at the given path.""" f = None try: f = open(path) return f.read() finally: if f: f.close()
d4ee16a0535d47f33bfe5c9480aed176cb928e46
687,279
def get_paralogs_data(paral_file): """Extract paralogous projections.""" if paral_file is None: return set() paral_proj = [] with open(paral_file, "r") as f: paral_proj = set(x.rstrip() for x in f.readlines()) return paral_proj
343e344b91a55b651d3177fa6d66f99e7291364d
687,280
import zipfile def compare_usdz_content(golden_path, test_path): """Returns true if usdz content matches.""" with zipfile.ZipFile(golden_path) as golden_zip: with zipfile.ZipFile(test_path) as test_zip: golden_infos = golden_zip.infolist() test_infos = test_zip.infolist() if len(golden_infos...
e41c7ee46ccedbb284ca4eac1e718e91131a7889
687,281
def list2set(element): """Lists should become sets. Used as object hook in load(), especially in json.load(). Args: element: .json-element Modifies: nothing Returns: element: itself unchanged or as set if the element was a list """ for key in element: if ty...
1516169e9f67ca1052d946301752a997e3304949
687,282
def get_strs_in_cats(str_list, cats, compl=False): """ str_list is the general list of strings, usually the list of all cell names cats is a selection of strings, it is usually a list for any x in str_list, if x is part of any y (y is an element of cats) then x is chosen. Example of str_list: all th...
00267a8d9003fd164eb296af60ae342fadeb08c8
687,283
import json import requests def get_onboard_certificates(clearpass_fqdn, access_token, username): """Get all valid certificates (not revoked or expired) for user""" url = "https://{}/api/certificate".format(clearpass_fqdn) queryfilter = {'mdps_user_name': username, 'is_valid':'true'} payload = {'fil...
868bfd1537eed04194abf254e75faaccd425be03
687,284
def slice_sum(lst, begin, end): """ This takes am iterable object and does recursive sum between begin and end. :param lst: iterable object :param begin: beginning index :param end: ending index :return: begin index for list + recursive call """ if begin > end or begin > len(lst) - 1 or ...
c8e5c3f686be61a44538813c5389138a796a64e4
687,285
import time def generate_stats_table(stats: dict) -> str: """Function to generate md table with questions stats. Args: stats: Stats dict. { "category": { "title" str, "cnt": int, } } Returns: Md...
7ca93107386b353f071f2e6cf6421e77f23ac1f0
687,286
def letter_omission_gen(s, pos): """пропуск буквы""" if pos + 1 == len(s): return [] return [s[:pos] + s[pos+1:]]
f5beaf27da65e1b8b4d86f00fcb0db216ec86b36
687,287
def connex(data,K,L): """ Return the list of members of the connex component containing the elements originaly in L. Parameters: ----------- data: pandas dataframe data must contain at least one column named neighbors. K: list The list of members of the connex component so f...
a2f0faee0b6b7c3cec20451511ca7f635d22fe44
687,288
def get_variant_id(variant_dict): """Build a variant id The variant id is a string made of CHROM_POS_REF_ALT The alt field for svs needs some massage to work downstream. Args: variant_dict (dict): A variant dictionary Returns: v...
7b39b7c9003aacec3e76fd161f62d990748182ca
687,289
import random def mcpi_samples(n): """ Compute the number of points in the unit circle out of n points. """ count = 0 for i in range(n): x, y = random.random(), random.random() if x*x + y*y <= 1: count += 1 return count
c6082155e6accc773be67ba35926bf33348b6fbf
687,290
def batchify(batch): """Gather a batch of individual examples into one batch.""" questions = [ex['question'] for ex in batch] question_tokens = [ex['question_tokens'] for ex in batch] answers = [ex['answer'] for ex in batch] answer_tokens = [ex['answer_tokens'] for ex in batch] if 'answer_tokens' i...
e1e98eb03341629ffe149becb324b78ecc8566de
687,291
def lv_unpack(txt): """ Deserializes a string of the length:value format :param txt: The input string :return: a list og values """ txt = txt.strip() res = [] while txt: l, v = txt.split(":", 1) res.append(v[: int(l)]) txt = v[int(l):] return res
e0390bb200515a595e7f177404fdfa44a11b1c7f
687,292
def binding_score(seq, pwm): """Score a sequence using a PWM. Parameters ---------- seq: str pwm: Pandas.DataFrame Returns ------- float """ score = list() for pos, symbol in enumerate(seq): score.append(pwm.at[symbol, pos]) return sum(score)
81bebc1e13857b8c63a2a3eb87cd38f4f1f80723
687,293
def def_notch(): """ defaults for notch frequencies""" return [60.0, 120.0, 180.0, 240.0]
5c824e471899e60077b62c45bf36d487d5afdf0f
687,294
def solution(n): """ >>> solution(10) 2640 >>> solution(20) 41230 >>> solution(100) 25164150 """ a = sum([x**2 for x in range(n+1)]) b = sum([x for x in range(n+1)]) ** 2 return b-a
0a745e10fdb4c7db06244c1b7b563db6a23ce61d
687,296
def tmp_data_directory(tmp_path_factory): """Creates temporary directory and returns its path. """ return str(tmp_path_factory.mktemp("getdera"))
310f41de97a4401280db8cc8309725e05c3aa267
687,297
def _Mabove(dat, surf_th): """Return total gas mass above threshold density surf_th.""" surf = dat.surf M = surf.where(surf>surf_th).sum()*dat.domain['dx'][0]*dat.domain['dx'][1] return M.values[()]
30a1f71c8dac52bb2f776e9489a10061216d34e0
687,298
import re def collectd_rpm_type_from_name(log, name): """ Return Collectd type from full RPM name or RPM fname The Collectd RPM types. The RPM type is the minimum string that yum could understand and find the RPM. For example: libcollectdclient-5.11.0...rpm has a type of libcollectdclient; ...
928a4e43bc51e3aa710906f6cef2238b7c85fbfd
687,299
import string import operator def getFisrtCharThatAppearsOnce(myString): """ Get the first char that appears once in the provided string. Only alphabetic chars are considered. """ myString = "".join(myString.lower().split()) charDict = {key:[0, 0] for key in string.ascii_lowercase} for pos, char i...
1658be27cdff59378afe8c92ff3a132337cd9307
687,301
def _strip_quotes(str_q): """ Helper function to strip off the ' or " off of a string """ if str_q[0] == str_q[-1] and str_q.startswith(("'", '"')): return str_q[1:-1] return str_q
df1b3eda68e913e2fa6ec30a0f59f8d7c9ef6fa7
687,302
import math def _str(x, dtype='a', n=3): """Handles string formatting of cell data x- is the item being added dtype- is so we can index self._dtype """ if x == None : return '--' try : f=float(x) except : return str(x) if math.isnan(f) : return '--' elif m...
c31cede54a79de3b36a0c3acfc75735bc230cb2e
687,303
def inverse2d(a): """ Returns the matrix inverse of 2x2 matrix "a". :param a: The original 2x2 matrix. :return: Its matrix inverse. """ result = [[0, 0], [0, 0]] det_a = (a[1][1] * a[0][0]) - (a[0][1] * a[1][0]) for a_row in range(len(result)): for a_col in range(len(result[a_...
b99fb5627b2136d28452d0864fe210d41f3ea81c
687,304
def number2binary(v, dynamic_padding=False, padded_length=None): """ Convert an integer value to the equivalent string of 1 and 0 characters. """ s = "" while v: s = [ "0", "1" ][v & 1] + s v >>= 1 if dynamic_padding: w = 4 while w < len(s): w <<= 1 else: ...
2bf7a334f5c38be6c827254d7a3c3875b28c8a9f
687,305
import json def feature_reader(path): """ Reading the features and transforming the keys. :param path: Path to the features. :return features: Feature dictionary. """ features = json.load(open(path)) features = {int(k): [int(x) for x in v] for k, v in features.items()} return features
156dcd61878c8a713050b1ce1928827060a548ae
687,306
import random def swap(arr): """ Randomly selects some items in the iterable. """ i1 = random.randint(0, len(arr) - 1) i2 = random.randint(0, len(arr) - 1) arr[i2], arr[i1] = arr[i1], arr[i2] return arr
7747a6a08776261f22411427f6c6d54707da6f7b
687,307
def propset_dict(propset): """Turn a propset list into a dictionary PropSet is an optional attribute on ObjectContent objects that are returned by the VMware API. You can read more about these at: | http://pubs.vmware.com/vsphere-51/index.jsp | #com.vmware.wssdk.apiref.doc/ | vmo...
e2f09d123f70e93dfec1066d01733f73fad5bc5f
687,308
def strip_and_split(line): """ Helper function which saves a few lines of code elsewhere :param line: :return: """ line = line.strip().split() stripped_line = [subline.strip() for subline in line] return stripped_line
e4b395a0f33fd9fd3324eb8c62654623913f0aa1
687,309
import torch def condition_mixture(net, g, sampler=None, n_samples=1): """Get the predicted distribution of measurement conditioned on input. Parameters ---------- net : g : sampler : (Default value = None) n_samples : (Default value = 1) Returns ------- ...
6d272c29d8ae703edb5c3bf18f17c8e6a8fd409a
687,310
import os import stat def get_oct_mode(entry): """Get the permissions of an entry in octal mode. The return value is a string (ex. '0600').""" entry_stat = os.stat(entry) mode = oct(entry_stat[stat.ST_MODE] & 0o777) return mode
a89843ac46d3b50bb9e75ed0fa3be9f95f370226
687,311
def blind_mice(): """Returns the names of the three blind mice in shrek""" return ['Forder', 'Gorder', 'Horder']
a6ea4cd62b1c2bd6c161d3337494b0dccb61c764
687,313
import re def first_upper(s): """Capitalizes the first letter, leaves everything else alone""" return re.sub('([a-zA-Z])', lambda x: x.groups()[0].upper(), s, 1)
5dd8ed4d019b1b094d24f255b2e35c070701fec7
687,314
import shutil def copy_obfiles(build_dir, site_packages_path): """ Copies .obf files to build folder """ # List of .obf files (file format support), add or remove obf files accordingly obf_files = ['formats_cairo.obf', 'formats_common.obf', 'formats_compchem.obf', 'formats_misc.obf', 'fo...
fdc53f34df35f07b67aeb7a8a86161175e2dd8fa
687,315
def get_repo_information(repo_obj): """ Using the current repository, we obtain information on the repository, which includes - owner_name - repo_name Requires for there to be a remote named "origin" in the current local repo clone Returns a dict with said values. If it cannot find both, retur...
b2bcaf5cae9b90d0311d22df9e4a1d28f92f9b73
687,317