content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Dict from typing import Any def occluders_too_close(occluder: Dict[str, Any], x_position: float, x_scale: float) -> bool: """Return True iff a new occluder at x_position with scale x_scale would be too close to existing occluder occluder.""" existing_scale = occluder['shows'][0]['scale'...
a7a11b9b759fa743689e96f283ab0b9b34ee754d
648,493
import re def parse_show_install(cmd_output): """ Parse output of 'show install request' :param cmd_output: an iterable of lines (str) from the command output :return: (is_complete, is_success) tuple of bool. is_complete indicates whether the request completed, is_success indicates whether...
c08af55ae1f07a0a2bf02dc86e1728ceec358c45
648,503
from typing import List def split_string(x: str, n: int) -> List[str]: """ Split string into chunks of length n """ # https://stackoverflow.com/questions/9475241/split-string-every-nth-character # noqa return [x[i:i+n] for i in range(0, len(x), n)]
f0ad8cb6208616d274ee8749fb5b4a51391b0c8d
648,504
def _is_tabular(structure): """ Determines if a PDS4 structure can be shown as a table. Tabular structures are either: (1) Tables, or (2) Arrays Parameters ---------- structure : Structure PDS4 structure to check. Returns ------- bool True if *structure...
e8dba310360e2c1c042aa3ddfe5330ce65ed7c78
648,506
def get_localized_name(name): """Returns the localizedName from the name object""" locale = "{}_{}".format( name["preferredLocale"]["language"], name["preferredLocale"]["country"] ) return name['localized'].get(locale, '')
efa32f51bf89d1f2262a225dcfb13ea3ae2fedbc
648,509
def sort_strlist(s): """Deserialise, sort, and reserialise a list of strings in the format "potato,spade,elephant" """ return ','.join(sorted(s.strip().split(',')))
94a575ba07d2d71f3c1f248fd5dbf90b1f7da3cc
648,512
def build_slack_payload(budgets, image_url): """ Builds the payload that is sent to the Slack webhook about our budget overspend. """ details = "\n".join( [f"{b.name}: {b.forecasted_spend} > {b.budget_limit}" for b in budgets] ) return { "username": "aws-budgets", "i...
314904333dd420aed9406f9078a6417ee65aa429
648,516
import re def does_not_have_bad_pairs(chars): """ It does not contain the strings ab, cd, pq, or xy, even if they are part of one of the other requirements. """ bad_pairs = ['ab', 'cd', 'pq', 'xy'] if not re.search('|'.join(bad_pairs), chars): return True return False
5057b7d3bf27604b1a845a12c30307d248ab9098
648,520
def get_attribute(t, key: str): """ Get an attribute from a given callable :param t: the callable :param key: the key, the attributes name :return: the attribute data """ return getattr(t, key)
b322382ae2273ec45e8f08b43abdfc1582fb0b4d
648,521
import math def scaling(axis_len): """Scaling of plot figure size Parameter: ---------- axis_len : int Number of rows or columns Return: ---------- scale : float scale for axis """ return 0.5/math.log10(axis_len)
4af5c0e77b7f8e66ee44df4e95848271dfbe60df
648,522
def der_order(order: int) -> str: """Return correct suffix for order. >>> der_order(1) ... "1-st" >>> der_order(4) ... "4-th" """ _suffix = ["st", "nd", "rd"] if order - 1 > 3: return f"{order}-th" else: return f"{order}-{_suffix[order - 1]}"
e073135851a8848c41fbdff75215cc0dfe3df7cd
648,524
def accuracy(output, target): """ Computes accuracy, from predicted and true labels. """ batch_size = target.size(0) _, pred = output.topk(1, 1, True, True) correct = pred.eq(target.view(-1, 1).expand_as(pred)) correct_total = correct.float().sum() return correct_total * (100.0 / batch_...
bbe07357c5d395a78553933403b220258029797e
648,525
def multicommand_get_command_short_help(self, ctx, cmd_name): """Returns the short help of a subcommand It allows MultiCommand subclasses to implement more efficient ways to provide the subcommand short help, for example by leveraging some caching. Parameters ---------- ctx : click.core.Contex...
0255615202c52f9a6ca82b12d273a97efbbee42d
648,530
def mydub(a): """Double a """ return a * 2
bf039316d510db53264ab435e5092477bd57e397
648,533
import torch def get_IoU(predictions: torch.Tensor, labels: torch.Tensor, threshold: float = 0.5): """Code inspired by https://www.kaggle.com/iezepov/fast-iou-scoring-metric-in-pytorch-and-numpy """ eps = 1e-6 # assert N x H x W if len(predictions.shape) != 3: predictions.unsqueeze_(0)...
e0189c98a09033f4ff80cedf9b638432c272edc8
648,534
def strip_comments(line: str) -> str: """Remove comments from line""" # comment at the beginning of the line if line.startswith("#"): return "" # in-line comment left = line.rsplit("#", 1)[0] # be sure we are not inside a string if left.count('"') % 2 == 0 and left.count("'") % 2 ==...
bdefd26b2822e6126a7633ed9b954936d7660094
648,535
def get_alphabet_mapping(filename): """ Given a filename, return a 2D list of [alphabet1, alphabet2] representing two alphabet list mappings """ with open(filename) as data: res = [] for line in data.read().splitlines(): alphabet = [] for letter in line: ...
b3b007184b4849ce07097974d5e136f7adffc4dd
648,536
def HMStime(s): """ Given the time in seconds, an appropriately formatted string. """ if s<60.: return '%.3f s'%s elif s<3600.: return '%d:%.3f'%(int(s/60%60),s%60) else: return '%d:%d:%.3f'%(int(s/3600),int(s/60%60),s%60)
bb8f86084bc6a6473d4775d48439061f17c44000
648,537
import collections def unique2lists(list1, list2, add=False): """Unique list1 and list2 based on list1 Args: list1(list): list2(list): add(Optional(bool)): add list2 elements with list1 duplicates Returns: list,list """ if add: cntr = collections.Counter() ...
5f0fb90498339f6115b083a06fddf01385544be8
648,538
def format_ISO_time(year,doy,timestr): """ Format an ISO-like time string: YYYY-DDDTHH:MM @param year : 4-digit year @type year : str @param doy : 3-digit day of year @type doy : str @param timestr : HHMM @type timestr : str @return: str """ return year + '-' + doy + 'T' + timestr[0:2] + ':...
fcaf101e1253beb02480f3c5db63355981674374
648,539
import click def validate_page_size(ctx, param, value): """Ensure that a valid value for page size is chosen.""" # pylint: disable=unused-argument if value == 0: raise click.BadParameter("Page size must be non-zero or unset.", param=param) return value
e0618c5c1b880f47bd719072d18123199aa447c2
648,540
import time def log(msg): """Print string s and current time.""" t = time.localtime() current_time = time.strftime("%H:%M:%S", t) return f"{current_time} | {msg}"
1e0119a8e82f4f6db81dcda6b690c133c4d89234
648,546
def scalar(p1, p2): """Scalar product between p1 and p2""" return p1.x*p2.x + p1.y*p2.y + p1.z*p2.z
bc9437ac2d1a10f901170a8fa6984f52f99e983e
648,548
def human_list(l): """ Formats a list of strings in a human-friendly way. """ l = ["'{0}'".format(x) for x in l] if len(l) == 0: return 'nothing' elif len(l) == 1: return l[0] elif len(l) == 2: return ' and '.join(l) else: return ', '.join(l[:-1]) + ' and...
c8985459cbbd080b2471f34883d04454c6f93adf
648,551
import warnings import inspect def _get_members(*args, **kwargs): """ Same as :func:`inspect.getmembers` except that it will silence warnings, which avoids triggering deprecation warnings just because we are scanning a class """ with warnings.catch_warnings(): warnings.simplefilter(act...
ab272c18f9d689e97da0d95722eeab11d678efea
648,555
import math def test3(x, sin=math.sin): """ >>> %timeit test3(123_456) 105 µs ± 3.35 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) """ res = 1 for _ in range(1000): res += sin(x) return res
43f36f9b2e0d261c47414fdae4300b260973c400
648,556
import collections def format_int_list(int_list, delim=',', range_delim='-', delim_space=False): """ Returns a sorted range string from a list of positive integers (*int_list*). Contiguous ranges of integers are collapsed to min and max values. Reverse of :func:`parse_int_list`. Args: int...
aa18a3608b15f35f7c34d258f16ee57e152977c6
648,557
def seq2kmer(seq, k): """ Convert original sequence to kmers Arguments: seq -- str, original sequence. k -- int, kmer of length k specified. Returns: kmers -- str, kmers separated by space """ kmer = [seq[x:x+k] for x in range(len(seq)+1-k)] kmers = " ".join(kmer) ...
21cdb39f2484ad4ca4ca18f2e0c9f8fba59fd0f6
648,559
from typing import Dict from typing import Union from typing import List from typing import Any import requests def get_record_by_doi( doi: str, is_version_doi=True, query_params: Dict[str, Union[int, str]] = {"size": 1} ) -> List[Dict[str, Any]]: """Retrieve a Record from the zenodo api, where doi or concept...
5a29ae1000ae0ae1189f32040521ff51a7d4a29a
648,560
import six def _DictToMetadataMessage(message_classes, metadata_dict): """Converts a metadata dict to a Metadata message.""" message = message_classes.Metadata() if metadata_dict: for key, value in sorted(six.iteritems(metadata_dict)): message.items.append(message_classes.Metadata.ItemsValueListEntry(...
10334ffea0872ffe55ca60ac032f51003fa88a88
648,562
def set_zenodo(ctx, production): """Add Zenodo details: api urls, communities, to context object Parameters ---------- ctx: dict Click context obj to pass arguments onto sub-commands production: bool If True using production api, if False using sandbox Returns ------- c...
03a07c7d8aaac397c78bc4ed153b028bfcdbdc10
648,563
def transfer_annotations_prob(mapping_matrix, to_transfer): """ Transfer cell annotations onto space through a mapping matrix. Args: mapping_matrix (ndarray): Mapping matrix with shape (number_cells, number_spots). to_transfer (ndarray): Cell annotations matrix with shape (number_cells, numb...
65d6d3167e63c5031f4216c80622960c30a7f8f6
648,567
def s_to_min(value): """Convert seconds to minutes.""" return "{}:{:02d}".format(int(value // 60), int(value % 60))
7aa4fd1e259f288eb04a49a60db41bae3378ed01
648,569
import re def change_case(s, separator="-"): """Changes the case to snake/kebab case depending on the separator. As regexes can be confusing, I'll just go through this line by line as an example with the following string: ' Foo2Boo_barBaz bat' 1. Remove whitespaces from beginning/end. => 'Foo2Boo_ba...
544b4b1e7dbde7f19ed99831b21c2a5e4a4c01c1
648,572
import random def is_prime_prob(n, k=5): """ Returns <True> if <n> is a prime number, returns <False> otherwise. It uses a probabilistic method based on the Fermat little theorem. The probability of false positives can be reduced incresing <k>. - The probability of error when returns <True> is ze...
e6ad7a270d1ccf1aa08971a69dab8cf3c009dfca
648,573
def caseins_getattr(enum, attr): """Case-insensitive `getattr` for enumerated types.""" lower_attr_keys = list(map(lambda x: x.lower(), enum._fields)) attr_idx = lower_attr_keys.index(attr.lower()) orig_attr = enum._fields[attr_idx] return getattr(enum, orig_attr)
6c35bb7f56d0ba535ec4ca5a95b62bb8ebf94bdc
648,576
import yaml def get_configs(file="config.yaml"): """ Load project config file. Parameters ---------- file: str Filepath of config file Returns ------- config: dict A loaded config file """ if file.endswith('.yaml') or file.endswith('.yml'): try: ...
688d78fea209fd57bfaf5f4b8c2b99e76921aac8
648,577
def isgoldrushlocation(location: str) -> bool: """ checks if the provided location is a location where a goldrush can happen. :param location: the provided location :return: boolean if location is in the list of locations where a goldrush can happen. """ goldrushlocationlist = open("commands/dat...
8c068f376341c4b3c8c6ce06aa9c5b299408cefe
648,578
def separate_data(X, c1, c2): """Function for diving the dataset X into two separate classes. Input arguments: ================ X : ndarray [n_rows, n_cols] The entire dataset having 'n_rows' rows and 'n_cols' columns. c1, c2 : ndarray [4, ] The coordinates of the top left and botto...
025e07df6141951b643e5367e3d5086e7b2199dd
648,580
def determinant(q_form): """ The determinant of a tensor, given in quadratic form Parameters ---------- q_form : ndarray The quadratic form of a tensor, or an array with quadratic forms of tensors. Should be of shape (x, y, z, 3, 3) or (n, 3, 3) or (3, 3). Returns ------- ...
e69720131de7005e0e6f7aefc8d1741fc6818a8c
648,581
def get_skel(s): """Get a tuple representing an instrution skeleton. Args: s: String of chars in {0, 1, x} of the skeleton Returns: Tuple (before, length, after), where - before is the number before the mask - length is the length of x's in the mask - after is t...
c310480448e6a959cf2a68e14d19dcbadb908e18
648,582
import pickle def get_game_models(fname='models/game_regressions.pkl'): """ Load pre-trained models from pickle file """ with open(fname, 'rb') as fid: game_models = pickle.load(fid) return game_models
dc17f0a6dba91a15f41e283ca582606319c19adc
648,586
def addcss(value, arg): """ Adds a css class to a form field """ css_classes = value.field.widget.attrs.get('class', '').split(' ') if css_classes and arg not in css_classes: css_classes = '%s %s' % (css_classes, arg) return value.as_widget(attrs={'class': css_classes})
9d28ab6e18e9c3fdb6de9044c95ea3c794ffa29d
648,587
def find_clusters(unit_loc, index_clusters): """ 找到某个位置在clusters中的哪个cluster return: cluster的下标,若未找到,返回-1 """ if unit_loc in index_clusters: return index_clusters[unit_loc] return -1
ce011f8616d97afff535e98186429f16bbfd68f4
648,588
import json def load_conf_file(metadata_path): """Load the json configuration file create with the function `create_conf_file`. :param metadata_path: path to the metadata folder :type metadata_path: str Example:: result = load_conf_file('/home/romain/Downloads/irsst/metadata/') """ json_...
946b6d601769330de11bbf834526a82525981e18
648,589
def _make_pretty_extended(extended): """ Makes the extended description pretty and returns a formatted string. Otherwise, returns None. """ if extended is not None and extended.strip() != "": extended = "\n".join(map(lambda u: u.strip(), extended.split("\n"))) return "```%s```\n\n" ...
3d5828eb50e2aef488421122987fb2efec1494ed
648,592
import base64 def get_string_encoding(image_path): """ Get the base64 encoding string of the given image :param image_path: The path to the image :returns: The base64 byte string of the image """ with open(image_path, 'rb') as image: string = base64.b64encode(image.read()) s = '...
9e8465725ce06bd71d2cf47729aab5f7915cfa21
648,594
import json def add_metadata_to_table(table, metadata, key='my_metadata'): """ Add json metadata to a pyarrow.Table under a given key Notes ----- Based on: https://stackoverflow.com/a/58978449/709975 """ # convert dictionary to json representation (str object), # then convert it to a ...
c1e979a4fbf2d67b35ae4a990bf0933f2e2f7bd0
648,598
def correl(dataset): """ Function that computes the correlation matrix for a given dataset. :param dataset: Pandas dataframe :return: Correlation matrix (Pandas Dataframe) """ corr_matrix = dataset.corr().abs() return corr_matrix
5cfcf963c9d3ffee36e420332e24dedc34230142
648,602
def get_aggregate_stats_overlay_bandwidth_ne_pk_tunnels( self, ne_pk_tunnel_list: list[str], start_time: int, end_time: int, granularity: str, ) -> dict: """Get aggregate overlay bandwidth stats data filter by query parameters .. list-table:: :header-rows: 1 * - Swagger...
ca884974ec8ff1c9cc75e1826800b2f6f920ac37
648,608
def transpose(matrix): """Returns the transpose for the given matrix""" if not matrix: return [] elif matrix[0] and not isinstance(matrix[0], list): return [[elem] for elem in matrix] return list(map(list, zip(*matrix)))
1aaa19714c01bdeb5fca202ca7a34a22d3c9020a
648,611
import torch def box2corners_th(box:torch.Tensor)-> torch.Tensor: """convert box coordinate to corners Args: box (torch.Tensor): (B, N, 5) with x, y, w, h, alpha Returns: torch.Tensor: (B, N, 4, 2) corners """ B = box.size()[0] x = box[..., 0:1] y = box[..., 1:2] w = bo...
158a8970d898f869e6e514250ae10b3bb647db1c
648,613
def strip(input_str): """Strip newlines and whitespace from a string.""" return str(input_str.replace('\n', '').replace(' ', ''))
aab668a9ce531e17ab38a9a6befabdb6f85ae6b2
648,617
from pathlib import Path def rmlink_safe(linkpath: Path): """Remove the linkpath only if it is a symbolic link.""" if linkpath.is_symlink(): linkpath.unlink() if linkpath.exists(): print(f"'{linkpath}' is not a symbolic link; it will not be replaced.") return False return True
c610863a8de726e3dd7c05d2307ee3e8561ccc6b
648,619
import collections def _get_infrequent_phrases(features_set, threshold_rate=0.03): """Get infrequent phrases on given dataset Args: features_set (iter): list of feature's dict threshold_rate (float, optional): Defaults to 0.03. Returns: set: set of infrequent phrase features ...
538d0354077df8e94029802f9d1c3fd570b36d39
648,620
def extract_csv_links(text): """Get a list of csv links from the download link response text""" links = text.replace("\r", "").split("\n") links.remove("") return links
e512a785759b4a80d903975ab7309b892c5c22c5
648,622
def str_is_empty_or_none(str_field: str) -> bool: """ Verifies whether a string is empty or None. Args: str_field (str): String to validate. Returns: bool: Evaluation result. """ return str_field is None or not str_field or str_field.isspace()
3e1a40dff415e5968669e36df61e5a50727f91db
648,625
def filter_clone(function, xs): """ Elements from xs are filtered out only for which the output of function holds True. """ filtered_lst = [] # We'll store our results here. for elem in xs: if function(elem): filtered_lst += [elem] return filtered_lst
da8da6967a2e6eaa446ee22331c3893cc39c0f34
648,629
def _get_unit_of_variable(df, variable, multiple_units="raise"): """ Get the unit of a variable in ``df`` Parameters ---------- variable : str String to use to filter variables multiple_units : str If ``"raise"``, check that the variable only has one unit and raise an `...
6234c474c71dba70fc330f017b47a371d7613942
648,630
def pretty_format_args(*args, **kwargs): """ Take the args, and kwargs that are passed them and format in a prototype style. """ args = list([repr(a) for a in args]) for key, value in kwargs.items(): args.append("%s=%s" % (key, repr(value))) return "(%s)" % ", ".join([a for a in args...
d3326bf2a36dc2eb002a77aec257682757f7bca5
648,633
def YumGetPathToConfig(vm): """Returns the path to the mongodb config file.""" return '/etc/mongod.conf'
1e7be583853d97e93efa81457edac3b548e42967
648,635
def define_stim_state(rel_time, on_time, off_time): """ Define stimulus state (1 = ON; 0 = OFF) based on relative stimulus time """ stim_state = ((rel_time > on_time) * (rel_time < off_time)).astype(int) return stim_state
0b447b22f7f2af627e7d4024f3bcde9eafccbb2d
648,637
def check_axes(x, axes): """ Checks if a list of axes is valid for a tensor or ndarray. If the input axis indices are not valid, a ValueError will be raised. Otherwise, the axes will be processed into a tuple of nonnegative integers Parameters ---------- x : torch.Tensor or np.ndarray ...
4f2528f28c612fde9d6b0410deac3ecab5291559
648,638
def send_request(client, post_data, **kwargs): """uses a dict to create a request on dataforSeo api parameters: client : Restclient object created with create_request post_data: dict created with create_request Optional parameters: server: server to use for request returns json style list"...
973fef88a77a592c8129ad5e409430173da08d69
648,639
def psy_const_of_psychrometer(psychrometer, atmos_pres): """ Calculate the psychrometric constant for different types of psychrometer at a given atmospheric pressure. Based on FAO equation 16 in Allen et al (1998). :param psychrometer: Integer between 1 and 3 which denotes type of psychrom...
0c1fe1d0b3702678cb1bc207d9e8e8537619b7d7
648,640
def to_lowercase_all(df): """ This function transforms all strings in the dataframe to lowercase Args: df (pd.DataFrame): Raw dataframe with some text columns. Returns: pd.DataFrame: Dataframe with lowercase standardization. """ return df.applymap(lambda s: s.lower() if type(s)...
131b10e97d2a882774b410eae7ab5b8c2c5f6946
648,643
def hard_most_common_letter(a): """Takes in a string of lowercase letters and returns the most common letter (if multiple, just pick one).""" # too tricky? d = {} for c in a: d[c] = d.get(c, 0) + 1 l = list(d.items()) l.sort(key=lambda x: -x[1]) return l[0][0]
ca5fc20d08dc9fe38e2d721e7e3557bdf92a51f6
648,645
def decompose_tokenized_text(token_list): """ Split the output of BERT tokenizer into word_list and tag_list """ # The initial tag is 'O' tag = 'O' word_list = [] tag_list = [] # A flag to indicate if it is in the entity now # 0 means out, 1 means start, 2 means in the middle i...
efce106b78a72f3c3151a144b77cdbdab21ac78f
648,649
import math def temperature_range(n, cut): """ Define the range of allowed temperature for given image size and cut. """ if isinstance(cut, (float, int)): log = math.log(cut) else: log = cut.log() T1 = 1 / (math.pi * n ** 2 * log) T2 = 4 / (math.pi ** 3 * cut ** 2 * log...
8701d2fb9503e82f31079b009cea4c89e7277e60
648,654
from typing import Dict def getLetters(string: str) -> Dict[str, int]: """Gets the letters of string and puts their occurences in a dictionary""" letters: Dict[str, int] = {} for letter in string: letters[letter] = letters.get(letter, 0) + 1 return letters
8a20cbc64baff825ad43874c96ca6ecd7f2e9231
648,658
import html def html2unicode(code): """ Converts HTML entities to unicode ('&amp;' => '&') """ return html.unescape(code)
1fc1ba02d47891320c087a7635327968bfe4f87c
648,659
def should_send_event(socket, annotation, event_data): """ Inspects the passed annotation and action and decides whether or not the underlying session should receive the event. If it should, the action is wrapped up in a websocket packet and sent to the client. """ if socket.terminated: ...
eb4458f58ad83ddb8de3716ee540e4fe2638d420
648,662
from typing import List def parse(text: str) -> List[str]: """ Parse a textual arguments into a list of strings in Unix style. This function currently supports: * Splitting arguments by spaces, cleaning up redundant spaces * String literals using single and double quotes :param text:...
e999023c8249c74216ee3b030828dd8d5a266477
648,663
def rotate(password, rotate_type, *params): """Rotate password - rotate left/right X steps - means that the whole string should be rotated; for example, one right rotation would turn abcd into dabc. - rotate based on position of letter X - means that the whole string should be rotat...
5b8248d56b1143a2d1ac41e890645649c6a434f5
648,664
from typing import OrderedDict def point_asdict(search_space, point_as_list): """Convert the list representation of a point from a search space to the dictionary representation, where keys are dimension names and values are corresponding to the values of dimensions in the list. .. seealso:: :class:`s...
f59aba0e6f64d93de31c9d7844f8e87e2c4eea70
648,666
def split(arr, n_devices): """Splits the first axis of `arr` evenly across the number of devices.""" return arr.reshape(n_devices, arr.shape[0] // n_devices, *arr.shape[1:])
204cb478ee4c39169c5142111842445e806845a1
648,667
def get_frequency_dict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence. sequence: string or list return: dictionary """ # freqs: dictionary (elemen...
26de771b5d1f5b0d8a255bd8cfbdbee314724dff
648,668
def find_root(node): """ Find the root of the current node. :param node: :return: """ current = node while current.parent: current = current.parent return current
4b0821e52af8c05321cf9d2a58ebcbe7df41cd29
648,670
def _strip_empty(d): """Strips entries of dict with no value, but allow zero.""" return { k: v for k, v in d.items() if v or (type(v) == int and v == 0) or (type(v) == str and v == "") }
57be868273b3d5e47cbf360c6df6e0eec238cf28
648,675
def adapt_param(p: float, p_min: float, p_max: float, d: float, d_target: float, xi: float ) -> float: """ Self adapts a param p given a measure m and control xi Args: p (float):...
f3d0b63aee18f8b5143aee81b4146acefbe76d26
648,676
def repeated_argument(e: SyntaxError) -> str: """Generates a feedback for a repeated keyword argument error. Parameters ---------- e : SyntaxError the error object Returns ------- str feedback message """ msg = "I couldn't parse your function call because I got a re...
7022e891d1780f10def78376deb8a6f79dce6dfc
648,678
def _Cond(test, if_true, if_false): """Substitute for 'if_true if test else if_false' in Python 2.4.""" if test: return if_true else: return if_false
18b5f69c0a8087753d8790a9d96c6e1d74e989b1
648,682
def dictfetchall(connection, sql, *params, **kwargs): """ Return all rows from a cursor as a dict, if kwargs.get("format") == 'list', return as list """ with connection.cursor() as cursor: cursor.execute(sql, params) columns = [col[0] for col in cursor.description] if kwargs.get("...
6f1ff2fe0fc1a21d76a7f761c85fc5a65dc505e2
648,685
def get_video_shape(params, is_space_to_depth=False): """Returns exact video shape as model's input.""" if is_space_to_depth: video_shape = [params.num_frames // 2, params.frame_size // 2, params.frame_size // 2, 24] else: video_shape = [params.num_...
ede7857e0a41c869c61472e344ca97266949e352
648,687
import json def make_request_callback(timeout_count, body_on_success, http_error_status=504): """Make a request callback that timeout a couple of time before returning body_on_success. Returns: A tuple (request_callback, attempts), attempts is an array of size one ...
17d19e19c16a13a657adac04f60eb150ad84a846
648,691
def factorial_recursive(num): """returns the factorial of num using a recursive method.""" if num == 1: return 1 return num * factorial_recursive(num -1)
430c93f14484bb8bfaa4581279b10daa79614e85
648,694
import time def timed(func): """ This decorator adds a timer to the decorated function. The original function results and the timer results are returned as a tuple of size 2 :param func: the function to decorate :return: decorated function """ def timed_method(*args, **kwargs): sta...
2bcedf03a8dff9021a2404094cfd39b5f81b44d5
648,697
def fit_predict_for_chain(chain, train_input, predict_input): """ Function apply fit and predict operations :param chain: chain to process :param train_input: InputData for fit :param predict_input: InputData for predict :return preds: prediction of the chain """ # Fit it chain.fit_fro...
10677b0395170125dd8691179fc03a631721e8e8
648,700
from typing import List def ListIntToSequence(l: List[int], separator: str = '.') -> str: """Merge [192,168,42,1] to '192.168.42.1' Returns: str: int join with sep """ return separator.join(str(x) for x in l)
512322e923192ed13a6d0e99abe2a2e921d4bbc3
648,703
def get_exec_command_python(language_cmd: str, in_file_path: str) -> str: """ Function which provides the execution command for an upcoming python execution @param language_cmd: base language command, in this case "python" @param in_file_path: file where the input code will exist @return the execu...
8b273054be14865d5a74b97b6fc40b5742a00652
648,707
import yaml def read_config(config, key=None): """Read a config file and return the right configuration.""" print("INFO: Loading configuration from", config) config = yaml.load(open(config, 'r'), Loader=yaml.SafeLoader) if key is not None: if key in config: print("INFO: Using the '...
dcedb58a0d97653f53c9fb93abc67f25e8e6a6dc
648,708
def get_user_display_name(u): """Get `display_name` for a user Args: u: user Returns: A string example: 'Donald J. Trump' """ name = [] if u.first_name: name.append(u.first_name) if u.last_name: name.append(u.last_name) return '|'.joi...
01aaefc0de548784f864501d2c8e6541ed125767
648,710
def launch_label(cfg): """Returns a label based on how far the piepline has progressed""" order = ["Initial", "Classify", "Post", "Upload", "Debase", "RM", "RVM_initial", "RVM_final", "Finish"] counter = sum(cfg["completed"].values()) # Number of True statements return order[counter]
391f0fd678d89935fa0f1facd9bc09dbfbeee1a6
648,715
import base64 import hashlib def make_hash_string(string, output_length=10): """Create a hash for given string Truncates an md5 hash to the desired length. Will always be safe for file names. Args: string (str): input string output_length (int): length for output Returns: ...
0982d6478d781a2d0e86b7ada2d7c12768c0214d
648,716
def dot_prod(a,b): """ This function takes two vectors, a and b, and finds the dot product,c. """ c = a[0]*b[0] + a[1]*b[1] + a[2]*b[2] return(c)
41724465bb8dc9d0bd154fbb5b41be4bcdfd5ff7
648,717
def drop_msg(module_name, module_package): """ Create info message for dropped modules. """ if module_package is not None: ignore_msg = "drop %s (in %s)" % (module_name, module_package) else: ignore_msg = "drop %s" % module_name return ignore_msg
e56461cbb6a195babd3d8038654df1d3ffb57bbe
648,721
def format_coverage_line(text, statements, missed, coverage, missed_lines=False): """Format one line with code coverage report of one class or for a summary.""" format_string = "{:80} {:3d} {:3d} {:3d}%" if missed_lines: format_string += " N/A" return format_string.format(text, statements...
a274ad021f1e12171c28ab5e218c93930120d55b
648,722
def extract_7z(archive, compression, cmd, verbosity, interactive, outdir): """Extract a 7z archive.""" cmdlist = [cmd, 'x'] if not interactive: cmdlist.append('-y') cmdlist.extend(['-o%s' % outdir, '--', archive]) return cmdlist
243a473657306866cb5a4d860c9ae6e48d4d3de6
648,724
def find_failed_results(run_artifacts: dict) -> list: """find the index and ID for which elements failed in run Args: run_artifacts (dict): dbt api run artifact json response Returns: list: list of tuples with unique id, index """ failed_steps = [] for index, result in enumera...
43333b823841ce84543319e64293ca233ea7d920
648,725
def _check(value,x,y): """ Check if a value is between x and y Parameters ---------- value : float Value of interest. x : float Limit x. y : float Limit y. Returns ------- int Numerical bool if value is between limits x and y. """ if x <...
43b09200577497793bf90649be990f55b2119452
648,726