content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def rescale(data, new_min=0, new_max=1, data_min=None, data_max=None): """Rescale/normalize the data to be within the range `[new_min, new_max]` If data_min and data_max are explicitly provided, they will be used as the old min/max values instead of taken from the data. .. note:: This is same a...
0322383456cbbdb2a97cc0d65b0dc2ff70dbb99c
602,650
def key_of_min_value(d): """Returns the key in a dict d that corresponds to the minimum value of d. >>> letters = {'a': 6, 'b': 5, 'c': 4, 'd': 5} >>> min(letters) 'a' >>> key_of_min_value(letters) 'c' """ # BEGIN Question 0 return min(d, key=d.get) # END Question 0
956d901441c7d613605957f68990243663d8e955
602,652
import csv def load_site_map(path): """Load the modification site map from a file. The site map file should be a comma-separated file with six columns:: UniprotId: Uniprot ID of protein Gene: Gene name OrigRes: Original (incorrect) residue OrigPos: Original (incorrect) residu...
53c13b716b71918ba555c863dcf2576ec851fcc0
602,655
def tmpdir(tmpdir): """ This fixture returns path to temp folder. Fixture was added for py35 compatibility """ return str(tmpdir)
d7a3c9cc7c4993580e229f13f24a899a3e1b26c6
602,657
def is_numeric(s): """ Checks if a string contains a numeric value. :param s: The string to check :type s: str :rtype: bool """ try: float(s) return True except ValueError: return False
3ceeb9f7c103e97afe7e06e9849f0f1303161b6f
602,659
def intcode(input): """simulates an intcode computer with opcodes 1, 2, and 99. 1 adds the numbers at locations specified by the following two parameters. 2 multiplies the numbers at locations specified by the following two parameters. 99 stops the funtion. Args: input: a list of ints with...
476d54d44563a618efecb347a10d60ef895e647a
602,661
def check_for_ticket_price_error(price): """ Returns any error message if the ticket's price is not between 10 and 100 else if there is no errors it returns false. :param price: the ticket's price as a string :return: false if no error, else returns the error as a string message """ if floa...
bdb260dadb68b97a24ca1621cd8cb5e524a46fcd
602,662
import random def sample_without_replacement(mylist: list): """ Pick a random name from a list return the name and the list without that name Args: mylist (list): list of items to pick from Returns: name (str): random item from the list mylist_copy(list): mylist with name...
2651135632ce1e072bbba076ca96f172981dc0ad
602,663
import re def identity_normalize(identity): """Normalize an email address for use as an identity: downcase and in certain cases remove characters. This is required to secure against a type of attack involving password-resets: an example of the vulnerability is described here: https://jameshfisher...
cd983cfd6d52f7b8c923b62c370d1c6e15143141
602,666
def merge_dicts(*dict_args): """ Given any number of dictionaries, shallow copy and merge into a new dict, precedence goes to key-value pairs in latter dictionaries. Parameters ---------- **dict_args : dict Dictionary to merge Returns ------- merged_dict : str Merge...
b29abc66fb49c344e5dadeed81c5ccda5a6fbefb
602,667
def parse_wildcards(props): """Pull out the wildcard attributes from the Component props. Parameters ---------- props: dict Dictionary with {propName: propMetadata} structure Returns ------- list List of Dash valid wildcard prefixes """ list_of_valid_wildcard_attr_p...
6751e178de74748f3cbb3032888dd57850c75086
602,668
def source_object_assoc(sources, sext, oext): """! Associates sources with default objects Creates a dictionary object of which the keys are the provided source files and the values are their object file names. The default object file names are the source file names without their extension to which is app...
90d079ed9c151c6ec8b7fc3b9e04c8adf975178e
602,671
def _default_key_normalizer(key_class, request_context): """ Create a pool key out of a request context dictionary. According to RFC 3986, both the scheme and host are case-insensitive. Therefore, this function normalizes both before constructing the pool key for an HTTPS request. If you wish to ch...
2051c2fef6c004e8560f1432e889a66ceef7657d
602,674
def make_url(data, credentials): """ URL generator to get menu details from Foursquare. :param data: Information about the venue. :param credentials: Foursquare credentials. :return: Generated URL. """ url = "https://api.foursquare.com/v2/venues/{}/menu?client_id={}&client_secret={}&v=20170...
6d0d422cedddc58f1dae1067631df02b7fb9cd4d
602,675
def calculate_standard_deviation(pessimistic, optimistic): """ Calculate the standard deviation of a task. """ return round((pessimistic - optimistic) / 6, 1)
4f8aa9c2d118fc278d77fd378c8d727a1ccd5038
602,678
def transform_part(p): """ Transform a part of the id of a node. """ return p.replace('(', '').replace(')', '')
9861a2498c83ac3d8de1d218b474cc660e29ccf8
602,681
def es_base(caracter): """ Str -> Bool Ingresa un caracter, se determina si es True o False >>> es_base('A') True >>> es_base('T') True >>> es_base('C') True >>> es_base('G') True >>> es_base('AT') Traceback (most recent call last): .. ValueError: AT no...
b4b706cc87e37ae1fa5b343a384610a4aed6d130
602,682
def kmer_is_interesting(kmer, casecounts, controlcounts, case_min=5, ctrl_max=1, screen_thresh=None): """ Well, is it? Consult the k-mer's abundance in each sample to determine whether it is "interesting". It must be >= `case_min` in each of `casecounts`, and must be <= `ctr...
744e61883b34618111b479e460848fe59e325b05
602,683
def get_presets(ctx): """ Get the valid setup string presets in the current context. """ presets = {} if ctx.guild: presets.update(ctx.client.config.guilds.get(ctx.guild.id, "timer_presets") or {}) # Guild presets presets.update(ctx.client.config.users.get(ctx.author.id, "timer_presets"...
594e4724413d18db030f04b65eb48bc7f67520b5
602,685
from typing import Counter def data2counter(data): """ Turn data (list of dict) into a Counter object based on the name (column 'prenom'-'nom') """ cpt = Counter() for item in data: name = item['prenom'] + " " + item['nom'] cpt[name] += 1 return cpt
b3cd80f640eef272da855ef42487b6f328cae6e0
602,686
def join_document(json_instance): """Returns the document as a single string. json_instance: A JSON instance from DocRED dataset """ joined_sentences = [' '.join(sent) for sent in json_instance['sents']] document = ' '.join(joined_sentences) return document
7608f6c445fe45b4c8d20809ebbda374674be3c5
602,687
def get_objects(predictions: list, img_width: int, img_height: int): """Return objects with formatting and extra info.""" objects = [] decimal_places = 3 for pred in predictions: if isinstance(pred, str): # this is image class not object detection so no objects return objects ...
0a348a1431856395c0b728087026fbedb75f325b
602,690
def get_user_data(user_response): """Get the user raw response and returns the user info in context and human readable format Returns: dict. User data """ user_data = { 'ID': user_response.get('id'), 'AccountName': user_response.get('accountName'), 'AccountDomain': user_...
cf6384bb4fee654429856b39d6a504b6760fbffd
602,692
def split_bulk_file_download(bulk_file_download): """ Split the chess.com bulk download file into individual PGN files. Args: bulk_file_download (str): The chess.com bulk download data. Returns: list: A list of individual game data strings. """ return ["[Event" + item for item ...
8f0ea142b3038ce2b2630641b74fdbc033ee18ce
602,693
import collections def parse_billing_data(billing_data): """ parse the billing data and store it in a hash args: billing_data: CSV object of billing data returns: user_dict: dict, keyed by AWS ID, containing name, user total for all services, and currency currency: string, cu...
470ba2ce69dff81bc6f0ed5ced4e89c67013661d
602,695
def getCurrentCats(imagepage): """Get the categories currently on the image.""" result = [] for cat in imagepage.categories(): result.append(cat.title(withNamespace=False)) return list(set(result))
a389f75b4a0cdaf4d22df65d7f8d104084d8b2cd
602,698
def id(x): """ The id function. """ return x
43b3945dda49153f6d124c20fab5e87e2224a36b
602,699
def get_machines(dynamic_client,namespace): """Gets all of the Machine objects from the cluster from the specified namespace. """ machines = dynamic_client.resources.get(kind='Machine') return machines.get(namespace=namespace).items
1e83bd60ddfac704625e60d53e37e3b8845daf86
602,705
def zscore(df): """Row zscores a DataFrame, ignores np.nan Args: df (DataFrame): DataFrame to z-score Returns (DataFrame): Row-zscored DataFrame. """ return df.subtract(df.mean(axis=1), axis=0).divide(df.std(axis=1), axis=0)
70fbae298fd76d6c4c71dd5fedea1dfccb1a28b1
602,711
def intstrtuple(s): """Get (int, string) tuple from int:str strings.""" parts = [p.strip() for p in s.split(":", 1)] if len(parts) == 2: return int(parts[0]), parts[1] else: return None, parts[0]
eb105081762e5d48584d41c4ace5697fccb8c29e
602,715
from typing import Any import pickle def pickle_load(path: str) -> Any: """Returns the value of the given pickle file. Arguments ---------- * path: str ~ The path to the pickle file. """ pickle_file = open(path, 'rb') pickled_object = pickle.load(pickle_file) pickle_file.close() r...
6aa76ed817491db23d68b119874e90cbfaa96ad7
602,716
def count_leafnodes(d:dict) -> int: """Count the number of nodes with leaves in a nested dictionary. """ n = 0 if d: m = 0 for k,v in d.items(): if type(v) is dict: m += count_leafnodes(v) return n + max(m,1) return n
21e1507d5361ddbd1541772b7844c466f827bcc1
602,718
def fib_recursive(n: int) -> list[int]: """ Calculates the first n (0-indexed) Fibonacci numbers using recursion >>> fib_iterative(0) [0] >>> fib_iterative(1) [0, 1] >>> fib_iterative(5) [0, 1, 1, 2, 3, 5] >>> fib_iterative(10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> fib_it...
d201fa02afb932bba19420af3e99d5011ed6aee5
602,719
import time def DateInfoString( tm ): """ Given a date in seconds, return a string that contains the day of the year, the year, the day of the week, the month, and the day of the month. These are white space separated. """ return time.strftime( "%j %Y %w %m %d", time.localtime(tm) )
f43e7d19b4938812c3a038c4d98bef59b371b92e
602,720
def Z(q, *args, **kwargs): """ (q, *args, **kwargs) -> qubit Applies Z to qubit and returns the qubit to be used for having a functional like programming, but not necessary as the qubit is modified in place. """ q.Z(*args, **kwargs); return q
264e3e6743a64d67ec0b1a1f130b035192e2a861
602,724
def _linspace(start, stop, num): """Returns `num` uniformly spaced floats between `start` and `stop`.""" if num == 1: return [start] return [start + (stop - start) * i / (num - 1.0) for i in range(num)]
a5ded9cefaebce4c07f1cb789310da5cec93cca4
602,730
from typing import Optional def stricmp(a: Optional[str], b: Optional[str]) -> bool: """Case insensitive string comparison""" if a and b: return a.casefold() == b.casefold() else: return False
d21be41c6959e02f9350e8dea917ec41382cf694
602,733
def _standardize_str(s): """ Remove unnecessary spaces Ex. "abc d" -> "abc d" """ memory = [] res = "" for c in s: if c != " ": res += c memory = [] elif not memory: res += c memory.append(" ") return res
c8f9cac12b4748970395ebd213a909494f848040
602,736
from typing import Optional def compute_sif_weights(words_counter: dict, alpha: Optional[float] = 0.001) -> dict: """ A function that computes smooth inverse frequency (SIF) weights based on word frequencies. (See "Arora, S., Liang, Y., & Ma, T. (2016). A simple but tough-to-beat baseline for sentence e...
8fb566bbad55ef56c0a95797a23f4b66b18d24f0
602,741
def make_derivative(f): """Returns a function that approximates the derivative of f. Recall that f'(a) = (f(a + h) - f(a)) / h as h approaches 0. We will approximate the derivative by choosing a very small value for h. >>> square = lambda x: x*x >>> derivative = make_derivative(square) >>> res...
aac42b3df085c24eca31c4fbb97fd0758b7cbee5
602,742
from datetime import datetime def parse_to_local(datetime_utc: datetime) -> datetime: """ Parse a datetime object to local time. """ return datetime_utc.astimezone()
4704fe76335d8e02beda321b841cb1caa05469a2
602,751
import yaml def load_yaml(filename): """ Load a YAML file. Parameters ---------- filename : str The name of the file to load Returns ------- dict The contents of the file. """ with open(filename) as file: return yaml.load(file, Loader=yaml.FullLoader)
68fd38e5312049af7c41bd2bfafc3345309ff166
602,752
def removeprefix(s: str, prefix: str) -> str: """Re-implementation of Python 3.9's str.removeprefix https://docs.python.org/3/library/stdtypes.html#str.removeprefix Args: s (str): The string from which to remove the prefix prefix (str): prefix to remove Returns: str: copy of `s...
b94adeb27050c20d543d0759a65e251d175454ac
602,754
def text_to_set(text): """ Split string by new line, save the elements to a set :param text: String :return: Set with lines as elements """ set_w_items = set() list_w_items = text.split("\n") for i in list_w_items: if len(i) > 0: set_w_items.add(i) return set_w_it...
a7b6d237df2d9c882e2d4baafd89615653077241
602,757
def filename_from_url(url): """Extract and returns the filename from the url.""" return url.split("/")[-1].split("?")[0]
9964d9cded18d39955a7c41f83a803de5852efb0
602,769
import random def get_backoff_delay(retry_count, delay_max): """Calculate exponential backoff with random jitter delay.""" delay = round( min(delay_max, (2 ** retry_count)) - (random.randint(0, 1000) / 1000), 3, ) return delay
04c0a42766c02dff0905cf271dbb50105d21c6b3
602,773
import re def tsqueryWrapVal(val): """ Check if a value contains any special characters. If it does, wrap it in parenthesis. :param val: value to possible wrap in parenthesis. :return: value that has been wrapped as needed. """ if len(re.split('[&|!()]', val, 1)) > 1: return '(' ...
e433b13d28746c23e04e109a5406a3814672aa3a
602,775
def parse_args(parser, args): """Wrapper around parse_args for the parser passed in as an argument, for doing input validation""" results = parser.parse_args(args) if results.type is None: raise ValueError('Type not specified') if results.input == (None,): raise ValueError('Input files n...
48bd07900127391273377c4b5801cdbebf64d544
602,778
def hamming(text1,text2): """calculates hamming distance between 2 texts of equal length, if not equal it throws an error""" distance=0 if len(text1)!=len(text2): return "Error" else: for i in range(len(text1)): if text1[i]!=text2[i]: distance+=1 e...
72b3058d4571d4e2ca345fdfc378f1c534e016b1
602,779
def parse_keywords(query): """ Parses the string for keywords. Returns a set of keywords, which contains no duplicates. """ return set(query.lower().split())
30fad6c3f71f2a57838a0b74fa426304775844d2
602,780
def nth_percentile(values, n=0.95): """Get's the value in values that is closest to the nth percentile. For example, nth_percentile([4, 2, 1, 5], .75) would return 4. """ sorted_vals = sorted(values) ind = int(len(sorted_vals) * n) return sorted_vals[ind]
29ab9f114f96dc3ddf91643ae3249fcae3058667
602,786
def format_label_outputs(label: dict = {}) -> dict: """Take GitHub API label data and format to expected context outputs Args: label (dict): label data returned from GitHub API Returns: (dict): label object formatted to expected context outputs """ ec_object = { 'ID': label...
bd7b7dccdceb989a5cd55e85b9dc875c4269ef40
602,790
import json def get_max_time(results_file): """ Returns the max simulated time (ns) for a data file :param results_file: str The path to the json file containing the additional data from the simulation. :return: float Max simulated time (ns) """ # Simulation time additional...
93b39394df494ee31a37a8e8222743cab023afca
602,797
import typing def type_error_message(fun_name: str, param_name: str, expected: str, actual: typing.Any) -> str: """ generates error message for TypeError """ return f"In MediaComp.pictures.{fun_name}: {param_name} " +\ f"expected a {expected}, actually {type(actual)}"
2e28716e8f1a2aa0e59c92895219b6b6bd2de684
602,801
def _wrap(text, color, reset='\033[0m'): """ wrap text between color and reset, unless color is None, then return text """ if color: return '\033[%sm%s%s'%(color, text, reset) else: return text
116a5eab5af94ea05b7ef3a6a993db703ee51af6
602,807
def almost_equal(x, y, rel_tol=0, abs_tol=0): """Check if two objects are equal within certain relative and absolute tolerances. The operations abs(x + y) and abs(x - y) need to be well-defined for this function to work. :param x: first object to be compared :param y: second object to be compared ...
400e576ab0ad54f86dbc723e2a4768f0dd469622
602,809
import re def _QuoteString(s): """Quotes a string with appropriate quotes and escaping. This performs lite escaping by choosing enclosing quotation marks that would escape the least (either single or double quotes) and escaping those quotes and the backslash. Note that this does not escape newlines. If the s...
67e19b01a1613ba5dbac8d6b2bb295669b9d29f5
602,813
def _get_opt_vars(cr, case_names, var_type=None): """ Return names of vars that are part of the optimization variables in at least one of the cases. Parameters ---------- cr : CaseReader The CaseReader housing the data. case_names : Iterable of str The case_names from which the ...
fe3827dc00095ce7ce9ab6f8fdf44686a935557b
602,816
def get_accuracy(cm): """Get the accuaracy by the confusion matrix cm.""" return float(sum([cm[i][i] for i in range(len(cm))])) / float(cm.sum())
b301b1b8d21c1bfa408d1599e45d06cad311d493
602,817
def is_mark(codepoint): """Returns true for diacritical marks (combining codepoints).""" return codepoint.general_category in ("Mn", "Me", "Mc")
8fb84f7a1b39fa1ce6504a31f6cc902b2d4ab7c8
602,825
def load_genomic_CDR3_anchor_pos_and_functionality(anchor_pos_file_name): """Read anchor position and functionality from file. Parameters ---------- anchor_pos_file_name : str File name for the functionality and position of a conserved residue that defines the CDR3 region for each V or ...
f46dde4f12725218824b4888325e0fa4d791318e
602,827
def is_default_defined(index, argspec): """Returns `True` if the argument at `ìndex` of `argspec` has a default value. Otherwise returns `False`.""" arglen = len(argspec.args) if argspec.args else 0 defaultslen = len(argspec.defaults) if argspec.defaults else 0 defaults_defined = defaultslen > 0 a...
3e59192bc3dab3dc8c2b78adc34bbc8b73c99dce
602,828
def convert_event_list_to_dictionary(events): """ This function converts a list of events, which are dicts, for a collection exercise into a dictionary where the key is the name of the event and the value is the timestamp. This can aid in finding the exact event you want without having to loop through t...
dc58fdcfd1225d6531c4ea935ab6f8771e786a89
602,830
def _is_quoted(string): """ Returns whether the given string is quoted inside of a content disposition parameter. Parameters ---------- string : `str` The string to check. Returns ------- is_quoted : `bool` """ if (len(string) > 1) and (string[0] == '"') and (string...
860eeba5843275c67bee6f783ee376b059054805
602,834
from math import ceil def week_of_month(dt): """Get the week of the month for the specified date. Args: dt (Datetime): Input date Returns: wom (Integer): Week of the month of the input date """ first_day = dt.replace(day=1) dom = dt.day adjusted_dom = dom + ...
ef039684ed4f078ab91bc3458dc4a7bc6ef3fc0c
602,842
def fix_name(inp, names_used): """Append a number if an autoSql field name is duplicated. """ name = inp i = 2 while name in names_used: name = "%s%s" % (inp, i) i += 1 names_used.append(name) return name
4021512b7ff815769bdf6b30b9852c4dfd5a17ab
602,843
def is_available_command(command): """Checks if ``command`` is available in TBot commands""" available_commands = [ "/start", "/help", "/weather", "/translate", "/calculate", "/tweet", "/ocr_url", "/stop", ] if command in available_command...
8d8c4f6e776c929165e0a84178b9f70651f8e6a1
602,845
def build_header(dictobject="", version="2.3.x", fileclass="dictionary", incl_foamfile=True): """Creates the header for an OpenFOAM dictionary. Inputs are the object and version.""" txt = \ r"""/*--------------------------------*- C++ -*----------------------------------*\ | ========= ...
0bcc77a68905bc5f154a9ea4ea239e20f7a1f9e7
602,847
async def pause_(self, ctx): """Pause the currently playing song.""" vc = ctx.voice_client if not vc or not vc.is_playing(): return await ctx.send('I am not currently playing anything!', delete_after=20) elif vc.is_paused(): return vc.pause() await ctx.send(f'**`{ctx.author}`**...
47271577c1aec1176f33ec56b8285787e1609b0b
602,849
def get_user_attrs(object): """ Return the attributes of an object :param object: the object to get attributes from :return: list of attributes """ return [k for k in dir(object) if not k.startswith('__') and not k.endswith('__')]
44e1a8bcfedad46f92cd9d98f39f5797f9de15d5
602,852
def get_camel_from_snake(snake: str) -> str: """Get a camel format string from a snake format string >>> get_camel_from_snake('foo_bar_baz') 'fooBarBaz' Args: snake (str): Snake style string Returns: str: Camel style string """ return ''.join(map( lambda t: t[1].ca...
3b9c2936548867bd3474a0eb28c84b803b23cc6d
602,853
def truncate_list(l, limit): """ Replace the middle of the list `l` with '...' if `l` contains more than `limit` elements """ length = len(l) if length <= limit: return l n1 = int(limit / 2.0) n2 = limit - n1 return l[:n1] + ["..."] + l[length - n2:]
2ff61750913f64e1b37593c3fa50e246ce9e34f5
602,855
def recreate_tags_from_list(list_of_tags): """Recreate tags from a list of tuples into the Amazon Tag format. Args: list_of_tags (list): List of tuples. Basic Usage: >>> list_of_tags = [('Env', 'Development')] >>> recreate_tags_from_list(list_of_tags) [ { ...
6c61396da3116ea7ef1cdc71ce0133bb366f2672
602,857
def select(df, column_name, value): """ Intuitive way of applying filters to a dataframe Parameters ---------- column_name : name of the columns column name for the function to be applied on. value : value to filter on value(s) to select within the column Returns ------...
3058eaf3adf211fd958df3285bc7dfe8129455fb
602,861
import re def find_latest_version(versions): """ Go through the versions, sort them and find the highest number Args: versions: list, the versions to use Returns: str or None if the highest version was able to be found """ def human_keys(astr): """ Sorts keys b...
13825a10351dd35aca46af6941699df389227949
602,864
def get_token_path(token_name): """ Formats the token name into a token path. Returns: The token path """ return "tokens.{}".format(token_name)
3b758bcb57e4491bf7179a7a941a4021e9ff4576
602,865
def get_tag_details_hr(tags): """ Iterate over tags list for human readable in 'risksense-get-host-detail', 'risksense-get-app-detail' commands. if only one record found it will add blank dictionary to list to display horizontally in table. :param tags: Tags detail from the response. :return: List ...
cb8ce94551ecccca3808bd179055891eecf83b48
602,868
def is_fast_round(rnd: int, r_fast: int, r_slow: int) -> bool: """Determine if the round is fast or slow.""" remainder = rnd % (r_fast + r_slow) return remainder - r_fast < 0
ceebe241e8817d8ac560ec1f08a408aa2ee34247
602,871
def _is_lab_package(name): """Whether a package name is in the lab namespace""" return name.startswith('@jupyterlab/')
82f679d2abe6515b2f22d7867215e2c69efd84c6
602,875
def _is_sunder(name): """Returns True if a _sunder_ name, False otherwise.""" return (len(name) > 2 and name[0] == name[-1] == '_' and name[1:2] != '_' and name[-2:-1] != '_')
b79cee50290ede7b8a09abc5a9d06cea2fce5274
602,877
def get_dependency(container, dependency_cls, **match_attrs): """ Inspect ``container.dependencies`` and return the first item that is an instance of ``dependency_cls``. Optionally also require that the instance has an attribute with a particular value as given in the ``match_attrs`` kwargs. """ ...
e0b98143e096b7d183a56b69938afc628481329f
602,878
import copy def get_camera_dict_for_hashing(camera_object): """Remove some keys from `camera_object.__dict__` that are very heavy and useless for the caching functionality. Parameters ---------- camera_object : :class:`~.Camera` The camera object used in the scene Returns ------- ...
64c34e973038b86f12a76c361d964a934f193a8d
602,882
def ev_fill(decimal_part): """Pad the first decimal part with zeros, taking into account E / V codes. """ if decimal_part.startswith("V"): return "V" + decimal_part[1:].zfill(2) elif decimal_part.startswith("E"): return "E" + decimal_part[1:].zfill(3) else: return decima...
4f9e19e161538c73f414ca17ab648538eb81b4d4
602,888
from typing import Optional def is_weighted(G, edge: Optional[tuple] = None, weight: str = "weight") -> bool: """Returns True if `G` has weighted edges. NOTE: ventorized from networkx: https://networkx.org/documentation/stable/_modules/networkx/classes/function.html#is_weighted Parameters ------...
e7dd27f22a32874224b509f66f58299d093494aa
602,889
import re def check_pv_name_valid(name): """Checks that text conforms to the ISIS PV naming standard Args: name (string): The text to be checked Returns: bool : True if text conforms to standard, False otherwise """ if re.match(r"[A-Za-z0-9_]*", name) is None: return Fals...
dc4f5bd51e501c0814aa6104fe7537d25d1bc280
602,891
def int_ceil(x): """return ceiling of value should be an integer""" _int = int(x) if _int < x: return int(x + 1) else: return _int
9f9de801bb24039a6ae5e89c700b4268a73eb30b
602,893
from typing import Dict from typing import List def read_dependencies() -> Dict[str, List[str]]: """ Read the file with the dependencies and return a dictionary with repos as keys and lists of their dependencies as values. Automatically considers the lower- and upppercase, and replaces "-" with "_". ...
0ca147bf282cc27788fd8ef4292c09c2246526e0
602,895
def quadratic_limb_darkening(mu, a_ld=0., b_ld=0.): """ Define quadratic limb darkening model with two params. """ return 1. - a_ld * (1. - mu) - b_ld * (1. - mu)**2
e8285416689120b999276bad7cdb4a343ebd8594
602,897
import torch def replace_masked_values(tensor: torch.Tensor, mask: torch.Tensor, replace_with: float) -> torch.Tensor: """ Replaces all masked values in ``tensor`` with ``replace_with``. ``mask`` must be broadcastable to the same shape as ``tensor``. We require that ``tensor.dim() == mask.dim()``, as oth...
eee3be2d07f44bfe93ff5ee03807ff373effee68
602,899
import pickle def load(filename): """ Loads in a saved instance of the SunXspex class. Parameters ---------- filename : str Filename for the pickled fitting class. Returns ------- Loaded in fitting class. """ with open(filename, 'rb') as f: loaded = pickle.loa...
6cc32b68ccb588d66bb072d0a3587dd82bcbe489
602,903
def quintic_easeinout(pos): """ Easing function for animations: Quintic Ease In & Out """ if pos < 0.5: return 16 * pos * pos * pos * pos * pos fos = (2 * pos) - 2 return 0.5 * fos * fos * fos * fos * fos + 1
56a11d46618af50123c910bc482e44f21f00a86c
602,906
def globalize_path(string: str, project_directory: str, ) -> str: """ Rebase an absolute file path on the current project path. Useful when restarting an ARC project in a different folder or on a different machine. Args: string (str): A string containing a ...
40d25751e40ef35885bff45967637f8ddffba2b6
602,907
def parse_app(app): """ >>> parse_app(None) '' >>> parse_app({}) '' >>> parse_app({'name': 'esteem'}) 'esteem' >>> parse_app({'version': 2}) '' >>> parse_app({'name': 'esteem', 'version': 2}) 'esteem 2' >>> parse_app('esteem 1.1.1') 'esteem 1.1.1' """ ...
66842ce07fbedf29f531365605c99735c98af49d
602,908
def _get_label_object_ids(label): """Returns a list of all object IDs contained in the label. Args: label: an ImageLabel instance Returns: list of IDs as strings """ list_field_name = type(label).__name__.lower() if hasattr(label, "id"): return [label.id] elif list_...
372e650d122949ab7b2a911247bc0dc2484abe64
602,909
def cox_ph_loss_sorted(log_h, event, eps=1e-7): """Requires the input to be sorted by descending duration time. See DatasetDurationSorted. We calculate the negative log of $(\frac{h_i}{\sum_{j \in R_i} h_j})^d$, where h = exp(log_h) are the hazards and R is the risk set, and d is event. We just co...
a92fa713313e594a7fd34952a75b729a42350826
602,912
def remove_existing_files(zip_files, existing_zip_files): """Removes entries in <zip_files> that exist in <existing_zip_files>.""" return [zip_file for zip_file in zip_files if zip_file not in existing_zip_files]
92cef10f6f174111f4087f5ee403513c7dc20a75
602,913
from typing import Tuple import re def split_package_version(package: str) -> Tuple[str, ...]: """Split the package which maybe contains version info. Args: package (str): Name of package to split. Example: >>> split_package_version('mmcls') 'mmcls', '' >>> split_package_...
7edac6f5b50c7be4aaa6d9418d88f52d1aebb0e6
602,919
def render_int(n): """ Renders an int in the shortest possible form. When packing the height into the coinbase script, the integer representing the height must be encoded in the shortest possible manner. See: https://bitcoin.org/en/developer-reference#coinbase. Args: n (int): number to be ...
6dd39c6ee77b335bf353bbd5fb16982769e9960c
602,920
import json def load_from_json(filepath): """ Load json file from filepath into a dictionary :param filepath: :return: python dictionary """ data = dict() with open(filepath) as data_file: data = json.load(data_file) return data
4943a9719feac01f42000ea3f4b2f2240ad8acaa
602,921
def out_upload_path(instance, filename): """ Function to return upload path for test case output file""" return "/".join(["testcases", str(instance.problem.id)]) + ".out"
cc7e6cda36753dca8593d5e6f80deacd4414c287
602,922