content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def upper(word: str) -> str: """ Will convert the entire string to uppercase letters >>> upper("wow") 'WOW' >>> upper("Hello") 'HELLO' >>> upper("WHAT") 'WHAT' >>> upper("wh[]32") 'WH[]32' """ # converting to ascii value int value and checking to see if char is a lower...
830939176937426bc8b0e0474e77acb1f74607cc
592,516
def add_attr(field, values): """Add attribute to an element. Example: {{ field|add_attr:'placeholder="Sample Text"'' }} """ return field.as_widget(attrs=values)
3cc4a1ff7977fdb3a39512457ec44a39a2aa110c
592,518
def remove_substr(comp_str, str_list): """Remove substring.""" ret_list = [] for s in str_list: if s in comp_str: continue ret_list.append(s) return ret_list
47a45137b4044cc88cbd09aa99986ac634030202
592,521
import csv def readcsv(fname): """Reads the CSV file given and returns a list of dicts""" reader = csv.DictReader(open(fname)) ret = [row for row in reader] return ret
a65508d2b09804a71eaf447e1b404415a87fb8af
592,525
import torch def uniform_random_rot_matrix(num_matrices, std=0.01): """ Uniform sampling of random 3D rotation matrices using QR decomposition. Source: https://arxiv.org/pdf/math-ph/0609050.pdf """ Z = torch.randn(num_matrices, 3, 3) * std Q, R = torch.qr(Z) d = torch.diagonal(R) ph = ...
b9326f005c955d069f46ac4b5a5b6ca3a669cc9f
592,527
import math def divisors(n): """Returns a list of divisors of n Args: n (int): The number whose divisors will be returned Returns: divisors (list): List of divisors of n """ divisors = [1] for i in range(2, math.floor(math.sqrt(n)) + 1): if n % i == 0...
4e2d48ff01a5a11cc7cdd00432eb94c66b5f866d
592,528
def get_attention(attn_mat, idx=0, layer=0, head=0): """ Get one slice of the attention map. Parameters ---------- attn_mat : Tensor attn_mat is numpy array in the shape of [S, N, H, d, d], where S is the total number of data samples, N is the layer number in the attention m...
35dbd786f54f03ee9b6a1612ea9a38654dc199c4
592,530
def L1(yhat, y): """ Arguments: yhat -- vector of size m (predicted labels) y -- vector of size m (true labels) Returns: loss -- the value of the L1 loss function defined above """ ### START CODE HERE ### (≈ 1 line of code) loss = sum(abs(yhat - y)) ### END CODE HERE ### retu...
28a931c8cf3fbe94e19bb641b15653a17a9ef55c
592,533
def find_in_listdict(listdict, search_key, val, return_key): """ For a given listdict (list of dictionary), if dict[search_key] is equal to val, return dict[return_key]. Return None if no match is found. """ search_key_exists = False for _ in listdict: if search_key in _: s...
1505984e7d269613c4d4aa3766fb307c53e035f8
592,534
def make_dict(duration, voltages, beats, mean_hr, beat_times): """Makes a dictionary following the format described on github :param duration: Time length of data sequence :param voltages: Voltage extremes in tuple form :param beats: Number of beats :param mean_hr: Calculated heart rate in BPM ...
8e7e30728f639a4c41b2201f11d58aadb8a5cf44
592,535
def _true(*args): """ Default rerun filter function that always returns True. """ # pylint:disable=unused-argument return True
d0f7a2909476f99a28d772cfa9923bbafd8fddc8
592,549
def fn_df_unique_3cols(df, columns): """Returns a unique list in the last column of the dataframe based on the first 2 columns. Inputs: df: Dataframe of interest columns: List of 3 column names. First 2 for grouping and last the column for unique values Notes: 3 columns must be based in. The unique ...
de7b74f89ee93ec8a1e5911f337dfeb115ba0bee
592,550
import six def hex_or_none(text): """ Get an integer from a hex number or return None """ if text is None: return if isinstance(text, six.integer_types): return text try: num = int(text, 16) except ValueError: num = None return num
7f6defe9badbbaa6b399d5684dbec499410603c1
592,551
def _is_local_ip(ip): """ Find if a address is from the local network. :param ip: the ip address to check :return: True if detected as a 'local'-Network address """ return True if ip in ['127.0.0.1', "0:0:0:0:0:0:0:1"] or not ip.startswith('192.') else False
f32b528700742e1ffa0c14a180beefd07b7f658c
592,553
def percent_unique_ngrams_in_train(train_ngrams_dict, gen_ngrams_dict): """Compute the percent of ngrams generated by the model that are present in the training text and are unique.""" # *Total* number of n-grams produced by the generator. total_ngrams_produced = 0 for _, value in gen_ngrams_dict.iteritems(...
5f07e359c186d13545aebdb573c36e5d5556faea
592,554
def get_ks_creds(cloud_creds, scope='PROJECT'): """Return the credentials for authenticating against keystone. :param cloud_creds: OpenStack RC environment credentials :type cloud_creds: dict :param scope: Authentication scope: PROJECT or DOMAIN :type scope: string :returns: Credentials diction...
2cb9635a34cb0ef0f1484c0ed27b1072dde28d92
592,558
def dotProduct(x, y): """ Gets the dot product between the two given vectors. Args: x (list): First vector. y (list): Second vector. Returns: (float): Dot product result, scalar. """ return sum([x[i] * y[i] for i in range(len(x))])
75afb3c1e8f7e5ca37a05b0a28306a2d57424100
592,559
from typing import List def get_intersection(a: List, b: List) -> List: """ 两个列表取交集 :param a: 集合A :param b: 集合B :return: 集合A交B """ return [val for val in a if val in b]
baf5cc76d1bcb717ea8939fd607f0bb54e0d9a6b
592,561
import re def match_pseudo_type_id(op): """Tell if given string matches a pseudo type.""" if re.match(r'(mat|vec)$', op): return True return False
f32ba291d2766de331c4ee5a556fce4f5aada071
592,563
def read_values(xs, sep, *values): """Read values from a string. Args: xs (str): Values as one string. sep (str): Separator separating the values in the string. *values (str): Names of the values. Returns: dict: Naming of the values mapping to the values. """ xs = [...
106293d3671ee401fb24c0642076c646da15bea3
592,572
def micro_f1_similarity( y_true: str, y_pred: str ) -> float: """ Compute micro f1 similarity for 1 row Parameters ---------- y_true : str True string of a space separated birds names y_pred : str Predicted string of a space separated birds names Returns ...
fbe6b07e329ce5727e8488f8627dc7904694f719
592,573
def all_equal(iterable): """Return True if all elements in `iterable` are equal. Also returns True if iterable is empty. """ iterator = iter(iterable) try: first = next(iterator) except StopIteration: return True # vacuously True return all(element == first for element in ...
aef8a4f315917d1f15e2e27d65220ba77e9c1375
592,574
def denormalize_coords(xx, yy, width, height): """ scale indices from [-1, 1] to [0, width/height] """ xx = 0.5 * (width - 1.0) * (xx.float() + 1.0) yy = 0.5 * (height - 1.0) * (yy.float() + 1.0) return xx, yy
3277b5a0cf80a10ff2c1b3b7c9d421513dfcd8d7
592,575
import gzip def open_file(fastq): """Open the FASTQ file, gzip or not, and return the handle.""" if fastq[-3:] == ".gz": return gzip.open(fastq) else: return open(fastq)
d2e5ae71e2abd82ea255ffdfd9ed7f77cda95cf3
592,577
def extract(dataset, column_index=0): """ Extracts one column from a dataset. :param list dataset: A list with all dataset content :param int column_index: The index of the column that will be extracted from dataset :return: A list with the column contents """ column = [] for row in data...
5959ee2071f7991c5ad5c19091ecee61b9466479
592,579
def noexceptions(phenny, input): """Tells someone there aren't ever any exceptions""" #whouser = input.groups()[1] whouser = input.nick if not whouser: return phenny.say('NO EXCEPTIONS!') response = "NO EXCEPTIONS, %s!" phenny.say(response % whouser)
2de310564d641542c3aa60a98adb55b40ef35f7b
592,581
def deleteindex(es, params): """ Deletes all indices in Elasticsearch matching the specified index pattern. It expects the parameter hash to contain the following key: "index_pattern" - Specifies the index pattern to delete. Defaults to 'elasticlogs-*' """ if 'index_pattern' in param...
4e1d030632733ff4a8c4dfd89b0b1daefd057fe0
592,584
def clean_subpath_id(db_name: str, subpath_id: str) -> str: """ Clean the subpathway id for all DBs except Wikipathways :param db_name: :param subpath_id: :return: """ if db_name == "reactome": return db_name + ':' + subpath_id.split('#')[-1] elif db_name == "kegg": retur...
3fcdd5e30b817aec2a9c2bf28a0fc15233651a0c
592,589
import math def pyramid_steps_loop(n): """Return a list of "n" progression pyramid steps, using loops.""" result = [] line_size = n * 2 - 1 line_mid = math.floor(line_size / 2) for i in range(n): line = "" for j in range(line_size): line += "#" if j >= line_mid - i and ...
84483dc165828f6ae5cf3de688c307db536bdc4c
592,590
def get_dataset_args(parser, args=[]): """ Get all relevant parameters to handle the dataset """ # Dataset: # ------------------------------------------------------------------------ parser.add_argument( "--dataset_type", type=str, default="MRNet", help='Dataset: ...
bb28cf4556a36ecf604e1578b88b9a93fe97cc44
592,595
import re def clean(string): """Clean string Cleans a string to be a valid Python variable name. It replaces all invalid characters with an underscore. Arguments: string {str} -- string to be formatted Returns: str -- formatted string """ string = re.sub('\W|^(?=\d)', '_...
3be5fabaa774e332f618d81a9a652904061b8115
592,598
def generate_merge_func(_): """ Returns the identity function :param _: the inputt paramter is ignored """ return lambda x: x
8b1bcc7c9550981113349037a46509b5bda7f58d
592,600
def dicts_to_html_table(a_list): """ Converts a list of dictionaries to a HTML table. Keys become the header of the table. Useful while sending email from the code :param list(dict) a_list: values in the form of list of dictionaries :return: HTML table representation corresponding to the values in...
c74fc3bbefd7ec638767a8298eea47640d8fd5fa
592,619
def is_local(connection): """ Returns true if a connection is local. """ return (connection.src.loc.x, connection.src.loc.y) == \ (connection.dst.loc.x, connection.dst.loc.y)
dfeba0f42cdcc4eb84393f1c4da442cf791a44af
592,620
import re def parse_synctex_response(response, pos): """ Take the stdout response of SyncTex and parse it into a dictionary. Parameters ---------- response: string The response output to stdout from SyncTeX pos: dict The position that was input to SyncTeX returns: ...
faf17aa3f7f1559e906c191a9690b6ef9fd1780f
592,622
def binary_search(list_obj, value, low, high): """ Recursive Binary Search Algoirthm: Using Divide and Conquer design paradigm to reduce the complexity and increase the efficiency Arguments: list_obj: represent list object value: an object where it's value that we are looking for in the list low: an int...
bd1bad68b0fa32e3528dee036f9dcd8e92c6b58e
592,623
def interpolate(color1, color2, mix): """Interpolate between color1 and color2.""" r = (color1[0] * (1.0 - mix)) + (color2[0] * mix) g = (color1[1] * (1.0 - mix)) + (color2[1] * mix) b = (color1[2] * (1.0 - mix)) + (color2[2] * mix) return (int(r), int(g), int(b))
6aa9035d5b274f65ad7c0e62b7f1a80ddc578a8a
592,624
from typing import Tuple def auto_figure_size(figure_shape: Tuple, scaling_factor: int = 4) -> Tuple: """Scales figure shape to generate figure dimensions. Args: figure_shape (Tuple): Figure shape in determines of rows and columns. scaling_factor (int, optional): Defaults to 4. Returns: ...
9c584becb9b4cb7a396b7b18647e5fd1a4bc3cc9
592,625
from typing import Iterable def remove_non_extreme_numbers(s: Iterable[str], leave_min=True) -> Iterable[str]: """ Removes from an iterable all numbers which are neither minimal or maximal. All non-numeric elements are left untouched. The order of elements might be different in the output. Exampl...
13dabbdec82592860eac2f52892eb31778efd24d
592,626
from typing import Any def rpc_bool(arg: Any) -> int: """ Convert between Python boolean and Transmission RPC boolean. """ if isinstance(arg, str): try: arg = bool(int(arg)) except ValueError: arg = arg.lower() in ["true", "yes"] return 1 if bool(arg) else 0
78b0aa5515ecf4ce4fac8fc7f105cd4836003511
592,628
import re def regex_groups(regex, line, on_error): """Function encapsulating regex search, for use with multiprocessing library. It will return the matching groups in a tuple, and raise errors if on_error is set to 'raise'. Explanation why this function is needed: Instead of returning re.match objects...
7587dce0a0fb475c234fcff4e6457c7cf7ff84c5
592,632
def personal_top_three(scores): """Return the top three scores of a player.""" return sorted(scores, reverse=True)[:3]
84bcf774341bb33d8399f080a3ab1745367a57c3
592,638
from typing import Optional import difflib def diff_code( oldcode: str, newcode: str, context: int, *, filename: Optional[str] = None ) -> str: """ Given two strings representing a module before and after a codemod, produce a unified diff of the changes with ``context`` lines of context. Optionally, ...
412a1281cd948f4bda093cb8142eaf050819fb84
592,639
def acc(modifier: int, number: int) -> int: """ acc adds or subtracts from accumulator :param modifier: Number to added/subtracted from acc :param number: current acc value :type modifier: int :type number: int :rtype: int """ return number + int(modifier)
efe108a5d98c1afab620eaef2c8f2e4fe3d42623
592,640
def pure_python_hello(name:str): """Testing a pure python function Args: name (str): Just a simple name """ return "Hello " + name
d3bcc5b8f4a1882f7dc09c26dc7a22ca4d1cfe9b
592,645
def find_mass_gain_rate(battery,power): """finds the mass gain rate of the battery from the ambient air Assumptions: Earth Atmospheric composition Inputs: power [W] battery. mass_gain_factor [kg/W] Outputs: mdot [kg/s] """ #weight...
1220d828f2cbf6515add52c16592295183ccc674
592,646
def _get_contig_based_variant_sort_keyfn(contigs): """Returns a callable used to sort variants based on genomic position. Args: contigs: list(ContigInfo). The list of contigs in the desired sort order. Returns: A callable that takes a single Variant proto as input and returns a value that sorts base...
52ca57b9da4349c2468520a37732899a173b5cf6
592,647
import re def find_news_source(link: str) -> str: """From news link, returns B if Bloomberg or or R if Reuters @:param news link as a string @:return B/R """ return "B" if re.search('bloomberg', link, re.IGNORECASE) else "R"
e3ab6ab38cbafec22c9f89c7e5a117ff166064e0
592,648
def bead_sort(sequence: list) -> list: """ >>> bead_sort([6, 11, 12, 4, 1, 5]) [1, 4, 5, 6, 11, 12] >>> bead_sort([9, 8, 7, 6, 5, 4 ,3, 2, 1]) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> bead_sort([5, 0, 4, 3]) [0, 3, 4, 5] >>> bead_sort([8, 2, 1]) [1, 2, 8] >>> bead_sort([1, .9, 0.0, 0,...
6be466c04e9576f131c63165bc9e2a95fb61f55b
592,652
def delete_named_urlpattern(urlpatterns, name): """Delete the named urlpattern. """ found = False ix = 0 while not found and ix < len(urlpatterns): pattern = urlpatterns[ix] if hasattr(pattern, 'url_patterns'): found = delete_named_urlpattern(pattern.url_patterns, name)...
495b41ca276ca1c0c7e5d174cbb736afb70ba560
592,653
import torch def evaluate_sce(confidences: torch.Tensor, true_labels: torch.Tensor, n_bins: int = 15) -> float: """ Args: confidences (Tensor): a tensor of shape [N, K] of predicted confidences. true_labels (Tensor): a tensor of shape [N,] of ground truth labe...
cb0ac9e02a0b8d27c5b65b599c71d766268f2993
592,654
def sha256(ctx, artifact): """Create an action to compute the SHA-256 of an artifact.""" out = ctx.new_file(artifact.basename + ".sha256") ctx.action( executable = ctx.executable.sha256, arguments = [artifact.path, out.path], inputs = [artifact], outputs = [out], mnem...
9e41bb57a99f2610c9305347f47e731171260514
592,655
def convert_mrphs_to_surf(mrphs: str) -> str: """Remove unnecessary spaces from a tokenized surface string.""" surf = mrphs.replace(" ", "") surf = surf.replace("]", "] ").replace("|", " | ").replace("▼", "▼ ").replace("■", "■ ").replace("(", " (") return surf.strip()
52548417d998adcbce305c46fc988916172d0c41
592,658
def _ssh_args(ssh_bin, address, ec2_key_pair_file): """Helper method for :py:func:`ssh_run` to build an argument list for ``subprocess``. Specifies an identity, disables strict host key checking, and adds the ``hadoop`` username. """ return ssh_bin + [ '-i', ec2_key_pair_file, '-o', ...
b9414b70bfd38619d3de3f626af666292189a94c
592,664
def allocate(reservations, total=1.0): """ Allocate resources among slices with specified and unspecified reservations. Returns a new list of values with the following properties: - Every value is >= the corresponding input value. - The result sums to `total`. Examples: allocate([0.25, Non...
3a85cda8de2b7d4fc4af0788c27f1f3518ffcd5f
592,668
def tableau_de_multiples(n: int, limite: int) -> list: """ Description: Trouver les multiples d'un nombre entier positif jusqu'à une limite donnée. Paramètres: n: {int} -- Le nombre entier positif. limite: {int} -- La limite. Retourne: {list} -- La liste des multipl...
27a61a3e058e231496a1786da33f28f6e3588be1
592,674
def find_layer_in_model(model, layer_name): """ Find a layer in a model by name """ layer = None for lay in model.model.layers: if lay.name == layer_name: layer = lay break if not layer: raise ValueError(f"layer {layer_name} not found!") return layer
4c0ec10f06a843dc938198d30b67b199b34f4571
592,677
def _stack_contains_kind(stack, kind): """ Checks if a cursor with the given kind is within the stack. :param stack: The stack holding a tuple holding the parent cursors and the child number. :param kind: The kind of the cursor to search for. :return: True if the kind was fo...
80baab96ec9b6fe0d5977537a6f842bde1b1a389
592,679
def shorten_path(path): """Shorten an incoming domain name like path to only have the first char of each segment except the last e.g. foo.bar.baz -> f.b.baz """ out = "" segments = path.split(".") l = len(segments) i = 0 while i < l: element = segments[i] if i ...
e004d8b4ae5344085af44869324af3ed7639834b
592,681
import types def is_function(tup): """ Takes (name, object) tuple, returns True if it is a function. """ name, item = tup return isinstance(item, types.FunctionType) # def _start(self, spin): # for args, kwargs in self.subscribers: # self.subscribers_init.append(rospy.Subscrib...
e49e0973828d0eea848d29b8a1b954119f1fe490
592,682
import torch def _get_triplet_mask(labels): """Get a 3D mask where mask[a, p, n] is True iff the triplet (a, p, n) are valid. A triplet (i, j, k) is valid if i, j, k are not the same indexes and labels[i] == labels[j] and labels[i] != labels[k] Args: labels (torch.tensor): Labels with shape (b...
cfc633823cd61a1845ad07d9061ffa7bc0c0cfdd
592,685
def get_runid(args): """ Generate a unique run ID from arguments """ # Input and network setting runid = f"in{args.input_dims}_cond{args.cond_dims}_"\ f"affx{args.num_aff_coupl_blks}_"\ f"subnet{args.subnet_nlayers}x{args.subnet_nunits}" if (args.batch_norm): runid += "_ba...
78a9e0dd48b43f33652712079a70a66198d6ad1f
592,688
import socket def pick_port(*ports): """ Returns a list of ports, same length as input ports list, but replaces all None or 0 ports with a random free port. """ sockets = [] def find_free_port(port): if port: return port else: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
94a4251145da6687358bc9a2eb478d13e89832e4
592,689
import string def formatStr(bad_str, hard=True): """Remove trash punctuation. Args: ----- bad_str (str): string to format hard (bool): remove all punctuation or just remove space Return: ------- string formated """ try: if hard:...
08a646eb0eef800833b9508f1ea23a635e6d8adb
592,690
def one_to_one(data): """Sample torchscript script that returns the highest element in an array. One input to one output """ # return the highest element return data.max(1)[0]
e5814267be7508c1d27fc369cba7b68aa938b9ee
592,693
import torch def compute_amplitude(waveforms, lengths=None, amp_type="avg", scale="linear"): """Compute amplitude of a batch of waveforms. Arguments --------- waveform : tensor The waveforms used for computing amplitude. Shape should be `[time]` or `[batch, time]` or `[batch, ...
c9c914811e5345fe5d57a79544c07d398d1e58de
592,694
def is_ignored_roi(roi, ignore_data): """Determine whether a specific ROI should be ignored Parameters ---------- roi: drymass.roi.ROI ROI instance ignore_data: list of str List of strings of the form "image_index" or "image_index.roi_index" that identify ROIs that s...
30aef8c4ae8832e70482ee1184b1a7cd0e9f4eee
592,698
def concatOverlapPep(peptide, j, prefixPeptide): """ Called by self.createOverlap(), this function takes two peptides which have an identical prefix/suffix sequence and combines them around this like sequence. Eg: ABCDE + DEFGH = ABCDEFGH :param peptide: the peptide with matching suffix sequence :p...
84cae79adcc1d6b4eeef8e8d679c963f925f3efa
592,703
def prog_bar(i, n, bar_size=16): """ Create a progress bar to estimate remaining time :param i: current iteration :param n: total number of iterations :param bar_size: size of the bar :return: a visualisation of the progress bar """ bar = '' done = (i * bar_size)...
dd350383f26b0fbba94baf1d44cb9d934cbec690
592,708
def sort_gift_code(code): """ Sorts a string in alphabetical order. :param code: a string containing up to 26 unique alphabetical characters. :return: a string containing the same characters in alphabetical order. """ return "".join(sorted(code))
38cbacd82f94adda87e3f39cd2924363dd37fa09
592,709
def get_verts(voxel, g): """return list (len=8) of point coordinates (x,y,z) that are vertices of the voxel (i,j,k)""" (i, j, k) = voxel dx, dy, dz = g["dx"], g["dy"], g["dz"] v1_0, v1_1, v1_2 = g["xlo"] + i * dx, g["ylo"] + j * dy, g["zlo"] + k * dz vertices = [ (v1_0, v1_1, v1_2), ...
ea8af6236d6f3ea1c1da4f6c62dae0e0e17ef668
592,710
from typing import Any from typing import Optional from typing import MutableSequence def listify(item: Any, default: Optional[Any] = None) -> Any: """Returns passed item as a list (if not already a list). Args: item (Any): item to be transformed into a list to allow proper iteration. ...
c14dfb86d0998a7df71b3dabb0d4a2dc22365e04
592,714
def array_swap_transform_next_index_to_current_index(position, move): """Transforms the position depending on the move. Works with the array_swap move type. This function transforms the position so that it can be used as the indice in the unaltered array, yet return the value it would have had if the m...
25610d29c9a35cec7307e9b70dc8d44fd725a967
592,718
import time def timer(func, times=1): """ Run a function in loop, the number of repeats is given by argument times. Return the total time in seconds. This function can't receive any argument of func. Use func from functools.partial instead. """ start = time.time() for i in range(times): ...
747078588ca03504a41c0abec7b1f639d7513a6f
592,722
def get_values(df, rows, column): """Get the desired column value from a list of dataframe iloc indexes.""" return [df.iloc[row][column] for row in rows]
2013275ba248ddcd6170f3bb71a31a468585b739
592,723
def vector(p0, p1): """Return the vector of the points p0 = (xo,yo), p1 = (x1,y1)""" a = p1[0] - p0[0] b = p1[1] - p0[1] return (a, b)
b5d6b8122d82a5b499c6f1ff5c327fdb3002ec0d
592,724
import logging def extract_gcs_tokens(full_object_name): """ Extracts the bucket and object name from a full GCS path. Args: full_object_name: A str, a full GCS object name. Returns: A tuple of the form (bucket_name, object_name). """ bucket_name = None object_name = None tokens = full_object_...
a20c07356e7c44dbf7c8ffd79b951d0ee5f614a0
592,725
import re def parse_prob_label(label): """ Parse the label into components. Currently (name)_ndx3_ndy7_std_h0.n(sample_size) - The dot . separates the file name from options. - (name) can contain _. - (sample_size) must be less than the total size of the original data. - _ndx%d is t...
5d82a976c5502ba6ffb4018b0953ae2487f476c9
592,728
def bound(val, lower, upper): """Clamps val between lower and upper.""" if val < lower: return lower elif val > upper: return upper else: return val
18cd6cb3fd320ddd0508a3b48780c5248d9cab3a
592,733
def get_current_top_category(request, obj): """ Returns the current top category of a product. """ if obj.__class__.__name__.lower() == "product": category = obj.get_current_category(request) else: category = obj if category is None: return category while category.p...
3e7c9ad2d4d1386ad0ce67163204b9066cb41a12
592,734
def get_topic_name(prefix, table, operation, host=None): """Create a topic name. The topic name needs to be synced between the agent and the plugin. The plugin will send a fanout message to all of the listening agents so that the agents in turn can perform their updates accordingly. :param pre...
af7c88e2e353f10cd74259bffc71ad48c2ef9c66
592,735
def step_back_while(cur_index, condition): """Helper function. Decreases index from cur while condition is satisfied.""" while cur_index >= 0 and condition(cur_index): cur_index -= 1 return cur_index
701d20c15ccd70e2ff8bf6995ff2233fce177d45
592,736
def _lowercase(dictin): """ Make all keys from a dictionary lowercase. Args: dictin (dict): dictionary Returns: modified dictionary dictin Ok for nested dictionaries, but will not work for dictionaries within lists. """ if isinstance(dictin, dict): return {k.lower(): ...
09ec3a7ff95a064f973503224a2770d0f94f689c
592,737
from typing import Callable from typing import Union from typing import Any def catch(func: Callable, *args, **kwargs) -> Union[Any, None]: """Execute func by passing args and kwargs. Catch exceptions and return None in case of failure. Args: func (Callable): function to execute and catch exceptions ...
8230fa225f6cb47b04b43bf743e626273b63115a
592,738
def average(collection, function=None): """Calculate the average of values in a collection. :param collection: The collection with the data to be averaged :type collection: list | iterator :param function: Function used to retrieve data from each element. If not passed an identity funct...
457e3ce25a32ee0af9c4572c7fb528e74066b682
592,741
def check_interface_capability(interface, capability): """Evaluate interface to determine if capability is present. :param interface: The interface object to check. :param capability: The value representing the capability that the caller wishes to check if present. :returns: Tru...
472b9c833de34d4edfb53d5ff5a362827ee9aa17
592,743
def pascal_case(what): """ Convert the first letter of a string to uppercase, to make the identifier conform to PascalCase. If there are dots, remove the dots, and capitalize the letter following where the dot was. Letters that weren't following dots are left unchanged, except for the first letter of the s...
3972abad7f23f37af8b3bdce973c163aefdb21eb
592,745
def drop_non_active_basis_functions(basis): """Remove all basis functions with no eci value and reindex the basis in a sequential order. New field is entered to remember what the old index used to be Parameters ---------- basis : json (eci.json file content) Returns ------- json ...
a34b69184b6441f5f93f56c7c5e876c06bdb470f
592,750
def find_in_list(a_list, find_func, reverse=False): """Find a matched item in list - a_list: list like object - find_func: the filter function to find a matched item - reverse: find in reversed? True/False Return a item in the list Example: data = [1, 2, 3] find_in_dict(data, lambda x...
61a7ef062406c3786dced43808d50ff2fbcf3416
592,751
from datetime import datetime def to_time_format(timestamp: int, fmt: str = '%Y-%m-%d %H:%M:%S'): """ Convert timestamp to string using format. :param timestamp: Timestamp in ms :param fmt: Format. :return: """ return datetime.fromtimestamp(int(timestamp) // 1000).strftime(fmt)
f5b88985250ab8144b28cb3cb2dc710be6590cfa
592,752
def determine_target(module, results): """ Determine the make target name. Determine the top level make target for the build. First, use the explicit target if given. Next interpret the explicit configure options if given. Finally, interpret the build options. This function may only be used a...
319ff1efdea23baa55c4d285fd226ee723e4b438
592,753
def CalculateConvolvedOutputDim(input_dim, filter_dim, stride, padding_type): """Calculates the size of an output dimension of a strided convolution. Given the sizes of the corresponding dimension of the input and filter shapes, and the stride and padding_types, calculates the size of the output dimension. Thi...
868d7dc5b4f553a244709697dccb2a580bb31cd3
592,754
def canonicalize_ints(values): """ Cast a nested sequence of numbers to a nested tuple of ints. """ if isinstance(values, (list, tuple)): res = [] for v in values: res.append(canonicalize_ints(v)) return tuple(res) return int(values)
2f452786260fabde9ac72462b1bde4257c96e32c
592,757
def dup_mul_term(f, c, i, K): """ Multiply ``f`` by ``c*x**i`` in ``K[x]``. **Examples** >>> from sympy.polys.domains import ZZ >>> from sympy.polys.densearith import dup_mul_term >>> f = ZZ.map([1, 0, -1]) >>> dup_mul_term(f, ZZ(3), 2, ZZ) [3, 0, -3, 0, 0] """ if not c or n...
b166a8a251262742caabf8794e03c05952f2f3c4
592,758
def create_dict(o): """Creates a dict from a object/class""" return dict((key, value) for key, value in o.items() if not callable(value) and not key.startswith('_'))
ea758352e80eb532d59378d5e96cdc46ede29f30
592,759
def optimize_circuit(params): """Minimize the variational circuit and return its minimum value. The code you write for this challenge should be completely contained within this function between the # QHACK # comment markers. You should create a device and convert the variational_circuit function into a...
829d2ffc74a28f0cd80caaed4534405df5411852
592,762
def kgtk_geo_coords(x): """Return True if 'x' is a KGTK geo coordinates literal. """ # Assumes valid KGTK values, thus only tests for initial character: return isinstance(x, str) and x.startswith('@')
7650e1ca9cb8bd1f76d9df8cdb2b14e3ac06bfc6
592,763
from typing import Optional def boolean_text(text: Optional[str]) -> str: """ Formats a string as yes/no depending on whether it is present :param text: The text to format :return: "Yes" if text is truthy, otherwise "No" """ return 'Yes' if text else 'No'
2d23d1d74a7fa82e01e46227a17736f7c12092f1
592,770
def crop_center(img, new_shape): """ Crop an image equally on each size to create the new_shape Args: img (numpy array): 2D array to crop new_shape: desired shape of the return Returns: numpy array: array cropped according to shape """ ul = ((img.shape...
d20ed57976def7d7a88344d90937bc7027040fcc
592,773
def eitem_event_builder(event, sender_app, obj=None, **kwargs): """Add eitem metadata to the event.""" record = kwargs["record"] event.update(dict( eitem_pid=record["pid"], document_pid=record.get("document_pid") )) return event
adc9b0ef803d5ba3cb3a84c0086b41bab33617eb
592,775