seed
stringlengths
1
14k
source
stringclasses
2 values
def middleware(get_response): """Set up middleware to add X-View-Name header.""" def add_view_name(request): response = get_response(request) if getattr(request, 'resolver_match', None): response['X-View-Name'] = request.resolver_match.view_name return response return add...
bigcode/self-oss-instruct-sc2-concepts
def enumerated_subsections(request): """Parametrized fixture of each subsection along with its index in the parent section.""" return request.param
bigcode/self-oss-instruct-sc2-concepts
def _MapObjcType(t, other_types): """Returns an Objective-C type name for the given IDL type.""" if t.element_type: assert t.name == 'sequence' return 'NSArray<%s>*' % _MapObjcType(t.element_type, other_types) elif t.name in other_types: return 'Shaka%s*' % t.name else: type_map = { # ID...
bigcode/self-oss-instruct-sc2-concepts
def seq_names(fasta_file): """Get sequence names from fasta file.""" names = [] f = open(fasta_file) fasta = f.read() f.close() for a in fasta.split(">"): names.append(a.split("\n")[0]) return [a for a in names if a != ""]
bigcode/self-oss-instruct-sc2-concepts
def dict_to_aws_tags(d): """ Transforms a python dict {'a': 'b', 'c': 'd'} to the aws tags format [{'Key': 'a', 'Value': 'b'}, {'Key': 'c', 'Value': 'd'}] Only needed for boto3 api calls :param d: dict: the dict to transform :return: list: the tags in aws format >>> from pprint import pprin...
bigcode/self-oss-instruct-sc2-concepts
def legrende_polynomials(max_n, v): """ Returns the legendre polynomials Based on the algorithm here: http://uk.mathworks.com/help/symbolic/mupad_ref/orthpoly-legendre.html """ poly = [1, v] + [0] * (max_n - 1) for n in range(2, max_n + 1): poly[n] = (2 * n - 1) / n * v * poly[n - 1]...
bigcode/self-oss-instruct-sc2-concepts
def agg_count_distinct(df, group_key, counted_key): """Returns a Series that is the result of counting distinct instances of 'counted_key' within each 'group_key'. The series' index will have one entry per unique 'group_key' value. Workaround for lack of nunique aggregate function on Dask df. """ re...
bigcode/self-oss-instruct-sc2-concepts
def get_err_msg(code): """ This function formats an error message depending on what error code is generated by the HTTP request. We wrap the error message in a HTML page so that it can be displayed by the client. """ if code == '404': str = 'Function Not Implemented' else: st...
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def count_neuron_frequency(neurons): """ Calculate neuron frequency for given labels sorted by id number and frequency (ensure the same frequency still keep sort by number ) Counter usage example: https://stackoverflow.com/questions/2161752/how-to-count-the-frequency-of-the-elem...
bigcode/self-oss-instruct-sc2-concepts
def csv_format_gaus(gaus): """flattens and formats gaussian names and bounds for CSV file""" # gaus_names = [] # gaus_bounds = [] gaus_flat = [] for g in gaus: gaus_flat.append(g[0] if g[0] else "-") this_bounds = [g[5],g[6],g[1],g[2],g[3],g[4]] gaus_flat += this_bounds # return gaus_names, gaus_bounds ret...
bigcode/self-oss-instruct-sc2-concepts
import re def aggregate_alignments(align_tokens): """ Parse the alignment file. Return: - s2t: a dict mapping source position to target position - t2s: a dict mapping target position to source position """ s2t = {} t2s = {} # process alignments for align_token in align_tok...
bigcode/self-oss-instruct-sc2-concepts
def check_digit(option, num, min, max): """ 文字列numが整数かチェックし, min-maxの範囲の数値であればTrueを返す Args: option: エラーメッセージに表示する文字列を指定. ''の場合はエラーメッセージを表示しない. num: チェックする文字列 min: 数値の範囲の下限 max: 数値の範囲の上限 Returns: bool: Trueなら問題なし. Falseなら整数でないか範囲外. """ val = False try: num_int = int(num) ...
bigcode/self-oss-instruct-sc2-concepts
def thermal_diffusivity(tc, density, Cp): """ calc.thermal_diffusivity Calculation of thermal diffusivity Args: tc: thermal conductivity (float, W/(m K)) density: (float, g/cm^3) Cp: isobaric heat capacity (float, J/(kg K)) Return: Thermal diffusivity (float, m^2/s...
bigcode/self-oss-instruct-sc2-concepts
import gzip def avg_fastq_quality(fastq_gz: str) -> float: """Calculate the mean quality for a set of sequencing reads in gzipped FASTQ format with a quality offset of 33. fastq: Path to a gzip-compressed FASTQ formatted set of sequencing reads """ total_length = 0 total_quality = 0 # D...
bigcode/self-oss-instruct-sc2-concepts
def text_to_words(the_text): """ return a list of words with all punctuation removed, and all in lowercase. """ my_substitutions = the_text.maketrans( # If you find any of these "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&()*+,-./:;<=>?@[]^_`{|}~'\\", # Replace them by these...
bigcode/self-oss-instruct-sc2-concepts
def to_float(value: str) -> float: """Convert value to a floating point number""" return float(value)
bigcode/self-oss-instruct-sc2-concepts
def validate_on_batch( network, loss_fn, X, y_target ): """Perform a forward pass on a batch of samples and compute the loss and the metrics. """ # Do the forward pass to predict the primitive_parameters y_hat = network(X) loss = loss_fn(y_hat, y_target) return ( loss...
bigcode/self-oss-instruct-sc2-concepts
def unwrap_solt(dc): """ Extracts the augmented image from Solt format. :param dc: Solt datacontainer :return: Augmented image data """ return dc.data
bigcode/self-oss-instruct-sc2-concepts
def seen(params): """'.seen' & user || Report last time Misty saw a user.""" msg, user, channel, users = params if msg.startswith('.seen'): return "core/seen.py" else: return None
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def merge_dicts(*args: Dict[Any, Any]) -> Dict[Any, Any]: """ Successively merge any number of dictionaries. >>> merge_dicts({'a': 1}, {'b': 2}) {'a': 1, 'b': 2} >>> merge_dicts({'a': 1}, {'a': 2}, {'a': 3}) {'a': 3} Returns: Dict: ...
bigcode/self-oss-instruct-sc2-concepts
import calendar def get_month_number(month): """ Returns corresponding month number from month name """ abbr_to_num = {name: num for num, name in enumerate(calendar.month_abbr) if num} month_number = abbr_to_num[month.capitalize()[:3]] return month_number
bigcode/self-oss-instruct-sc2-concepts
def get_provenance_record(caption: str, ancestors: list): """Create a provenance record describing the diagnostic data and plots.""" record = { 'caption': caption, 'domains': ['reg'], 'authors': [ 'kalverla_peter', 'smeets_stef', 'brunner_lukas...
bigcode/self-oss-instruct-sc2-concepts
def color_negative_red(val): """ Takes a scalar and returns a string with the css property `'color: red'` for negative strings, black otherwise. """ color = "red" if val < 0 else "black" return "color: %s" % color
bigcode/self-oss-instruct-sc2-concepts
def _human_readable(size_in_bytes): """Convert an integer number of bytes into human readable form E.g. _human_readable(500) == 500B _human_readable(1024) == 1KB _human_readable(11500) == 11.2KB _human_readable(1000000) == """ if size_in_byt...
bigcode/self-oss-instruct-sc2-concepts
def flatten_list(a, result=None): """Flattens a nested list. >>> flatten_list([ [1, 2, [3, 4] ], [5, 6], 7]) [1, 2, 3, 4, 5, 6, 7] """ if result is None: result = [] for x in a: if isinstance(x, list): flatten_list(x, result) else: result...
bigcode/self-oss-instruct-sc2-concepts
import itertools def record_list(games, wins): """ Inputs: games (integer) - total number of games played wins (integer <= games) - total number of games won Returns: record_list (list) - all possible ways record could be achieved as binary """ record = list() losses =...
bigcode/self-oss-instruct-sc2-concepts
import io def spit(path, txt, encoding='UTF-8', append=False): """ Write a unicode string `txt` to file `path`. By default encoded as UTF-8 and truncates the file prior to writing Parameters ---------- path : str File path to file on disk txt : unicode Text content to wr...
bigcode/self-oss-instruct-sc2-concepts
def check_na(df, norm=False): """quick check the missing value stats for each column in a df.""" if norm: return df.isna().sum()/df.shape[0] else: return df.isna().sum()
bigcode/self-oss-instruct-sc2-concepts
def indice_to_pos(image_size, indice): """Converts indice of a pixel in image(index number in array of pixels) to x,y coordinates. Args: image_size: indice: index number in image's array of pixels. Returns: tuple: pair of values representing x,y coordinates corresponding to given i...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict from typing import Union from typing import Any def extract_outputs(path: List[str], results: Dict) -> Union[Any, List[Any]]: """Pull data out of results according to ref. :param path: The data location. :param results: The data to pull content from. :r...
bigcode/self-oss-instruct-sc2-concepts
def construct_bap_id(subscription_id, group_name, lb_name, address_pool_name): """Build the future BackEndId based on components name. """ return ('/subscriptions/{}' '/resourceGroups/{}' '/providers/Microsoft.Network' '/loadBalancers/{}' '/backendAddressPools...
bigcode/self-oss-instruct-sc2-concepts
def get_channel_block(peer_ex, ord_name, ord_namespace, channel, cmd_suffix): """Get channel block from Peer. Args: peer_ex (Executor): A Pod Executor representing a Peer. ord_name (str): Name of the orderer we wish to communicate with. ord_namespace (str): Namespace where the orderer r...
bigcode/self-oss-instruct-sc2-concepts
def _check_if_list_of_featuregroups_contains_featuregroup(featuregroups, featuregroup_name, version): """ Check if a list of featuregroup contains a featuregroup with a particular name and version Args: :featuregroups: the list of featuregroups to search through :featuregroup_name: the name...
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import Tuple def replace(s: str, src_dst: Iterable[Tuple[str, str]]) -> str: """ :param s: string :param src_dst: [(src1, dst1), (src2, dst2), ...] :return: string with srcX replaced with dstX """ for src, dst in src_dst: s = s.replace(src, dst)...
bigcode/self-oss-instruct-sc2-concepts
def _normalize_activity_share_format(share): """ Convert the input share format to the internally format expected by FTS3 {"A": 1, "B": 2} => [{"A": 1}, {"B": 2}] [{"A": 1}, {"B": 2}] => [{"A": 1}, {"B": 2}] """ if isinstance(share, list): return share new_share = list() for key,...
bigcode/self-oss-instruct-sc2-concepts
def _num_columns(data): """Find the number of columns in a raw data source. Args: data: 2D numpy array, 1D record array, or list of lists representing the contents of the source dataframe. Returns: num_columns: number of columns in the data. """ if hasattr(data, 'shape'): # True for numpy arr...
bigcode/self-oss-instruct-sc2-concepts
def equal(a, b, eps=0.001): """ Check if a and b are approximately equal with a margin of eps """ return a == b or (abs(a - b) <= eps)
bigcode/self-oss-instruct-sc2-concepts
def center_x(display_width: int, line: str) -> int: """ Find the horizontal center position of the given text line Parameters: display_width (int) : The character width of the screen/space/display line (int) : Line of text Returns: (int): Horizontal character number ...
bigcode/self-oss-instruct-sc2-concepts
def Parents(it): """ Return a generator to the parents of all the nodes in the passed iterable. Note that we first use a set to remove duplicates among the parents.""" return iter(set((n.GetParent() for n in it if n.GetParent() != None)))
bigcode/self-oss-instruct-sc2-concepts
def df_rename_col(data, col, rename_to, destructive=False): """Rename a single column data : pandas DataFrame Pandas dataframe with the column to be renamed. col : str Column to be renamed rename_to : str New name for the column to be renamed destructive : bool If ...
bigcode/self-oss-instruct-sc2-concepts
def identity(n): """ Return the identity matrix of size n :param n: size of the identity matrix to return :return: identity matrix represented by a 2 dimensional array of size n*n """ return [[1 if i == j else 0 for i in range(n)] for j in range(n)]
bigcode/self-oss-instruct-sc2-concepts
def create_coco_dict(images, categories, ignore_negative_samples=False): """ Creates COCO dict with fields "images", "annotations", "categories". Arguments --------- images : List of CocoImage containing a list of CocoAnnotation categories : List of Dict COCO categories ...
bigcode/self-oss-instruct-sc2-concepts
def reduce_breed_list(test): """ Input: cleaned dataset returns: a data set with the variable "breeds" reduced for cats and dogs. Removes the "Mix" part of the breed name and stripped white space. Made choice that Domestic Shorthair is equivalent to Domestic Shorthair Mix when it comes to cats...
bigcode/self-oss-instruct-sc2-concepts
import itertools def broadcast_lists(list_a, list_b): """Broadcast two lists. Similar behavior as ``gs.broadcast_arrays``, but for lists. """ n_a = len(list_a) n_b = len(list_b) if n_a == n_b: return list_a, list_b if n_a == 1: return itertools.zip_longest(list_a, list_b...
bigcode/self-oss-instruct-sc2-concepts
def any_endswith(items, suffix): """Return True if any item in list ends with the given suffix """ return any([item.endswith(suffix) for item in items])
bigcode/self-oss-instruct-sc2-concepts
def resolve_value(val): """ if given a callable, call it; otherwise, return it """ if callable(val): return val() return val
bigcode/self-oss-instruct-sc2-concepts
import json def read_data_from_file(filepath): """ This function reads data from the testbed saved into a file """ data = [] with open(filepath, "r") as file: for json_obj in file: data.append(json.loads(json_obj)) return data
bigcode/self-oss-instruct-sc2-concepts
def to_iso_date(timestamp): """Convert a UTC timestamp to an ISO8601 string. datetime instances can be constructed in alternate timezones. This function assumes that the given timestamp is in the UTC timezone. Args: timestamp(datetime): A datetime object in the UTC timezone. Returns: ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import string def kernelspec_dir(kernelspec_store: Path, kernel_id: str) -> Path: """Return path to the kernelspec directory for a kernel with a given ID Parameters ---------- kernelspec_store Path to the place kernelspec store where kernelspec dir should be p...
bigcode/self-oss-instruct-sc2-concepts
def test_iterable(value): """Check if it's possible to iterate over an object.""" try: iter(value) except TypeError: return False return True
bigcode/self-oss-instruct-sc2-concepts
def _write_to(string, path): """ Writes a string to a file on the server """ return "echo '" + string + "' > " + path
bigcode/self-oss-instruct-sc2-concepts
def get_plot_properties_for_trajectory(plot_nums:int, base_color:str='r') -> tuple: """ Get plot properties for trajectory. Args: plot_nums (int): The number of plots. base_color (str): Base color. Returns: tuple: (cs, alphas, linewidths, ...
bigcode/self-oss-instruct-sc2-concepts
def change_image_mode(img, label, args): """ Change image mode (RGB, grayscale, etc.) """ img = img.convert(args.get("image_mode")) label["image_mode"] = args.get("image_mode") return img, label, args
bigcode/self-oss-instruct-sc2-concepts
def get_all_attached_volumes(self): """ Get all the the volumes that are attached to an instance. :param boto.ec2.instance.Instance self: Current instance. :return: List of attached boto.ec2.volume.Volume :rtype: list """ return [v for v in self.connection.get_all_volumes() if v.at...
bigcode/self-oss-instruct-sc2-concepts
def get_prob_from_odds( odds, outcome ): """ Get the probability of `outcome` given the `odds` """ oddFor = odds[ outcome ] oddAgn = odds[ 1-outcome ] return oddFor / (oddFor + oddAgn)
bigcode/self-oss-instruct-sc2-concepts
def p2(max): """Problem 2 Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find...
bigcode/self-oss-instruct-sc2-concepts
from typing import Set import re def _replace_stopwords(text: str, words: Set[str], symbol: str = " ") -> str: """ Remove words in a set from a string, replacing them with a symbol. Parameters ---------- text: str stopwords : Set[str] Set of stopwords string to remove. symbol: str...
bigcode/self-oss-instruct-sc2-concepts
def frags_overlap_same_chrom(frags, start, end): """ get the fragments overlapping the interval [start, end], assuming all fragments in the input table are already on the correct chromosome """ f = frags.loc[((frags["start_pos"] < start) & (frags["end_pos"] > start)) | ((frags["sta...
bigcode/self-oss-instruct-sc2-concepts
def cp_model(k_min: float, mu_min: float, phi: float, cp=0.4) -> tuple: """ Build rock physics models using critical porosity concept. :param k_min: Bulk modulus of mineral (Gpa) :param mu_min: Shear modulus of mineral (Gpa) :param phi: Porosity (fraction) :param cp: critical porosity, default ...
bigcode/self-oss-instruct-sc2-concepts
def get_items(request, client): """ Get items using the request with the given parameters """ # query results result = client.quick_search(request) # get result pages items_pages = [page.get() for page in result.iter(None)] # get each single item return [item ...
bigcode/self-oss-instruct-sc2-concepts
def split_list(values, split_string=","): """ Convert a delimited string to a list. Arguments values -- a string to split split_string -- the token to use for splitting values """ return [value.strip() for value in values.split(split_string)]
bigcode/self-oss-instruct-sc2-concepts
import math def scale_value( value: float, input_lower: float, input_upper: float, output_lower: float, output_upper: float, exponent: float = 1, ) -> float: """Scales a value based on the input range and output range. For example, to scale a joystick throttle (1 to -1) to 0-1, we woul...
bigcode/self-oss-instruct-sc2-concepts
def user_select_csys(client, file_=None, max_=None): """Prompt the user to select one or more coordinate systems. and return their selections. Args: client (obj): creopyson Client. `file_` (str, optional): File name. Defaults is the currently active mode...
bigcode/self-oss-instruct-sc2-concepts
def copy_image_info(reference, target): """ Copy origin, direction, and spacing from one antsImage to another ANTsR function: `antsCopyImageInfo` Arguments --------- reference : ANTsImage Image to get values from. target : ANTsImAGE Image to copy values to Returns ...
bigcode/self-oss-instruct-sc2-concepts
def get_task_segments(workflow): """ Returns a dict that has the corresponding segment for each task. Segments are zero-based numbered :param workflow: :return: """ visited = dict() segment = dict() def get_segment(task): """ Calculates recursively the depth of the w...
bigcode/self-oss-instruct-sc2-concepts
def get_join_parameters(join_kwargs): """ Convenience function to determine the columns to join the right and left DataFrames on, as well as any suffixes for the columns. """ by = join_kwargs.get("by", None) suffixes = join_kwargs.get("suffixes", ("_x", "_y")) if isinstance(by, tuple): ...
bigcode/self-oss-instruct-sc2-concepts
def function_sync(from_fun, to_fun): """ Copy name and documentation from one function to another. This function accepts two functional arguments, ``from_fun`` and ``to_fun``, and copies the function name and documentation string from the first to the second, returning the second. This is useful wh...
bigcode/self-oss-instruct-sc2-concepts
def daily_profit(daily_mined: float, xmr_price: float, kwh: float, kwh_cost: float, pool_fee: float, precision: int) -> float: """ Computes how much money you gain after paying the daily mining expense. Formula: (daily_income - daily_electricity_cost) * (100% - pool_fee) :param daily_mined: Float. Amou...
bigcode/self-oss-instruct-sc2-concepts
import re def snake(string): """Convert string to snake case Implementation must be consistent with tf.Module's camel_to_snake in github.com/tensorflow/tensorflow/blob/master/tensorflow/python/module/module.py """ return re.sub(r"((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))", r"_\1", string).lower()
bigcode/self-oss-instruct-sc2-concepts
def log_metrics(metrics, time, task_id, acc_db, loss_db): """ Log accuracy and loss at different times of training """ print('epoch {}, task:{}, metrics: {}'.format(time, task_id, metrics)) # log to db acc = metrics['accuracy'] loss = metrics['loss'] loss_db[task_id][time-1] = loss acc_db[task_id][time-1] = ac...
bigcode/self-oss-instruct-sc2-concepts
import functools def list_generalizer(f): """ A decorator that makes a function work for either a single object or a list of objects by calling the function on each element Parameters ---------- :param f: the function to decorate, of the form f(data, *args, **kwargs). Returns -------...
bigcode/self-oss-instruct-sc2-concepts
import json def get_target_names(json_label_decode): """Get encode of label Args: json_label_decode (string): path to json file Returns: [dict] encode of label """ if json_label_decode: with open(json_label_decode) as f: label_decode = json.load(f) t...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def hash256(string): """ Create a hash from a string """ grinder = hashlib.sha256() grinder.update(string.encode()) return grinder.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
import re def config_attrs(config): """Returns config attributes from a Config object""" p = re.compile('^[A-Z_]+$') return filter(lambda attr: bool(p.match(attr)), dir(config))
bigcode/self-oss-instruct-sc2-concepts
import logging def _get_sac_origin(tr): """ Get the origin time of an event trace in sac format. :param tr: A event trace :return origin: origin time of an event .. Note:: The trace should be sac formatted. """ try: origin = tr.stats.starttime - tr.stats.sac.b + tr.stats...
bigcode/self-oss-instruct-sc2-concepts
def word_count(phrase): """ Count occurrences of each word in a phrase excluding punctuations""" punctuations = '''!()-[]{};:"\<>./?@#$%^&*~''' counts = dict() no_punct = "" for char in phrase: if char not in punctuations: no_punct = no_punct + char no_punct = no_punct.repla...
bigcode/self-oss-instruct-sc2-concepts
def renew_order(order, icon): """Returns the new order with the contracted indices removed from it.""" return [i for i in order if i not in icon]
bigcode/self-oss-instruct-sc2-concepts
def gcd(x, y): """Calculate greatest common divisor of x and y.""" if not y: return x if x % y == 0: return y return gcd(y, x % y)
bigcode/self-oss-instruct-sc2-concepts
def resource_wrapper(data): """Wrap the data with the resource wrapper used by CAI. Args: data (dict): The resource data. Returns: dict: Resource data wrapped by a resource wrapper. """ return { 'version': 'v1', 'discovery_document_uri': None, 'discovery_nam...
bigcode/self-oss-instruct-sc2-concepts
def exists(item, playlist): """Return a boolean True if playlist contains item. False otherwise. """ for i in playlist: #for each item in playlist if i.song_id == item.song_id: #check if the primary key is equal return True return False
bigcode/self-oss-instruct-sc2-concepts
def mask_val(val, width): """mask a value to width bits""" return val & ((1 << width) - 1)
bigcode/self-oss-instruct-sc2-concepts
def get_length(dna): """ (str) -> int Return the length of the DNA sequence dna. >>> get_length('ATCGAT') 6 >>> get_length('ATCG') 4 """ return len(dna)
bigcode/self-oss-instruct-sc2-concepts
import re def get_function_name(line): """Get name of a function.""" func_name = re.split(r"\(", line)[0] func_name = re.split(r" ", func_name)[-1] func_name = re.sub(r"(\*|\+|\-)", r"", func_name) return func_name
bigcode/self-oss-instruct-sc2-concepts
import requests import json def get_swagger_dict(api_url: str) -> dict: """ Gets the lusid.json swagger file Parameters ---------- api_url : str The base api url for the LUSID instance Returns ------- dict The swagger file as a dictionary """ swagger_path = "...
bigcode/self-oss-instruct-sc2-concepts
def calculate_error(source, target, base, alpha): """ Calculates error for a given source/target/base colors and alpha """ alpha /= 255.0 alpha_inverse = 1.0 - alpha return abs(target - alpha * source - alpha_inverse * base)
bigcode/self-oss-instruct-sc2-concepts
def cal_num_procs(world_size: int, gnx: int, gny: int): """Calculate the number of MPI ranks in x and y directions based on the number of cells. Arguments --------- world_size : int Total number of MPI ranks. gnx, gny : int Number of cells globally. Retunrs ------- pnx,...
bigcode/self-oss-instruct-sc2-concepts
def _rshift_nearest(x, shift): """Given an integer x and a nonnegative integer shift, return closest integer to x / 2**shift; use round-to-even in case of a tie. """ b, q = 1 << shift, x >> shift return q + (2 * (x & b - 1) + (q & 1) > b)
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def parse_path(path: str) -> Tuple[str, str]: """Split a full S3 path in bucket and key strings. 's3://bucket/key' -> ('bucket', 'key') Parameters ---------- path : str S3 path (e.g. s3://bucket/key). Returns ------- Tuple[str, str] Tuple of ...
bigcode/self-oss-instruct-sc2-concepts
def is_cli_tool(req): """ Returns true if the user-agent looks like curl or wget """ user_agent = req.headers.get_first("User-Agent", "") if user_agent.startswith('curl'): return True if user_agent.startswith('Wget'): return True return False
bigcode/self-oss-instruct-sc2-concepts
def valid_odd_size(size): """ Validates that a kernel shape is of odd ints and of with 2 dimensions :param size: the shape (size) to be checked :return: False if size is invalid """ if type(size) not in (list, tuple): return False if len(size) != 2: return False if size[...
bigcode/self-oss-instruct-sc2-concepts
def make_url(photo: dict): """ Get download URL for photo :param photo: photo data as returned from API """ return photo["baseUrl"] + "=d"
bigcode/self-oss-instruct-sc2-concepts
def adjacent_vectors(vector_field, neighbors): """ Query the vectors neighboring a vector field entry. """ return [vector_field.vector(key) for key in neighbors]
bigcode/self-oss-instruct-sc2-concepts
def dictfetchall(cursor) -> list: """ 從 cursor 獲取的資料行轉換成元素為字典的列表 [ { 'column1': '...', 'column2': '...', ...': '...', }, { 'column1': '...', 'column2': '...', '...': '...', }, ] """ columns = ...
bigcode/self-oss-instruct-sc2-concepts
def split_and_strip(sep, s): """ Split input `s` by separator `sep`, strip each output segment with empty segment dropped. """ return [y for y in (x.strip() for x in s.split(sep)) if len(y) > 0]
bigcode/self-oss-instruct-sc2-concepts
def build_post_data_from_object(model, obj, ignore=["id"]): """ Build a payload suitable to a POST request from given object data. Arguments: model (django.db.models.Model): A model object used to find object attributes to extract values. obj (object): A instance of given model ...
bigcode/self-oss-instruct-sc2-concepts
def full_name(user): """ returns users full name. Args: user (User): user object. Returns: str: full name from profile. """ if not user or not user.profile: return None profile = user.profile first = profile.first_name or profile.user.username last = " {}"....
bigcode/self-oss-instruct-sc2-concepts
def piecewise_compare(a, b): """ Check if the two sequences are identical regardless of ordering """ return sorted(a) == sorted(b)
bigcode/self-oss-instruct-sc2-concepts
def patch_many(mocker): """ Makes patching many attributes of the same object simpler """ def patch_many(item, attributes, autospec=True, **kwargs): for attribute in attributes: mocker.patch.object(item, attribute, autospec=autospec, **kwargs) return patch_many
bigcode/self-oss-instruct-sc2-concepts
def make_readable_pythonic(value: int) -> str: """Make readable time (pythonic). Examples: >>> assert make_readable(359999) == "99:59:59" """ return f"{value / 3600:02d}:{value / 60 % 60:02d}:{value % 60:02d}"
bigcode/self-oss-instruct-sc2-concepts
def _get_index(x, x_levels): """Finds element in list and returns index. Parameters ---------- x: float Element to be searched. x_levels: list List for searching. Returns ------- i: int Index for the value. """ for i, value in enumerate(x_levels): ...
bigcode/self-oss-instruct-sc2-concepts