content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def powerset(lst): """typically L=['one', 'two'] - return list of lists """ if lst == []: return [[]] #return empty list of list lose_it = powerset(lst[1:]) #lost the first element in the list use_it = map(lambda x: [lst[0]] + x, lose_it) #add the first element to the lose_it return...
923fd3aea67e42ef3f1222894aa72c666e675d25
646,640
def get_fields_that_differ(model, obj1, obj2): """Returns the fields that differ when comparing two instances of the same model.""" if type(obj1) == type(obj2): field_names = [f.name for f in model._meta.get_fields() if not f.unique] fields_that_differ = [f for f in ...
3a2b7da45700ff26d6b3e23542145523e36ead45
646,641
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
import pickle def read_analysis_files(pathnames): """Reads in simulation analysis files (as produced by pathsim_analysis.py). Returns list of start times, end times, and statistics.""" start_time = None end_time = None compromise_stats = [] for pathname in pathnames: with open(pat...
ba3529a3b45bd20c0d3dc7e4243620a7f2c510ab
646,645
import socket def _canonicalize_hostname(hostname): """Canonicalize hostname following MIT-krb5 behavior.""" # https://github.com/krb5/krb5/blob/d406afa363554097ac48646a29249c04f498c88e/src/util/k5test.py#L505-L520 af, socktype, proto, canonname, sockaddr = socket.getaddrinfo( hostname, None, 0, 0...
3d8bf992e820292112e07aa03b1d1c98dc85c93b
646,646
def drop_na_rows_from_datum(datum): """Drops rows from the pandas dataframe where all values are NA.""" datum_size = len(datum) datum_type = datum['Type'][0] dropped_datum = datum.dropna(axis=0, how='all') dropped_datum_size = len(dropped_datum) print(str(datum_size - dropped_datum_size) + " ro...
a82cc5a43a3e6e7ea5ef8b467e1601ea281386b9
646,647
import time def timeit(callback, message): """Measure the time taken to execute a function. This function measures the amount of time it takes to execute the specified callback and prints a message afterwards regarding the time taken. The `message` parameter provides part of the message, e.g. if ...
093e53859132651113830733d034ee69be736488
646,649
def build_answers_dict(selector, answers): """ cc.license uses a dict form of the answers xml. This function converts the xml string `answers` into a python dict. """ answers_dict = {} questions = answers.xpath('/answers/license-%s' % selector.id)[0] for field in selector.questions()...
a82e3d2ac8b8b7177787eaee600dfd6340f6091c
646,650
def transcode_file(filename): """Input injection""" command = 'ffmpeg -i "{source}" output_file.mpg'.format(source=filename) return command # a bad idea!
e34ccd0f3d5aeac5f5cd92bc788ccf152262ea94
646,651
def indexOfShortestString(listOfStrings): """ return index of shortest string from a non-empty list of strings, False otherwise By "shortest", we mean a value that is no longer than any other value in the list There may be more than one string that would qualify, For example in the list ["dog","...
d525d118e499c8da6b6a82cd06c6b43290120a5b
646,653
import yaml def read_config_file(file_name): """Setup config parameters Read and store configuration parameters from given config file """ with open(file_name) as config_file: config_values = {} config = yaml.safe_load(config_file) # get values from yaml config_va...
f242fbfce7e2b59d3fa9a8129ca73bb56bde170e
646,654
import re def build_filter(pattern): """Function to return a filter function for scan_directories Parameters ---------- pattern : str Regex pattern to match Returns ------- function : a filter which returns true when a file matching the pattern is present ...
7d0543276f0bbadba15441f4dfe2c8363f664b65
646,655
from datetime import datetime def parse_date(date_string): """ Dates from cli are expected as yyyy-mm-dd """ if not date_string: return None year, month, day = map(int, date_string.split('-')) return datetime(year, month, day)
7ebc9200aee21a9d59b25a96333722d3fb17e700
646,656
def rearrange_pandasdf_columns(df): """ Takes a pandas Dataframe with columns 'DateTime' and 'WorkerIndex' amongst others and places them at the front :param df: The pandas Dataframe :return: The column rearranged df """ new_columns = ['DateTime', 'WorkerIndex'] for c in df.columns: ...
799f65fa8cdc0285e285865d9ed1823d0f802321
646,657
def compare_flavors(flavor_item): """ Helper function for sorting flavors. Sorting order: Flavors with lower resources first. Resource importance order: GPUs, CPUs, RAM, Disk, Ephemeral. :param flavor_item: :return: """ return ( flavor_item.get("Properties", {}).get("Accelerato...
a0e167ee1c7a4f93cc3533064a801b1a29211b7d
646,658
import json def process_config(json_file): """Load configuration as a python dictionary. Args: json_file (str): Path to the JSON file. Returns: dict: """ # parse the configurations from the config json file provided with open(json_file, 'r') as config_file: co...
2190525330bb319547fa143ea9e78bbddf052ffa
646,660
import copy def _deepcopy(x, memo: dict): """deepcopy a regular class instance""" cls = x.__class__ result = cls.__new__(cls) memo[id(x)] = result for k, v in x.__dict__.items(): setattr(result, k, copy.deepcopy(v, memo)) return result
5b84d21c22f477620347ffc6e62e73fb256c1f63
646,661
import inspect def _filter_class_attributes(path, parent, children): """Filter out class attirubtes that are part of the PTransform API.""" del path skip_class_attributes = { "expand", "label", "from_runner_api", "register_urn", "side_inputs" } if inspect.isclass(parent): children = [(name, child)...
b9911c076dc7aafcfbda0f7dcf197982ed8067a3
646,662
def recur_fibonacci(k): """ Find the Fibonacci number of order n by recursion """ if k < 2: return k else: return recur_fibonacci(k - 1) + recur_fibonacci(k - 2)
3c0e6a08061da4e563b60c36f41e742da470b454
646,664
def make_list(arg): """Return a list with arg as its member or arg if arg is already a list. Returns an empty list if arg is None""" return (arg if isinstance(arg, list) else ([arg] if arg is not None else []))
d3663fb45d6dbf1b82508eaebac04afc48b7a6f4
646,665
def is_hex( data, length=0 ): """妥当な16進数かどうかをチェック 引数: data (str):チェックする文字列 length (int) = 0: 指定すると長さチェックも行う 戻り値: True/False """ if length: if len(data) != length: return False for ch in data: if not ch in '0123456789ABCDEF': return ...
5de9d0068db5e28a821a840f98a443829df7fb30
646,666
from datetime import datetime import pytz def ns_to_datetime(ns): """ Converts nanoseconds to a datetime object (UTC) Parameters ---------- ns : int nanoseconds since epoch Returns ------- nanoseconds since epoch as a datetime object : datetime """ dt = datetime.utcf...
8e70e06b01add515147e267c2490b552567afb09
646,667
import os def _install_git_lfs_on_linux_on_the_fly() -> str: """ A dirty hack as there is no clean way how to install git lfs on Read the Docs at the moment. """ _git_lfs_cmd = "./git-lfs" if os.path.isfile(_git_lfs_cmd): return _git_lfs_cmd os.system("echo 'Installing git-lfs on-the-...
99b71c077a4013cfaa3f71ca16bfd58568110efc
646,668
def get_total_ramp_rate_violation(model): """Total ramp rate violation""" ramp_up = sum(v.value for v in model.V_CV_TRADER_RAMP_UP.values()) ramp_dn = sum(v.value for v in model.V_CV_TRADER_RAMP_DOWN.values()) return ramp_up + ramp_dn
d0b7a7df22534f9a18f164a7c4ab27de7d7af577
646,669
import os def ispackage(path: str) -> bool: """Guess whether a path refers to a package directory.""" if os.path.isdir(path): for ext in (".py", ".pyc"): if os.path.isfile(os.path.join(path, "__init__" + ext)): return True return False
1bbc996db2af30bd8afae55c2ae9166344160b4f
646,670
def single_byte_xor(hex_string, single_byte: int) -> str: """XOR the hex_string with a single byte.""" return "".join((chr(letter ^ single_byte) for letter in bytes.fromhex(hex_string)))
5c0d6d7128e6d38d19515d45bdc02877bcddd0df
646,672
def _readSPARQLQuery(filename): """Read a SPARQL query from file and return the content as a string.""" content = "" with open(filename, 'r') as reader: content = reader.read() return content
6af37a844b1839c851fb686793e8b5ba2b0b12ae
646,673
def a_function(): """Обычная функция""" return "1+1"
98f8893d622107d166757dabafd20c8ede66d52a
646,674
import itertools def split_escaped_whitespace(text): """ Split `text` on escaped whitespace (null+space or null+newline). Return a list of strings. """ strings = text.split('\x00 ') strings = [string.split('\x00\n') for string in strings] # flatten list of lists of strings to list of strin...
32976934ae41b927ac9c5ed3b202881f0d2bc9e7
646,675
import os import fnmatch def find_files(path,extension): """ Find files with the given extension under the given path. :param path: base path :type path: string :param extension: file extension :type extension: string :return: paths to the files with the provided extension under the given path :rtype:...
d77dc9a6a233470c21fef945e8b5a08d729606cd
646,676
import numpy def distance_matrix(points): """return NxN point to point distance matrix this works but is not needed for USR """ points = numpy.array(points) num, dim = points.shape delta = numpy.zeros((num,num), 'd') for d in range(dim): data = points[:,d] delta += (data - ...
48574535a099e32fd6bb4100836d7b1b3cbbb31a
646,677
def get_seqrc(sequence): """ :param sequence: :return: """ rcmap = {'A': 'T', 'a': 't', 'C': 'G', 'c': 'g', 'G': 'C', 'g': 'c', 'T': 'A', 't': 'a', 'N': 'N', 'n': 'n'} return ''.join(map(lambda x: rcmap[x], reversed(list(sequence))))
a1af5221018d17f518fee45ba2e7b7b3f1e7f17d
646,678
def split_title(title, delim): """Return largest title piece.""" largest_len = 0 largest_piece = None piece_len = 0 for piece in title.split(delim): piece_len = len(piece) if piece_len > largest_len: largest_len = piece_len largest_piece = piece return la...
4af6003d5d74299920f5c544be888c788654b50c
646,679
def find_opt_pars(path_optpars, read_length): """ Read in optimal parameters for each family at given read length Returns optpars[fam_id] = [min_cov, max_aaid, min_score, aln_stat] """ optpars = {} with open(path_optpars) as f_in: next(f_in) for line in f_in: fam_id, ...
59e94e959aae72e620baa7d320aa7ee9187304b9
646,680
import os def get_version(project_dir): """ This function read the VERSION file in the project_dir project then returns the version (str) of the project. Parameters: - project_dir: str, path to the project_dir project Returns: str, version extracted from $PROJECT_DIR/VERSION or None ...
92a9bdb73df6bacb794a86f49c190e33abc3d307
646,681
def halfwidth_to_fullwidth(half_text: str): """ 半角数字を全角数字に置換する Parameters ---------- half_text : str 対象の文字列 Returns ------- full_text : str 置換された文字列 """ halfwidths = '0123456789' fullwidths = '0123456789' half_to_full_dict = dict(zip(halfwidths, fullwid...
082035dade4498435451802bd452be8bb3422d65
646,683
import re def axes_from_cmd(cmd, alt_names=None): """ Get axes name from command string :param cmd: str :param alt_names: dict {name_in_cmd: name_in_file} :return: str """ alt_names = {} if alt_names is None else alt_names cmd = cmd.split() axes = cmd[1] if axes in alt_names: ...
443acce54aaec1f9bf1fda3031464bcc1566399e
646,684
def most_relevant_tags(mesh, n_tags=30, entities=False): """This method needs work - current heuristics remain flawed.""" concept_avgs = [ {"name": concept, "relevance": mesh.graph.nodes[concept]["score"]} for concept in mesh.concept_cache.keys() ] if entities: # only return entities ...
da458edcb6f15eb208b9a1f81bdbc1e514ff4ccd
646,685
from typing import Optional import pathlib import os def which(program: str) -> Optional[pathlib.Path]: """Locate a command on the filesystem.""" for path in os.environ["PATH"].split(os.pathsep): dirname = pathlib.Path(path) fpath = dirname / program if os.access(fpath, os.X_OK): ...
35bf9b0030de47910944985e5f4384aebfa898ed
646,686
def level_states_full_space(level, dimension): """ Creates a list of all states in ``level``. Parameters ---------- level : int Level of the state space. dimension : int Number of clonotypes. Returns ------- state_list : list List of all states in level. ...
2796b6f00c9a1ffd5ffa4f42cf49f5b1cc7c1053
646,687
import re def Extract_Numbers(string): """Function to extract the individual numbers form within a string """ List = [int(s) for s in re.findall(r'\d+', string)] # Pythonic language for obtaining the integers that may appear in a string return List # Return the list of integers. Remianin...
c15b7374bc6f0655df503f461bc8af2477949bfc
646,688
import os def macro_has_matching_test_model(macro): """ checks tha there is a matching test model for a given macro. """ return os.path.exists(macro.expected_model)
cf1da5b11b43812419c13c44cb2e5aaacd652d04
646,689
def read_group_string(experiment_sample): """ Generate a SAM header string for the read group. Passed to bwa with escaped tabs. """ read_group_fields = [ '@RG', 'ID:'+experiment_sample.uid, 'PL:illumina', 'PU:'+experiment_sample.uid, 'LB:'+...
2c51e599ade513990a834d701b606cf7b444daba
646,690
def guess_n_initial_points(params): #96 (line num in coconut source) """Guess a good value for n_initial_points given params.""" #97 (line num in coconut source) return max(len(params), min(len(params) * 2, 10))
bceea596c4793a1f87cf5ac01398fe051b98b5e7
646,691
import logging def ping(reply, cfg) -> str: """ Replies to the !ping command, and is used as a keep alive check :param reply: Message object :param cfg: See reply param :return: The ping string, which in turn is given to Reddit's reply.reply() """ logging.info(f"Received ping from {reply.a...
fdd8a2f92f9059a40d351993ab9d718ef20fbfe7
646,692
def unwanted_elements_remover(input_list): """Function to loop to traverse each element in list and, remove elements which are equals to the del items""" item_list = input_list # elements to be removed to be removed del_item1 = 'a' del_item2 = ';' del_item3 = ',' i=0 #loop counter lengt...
a0e64c694c6630a8ce26e9c4751f38b4392478f0
646,693
from typing import Any from typing import Dict import attr def instantiate_attrs_with_extra_kwargs( cls: Any, **kwargs: Dict[str, Any] ): """Return ``cls`` instantiated with ``kwargs`` ignoring extra kwargs. Parameters ---------- cls : Object An object that has been decorated ...
b8e7dbabea1fe6100e3601bb99014221043a2267
646,694
import math def warm_cos_lr(lr, total_iters, warmup_total_iters, warmup_lr_start, iters): """Cosine learning rate with warm up.""" if iters <= warmup_total_iters: lr = (lr - warmup_lr_start) * iters / float( warmup_total_iters ) + warmup_lr_start else: lr *= 0.5 * ( ...
d9830d0629604fd04e45d5554074168b61c989e6
646,696
def flip(xy): """ :param xy: A tuple of pair items >>> flip((1, 2)) (2, 1) """ (x, y) = xy return (y, x)
2a213f502fd2cad2c04d5c05bc35969f48c01b9a
646,697
def get_domain(event): """Return the domain that will display the new policy.""" if event['headers'] is None: return "https://testinvocation/approve" if 'amazonaws.com' in event['headers']['Host']: return "https://{domain}/{stage}/".format( domain=event['headers']['Host'], ...
dbf122fd949c5855a2a205c92352dadbac73ba5c
646,698
import os def make_full_directory(directory): """Create all directories to the given path if they do not exist""" if not os.path.isfile(directory): if not os.path.exists(directory): # Create the path to the model if it does not exist os.makedirs(directory) return True ...
4c1806a113f09b5ef4a8ef185eb4ee0df7fb5298
646,699
import base64 import json def serialize(obj: object) -> str: """ Serializes a given object. It will find all the attributes of the class that don't start with '__' and returns a base64 encoded json string. """ final_dict = {} for attr in dir(obj): if not attr.startswith("__") and n...
eecc7016daca6b7f37bd16aa81b4d23bdff34abb
646,700
import pickle def loadData(file_model): """ Load object from (pk) dump file :param file_model: object file :return: reconstructed object file """ object_file = None try: object_file = open(file_model, 'rb') object_model = pickle.load(object_file) object_file.close()...
5715e6343b0ab12370ce3821089d3dc9f4b150a1
646,701
def dataset_len(tf_dataset, verbose=False): """ Compute the length of a TF dataset. """ tot = 0 for data, _ in tf_dataset.batch(128): tot += data.shape[0] if verbose: print('.', end='') if verbose: print(flush=True) return tot
1db2b4d474716633530bebecd6eeb450b3aa6b87
646,702
def test(arg: str) -> bool: """Hello >>> 1 + 13 14 :param arg: An argument :return: Return the resulting value """ return arg == 'foo'
16d7e830690b8a7a7cac2f641fc2087a9aabb7b7
646,703
from typing import List def argmax(array: List[float]) -> int: """Simple argmax implementation for lists of floats.""" index, value = max(enumerate(array), key=lambda x: x[1]) return index
30ac274ff31c8e0da83d07cca9d48c17a1d08b2c
646,704
def check_exists(connection, path): """Check the file path in the SQL filepaths table. :param connection: :param path: :return: path id""" exists = '''SELECT EXISTS(SELECT 1 FROM filepaths WHERE filepath = ?);''' cursor = connection.cursor() cursor.execute(exists, (path,)) return cursor.fetchone()
2a7aab7ab36b644db9a5efbe2aa847a8f7fd7487
646,705
def _round_to_interval(time, interval): """ :param time: in us :return: time in us rounded to the earliest interval """ return time - time % interval
62bdd9a1ea5e7466c8effca9443c004c5c8423f9
646,706
def BMI_calculator(weight, height): """ Function to calculate the BMI of an individual given their respective weight (lb) and height (in)""" # Calculate BMI using lb / inches equation bmi = ((weight)/(height * height)) * 703 return bmi
610af23be46bb16ad28a1ba6bec4048ad67e9083
646,707
def _extract_spotinst_access_token(definition: dict): """ extract the provided access token """ return definition["Mappings"]["Senza"]["Info"]["SpotinstAccessToken"]
90e0935a5180199c87d2ddc5fcec8eee05116348
646,709
import uuid def create_id() -> str: # pragma: no cover """Creates an uuid.""" return str(uuid.uuid4())
a22df1382bc2da7d730aed6e9131301749720919
646,710
def cleanOptions(options): """ Takes an options dict and returns a tuple containing the daemonize boolean, the reload boolean, and the parsed list of cleaned options as would be expected to be passed to hx """ _reload = options.pop('reload') dev = options.pop('dev') opts = [] store_t...
8586836d03f1c0fed2d0a72a0ddfb751cb3d4b24
646,711
import pkg_resources def _load_entry_point(ep_name, name=None): """Try to load the entry point ep_name that matches name.""" for ep in pkg_resources.iter_entry_points(ep_name, name=name): try: return ep.load() except (ImportError, pkg_resources.UnknownExtra, AttributeError): ...
24b2148c489a3c9efb7af43faee3b314e628d0cf
646,712
def ReadFileAsLines(filename): """Reads a file, removing blank lines and lines that start with #""" file = open(filename, "r") raw_lines = file.readlines() file.close() lines = [] for line in raw_lines: line = line.strip() if len(line) > 0 and not line.startswith("#"): lines.append(line) ret...
ff4ed7f4a380e0b80d8c1353483a509906dfd47e
646,713
def empty_copy(obj): """Return an empty instance of obj's class.""" class Empty(obj.__class__): def __init__(self): pass newcopy = Empty() newcopy.__class__ = obj.__class__ return newcopy
61d0f938fefde9d192a559d83574967d5fcd2b91
646,714
def _formula_str(formula, sep='&'): """Returns a representation of 'formula' for prettyprinting""" next_sep = '|' if sep == '&' else '&' items = [item if (type(item) == str) else _formula_str(item, next_sep) for item in formula] return '({0})'.format(' {0} '.format(sep).join(items))
2cd33343ef16172f898da130cd59deaffcd0e76a
646,715
from typing import List def as_list(ans: str, sep: str = ",") -> List[str]: """ Spits answer into list according to separator """ items = ans.strip().split(sep) items = map(str.strip, items) return list(items)
c9607856762064fbeeaea668e05cff51d7684d61
646,716
def _parse_session(session): """Return a request mapping for a notification from the given session.""" return dict( (str(k), str(v)) for (k, v) in session.items() )
213e582cdb9ec5a0a3297ed11cd57dc91dcea2c4
646,718
def cryptography_pub_key_decrypt(enctext, private_key, pad): """Decrypt data that were encrypted using the cryptography library. Returns a byte array of deciphered data that is equivalent to the data that were passed to the original encryption operation. Keyword arguments: enctext -- A list of pub...
e406cec11e0648d06ff40146fb61847d5571360c
646,719
def empty(level): """ To generate empty space needed for shaping the tree""" s = "" for x in range(level): s += " " return s
a312865a038d51fa3a9885f94b1f9c1926b172fc
646,720
def get_all_teams(): """Returns all teams""" allteams = { "ANA": "Anaheim Ducks", "ARI": "Arizona Coyotes", "BOS": "Boston Bruins", "BUF": "Buffalo Sabres", "CAR": "Carolina Hurricanes", "CBJ": "Columbus Blue Jackets", "CGY": "Calgary Flames", "CH...
a7d81b117524943f55e2d7c66a9f8de33e04c789
646,721
def export_by_name(template_name, nb, config=None, transformers=None, filters=None): """ Export a notebook object to a template type by its name. Reflection (Inspect) is used to find the template's corresponding explicit export method defined in this module. That method is then called directly. ...
a5d0843e24ff78f96fd4614e757c3c20b7c35897
646,722
def is_python_file(filename): """ Return whether a file is a Python file or not """ return filename.endswith('.py')
6f4b64a0c71afa3afe610f0aa014e526c6db77c7
646,723
def partition(message): """ Takes in a decoded message (presumably passed through prepare()) and returns a list of all contained messages. The messages are strings Example: >>> partition("5 Hello6 World!") ['Hello', 'World!'] """ messages = [] while len(message) > 0: ...
1d6c6b32052924b7862d579f5baae8bf8285c03c
646,724
def _date_long_form(date): """ Displays a date in long form, eg 'Monday 29th April 2019'. """ second_last = (date.day // 10) % 10 last = date.day % 10 if second_last != 1 and last == 1: ordinal = "st" elif second_last != 1 and last == 2: ordinal = "nd" elif second_last != 1 and l...
248cdaaba72e6252d6fdcec6499a4332e50a85c9
646,725
def formatta(str): """ @input str è della forma "frase."Autore Mi interessa estrarre solo la frase """ pezzi = str.split('.') prima_parte = pezzi[0] frase = prima_parte[1:] return frase
4f7c1a7a374cf29530332e2101d0fe688992f002
646,726
import torch def pairwise_dist(x, y=None, sqrt=False): """ Args: x: (n_pts, ndim) y: if None, set to be x Returns: dist: (n_pts, n_pts) """ if y is None: y = x dist = (x*x).sum(1, keepdim=True) + (y*y).sum(1) - 2*torch.mm(x, y.T) dist[dist<...
800131744df65c0024e358e30f69cb981d8d522c
646,727
def _seconds_and_microseconds(timestamp): """ Split a floating point timestamp into an integer number of seconds since the epoch, and an integer number of microseconds (having rounded to the nearest microsecond). If `_seconds_and_microseconds(x) = (y, z)` then the following holds (up to the err...
5776932c2c2eb1e155c47cb7ca07c34933439f15
646,729
from numpy import asarray def trim_to_range(data, xmin=None, xmax=None, **kwargs): """ Removes elements of the data that are above xmin or below xmax (if present) """ data = asarray(data) if xmin: data = data[data >= xmin] if xmax: data = data[data <= xmax] return data
4687898619560eeed5143dac2fe7c5760a0162e0
646,730
def _requestLink__CMORvar(self,rql=None,pmax=None): """Return set of CMORvar item identifiers for CMORvar linked to this requestLink, or to set of requestlinks in argument rql: pmax: maximum variable priority: if set, only return variables requested with priority <= pmax; rql: set of requestLink...
8f0a5906894c218d6ad6abe1d7b08e8af503eb3d
646,731
def _is_external(p): """Checks if the string starts with ../""" return p[0:3] == '../'
4e80683d6e84c2ada4d32e69aa6513df680a1616
646,732
def product_list(list_of_numbers): """z = (len(list_of_numbers))-1 contador = 0 if z > 1: while z > 0: contador = list_of_numbers[z] * list_of_numbers[z-1] list_of_numbers.pop() list_of_numbers.pop() list_of_numbers.append(contador) z = z -...
ef18095ae473df3666cd8bc7499611508a6d45a4
646,733
def cli(ctx, tool_id, io_details=False, link_details=False): """Get details of a given tool. Output: Information about the tool's interface """ return ctx.gi.tools.show_tool(tool_id, io_details=io_details, link_details=link_details)
c56943a42517d2fa5ebd6654e7af45a59fe26018
646,734
def get_centroids(vertices, entities, dim=2): """Calculate the centroids of all the entities. :param vertex: vertex coordinates of mesh :type vertex: numpy.ndarray[float64 x dim] :param entities: mesh connectivity :type entities: numpy.ndarray[int x (dim+1)] :param dim: dimension of mesh :t...
8a3dc3c64b791698d90c3de1857f6d54bbc3a697
646,735
import itertools import fnmatch def ignore_rules_for_url(spider, url): """ Returns a list of ignore rules from the given spider, that are relevant to the given URL. """ ignore_rules = getattr(spider, "pa11y_ignore_rules", {}) or {} return itertools.chain.from_iterable( rule_list ...
1f225b175cf412df063e161ef5f4c824a93e65fc
646,736
def is_space(ch): """ """ return ch == " "
3b9f7af1ac47cc9f66c6d8ae8a4dc4381fb19d04
646,737
def add_identity(axes, *line_args, **line_kwargs): """helper function for the scatter plot""" identity, = axes.plot([], [], *line_args, **line_kwargs) def callback(axes): low_x, high_x = axes.get_xlim() low_y, high_y = axes.get_ylim() low = max(low_x, low_y) high = min(high_...
68f4d990251c688bb91b8d4fcc3a2240b124a2fa
646,738
def remove_resource(admin_mc, request): """Remove a resource after a test finishes even if the test fails.""" client = admin_mc.client def _cleanup(resource): request.addfinalizer(lambda: client.delete(resource)) return _cleanup
6fd635e0906bbad96094cdba3d4cdb2dc4b97a2c
646,739
def fixture_make_queue(request, make_unique_name): """ Return a factory function that can be used to make a queue for testing. :param request: The Pytest request object that contains configuration data. :param make_unique_name: A fixture that returns a unique name. :return: The factory function to ...
90d3259e19c5a3ab828841d01d219df8c3f89a56
646,740
from datetime import datetime def convert_date(date): """Traduz datas em formato YYYYMMDD ou ano-mes-dia, ano-mes para o formato usado no banco de dados""" _date = None if "-" not in date: date = "-".join((date[:4], date[4:6], date[6:])) def limit_month_range(date): """Remove o s...
db4c5082f05faac2370480c0e4d80cf00fee5b5e
646,742
import logging def check_mass_balance(species, reaction, limit=1e-5): """Check the given reaction for their mass balance.""" mass_sum = 0.0 for spc, spc_nu in reaction.reactants.items(): mass_sum += species[spc].molar_mass * spc_nu for spc, spc_nu in reaction.products.items(): mass_s...
798eec249158bf39589a034270cf2305dda29f59
646,743
def _join_args(call, nargs=None): """ Join arguments in call together. :param call: :param nargs: dict from arguments names to how many args it takes, default 1 for all. :return: """ if not nargs: nargs = {} assert all(not k.startswith('-') for k in nargs.keys()) out = [] ...
d985fcaeab0da93b1e8687a428bd263d4f8f7858
646,744
import torch def compute_patch_error(x, y, h, w): """Compute the absolute error between patches. """ return torch.abs(x - y)[..., h // 4:-h // 4, w // 4:-w // 4].mean()
6960ab3938dfecbfce711cba0da15a830d69ed4b
646,746
import requests def aget(url, **kwargs): """ Async version of get """ return requests.get(url, **kwargs)
255be298eeb28a8b6098adb7d463330f5ae7eaf7
646,748
import torch def points_to_cartesian(batch: torch.Tensor) -> torch.Tensor: """ Transforms a batch of points in homogeneous coordinates back to cartesian coordinates. Args: batch: batch of points in homogeneous coordinates. Should be of shape BATCHSIZE x NUMPOINTS x NDIM+1 Ret...
d2acca1df5deac28c4cb415a471e1eecadc2d2a9
646,749
import csv def get_movie_list(): """ List of MCU movies to query """ movies = [] with open('movie_links.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: movies.append({ 'movie': row['name'], 'bom_id': row['bom_id'], ...
a224c038d02750acc0bcdecbac8d34f98cd18c44
646,750
def dnsamp2(x): """Downsamples by a factor 2 a 2D numpy array""" return x[::2,::2]
53faf6dd9992808b83059efeace7d3e74d69d88a
646,752
def get_view_predicates(view): """Returns the given view's predicates as list with (predicate's class name, predicate's value) pairs as items. Assumes the predicate's value is stored an attribute ``val``. """ predicates = [] for predicate in getattr(view, "__predicates__", []): if hasatt...
105881bc64a5238d6e67946f9d99f97c5b6902f8
646,753
import argparse def get_arguments(): """Get command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument('-i', '--img_path', required=True, type=str, help='Path to the input image.') return parser.parse_args()
236ae20c00a0b96a51f071b2b13bd4335e7b4f7d
646,754