seed
stringlengths
1
14k
source
stringclasses
2 values
def to_currency(cents: int) -> str: """Convert a given number of cent into a string formated dollar format Parameters ---------- cents : int Number of cents that needs to be converted Returns ------- str Formated dollar amount """ return f"${cents / 100:.2f}"
bigcode/self-oss-instruct-sc2-concepts
def sum_of_self_exponential(numbers): """ Sums each digit raised to the power of itself Ex: sum_of_self_exponential([2, 3, 4]) = 2^2 + 3^3 + 4^4 = 287 """ return sum(pow(number, number) for number in numbers)
bigcode/self-oss-instruct-sc2-concepts
def subset_spike_time_by_channel(spike_time_labels, channel_id): """Subset spike times by specific channel ID Args: spike_time_labels: A numpy array of shape (n_spikes, 2), each row is [time, channel_id] channel_id: int, channel_id Return: a subset of spike_time_labels from a pa...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def check_date_time( y: int, mon: int, d: int, h: int = 0, minute: int = 0, sec: int = 0 ) -> bool: """Checks if the provided date and time is valid.""" try: datetime(y, mon, d, h, minute, sec) except ValueError: return False return True
bigcode/self-oss-instruct-sc2-concepts
def square(x): """Return the square of `x`. Parameters ---------- x : int or float The input number. Returns ------- x2 : same type as `x` The square of the input value. Examples -------- >>> square(5) 25 """ return x ** 2
bigcode/self-oss-instruct-sc2-concepts
def build_cluster_info(config): """ Construct our cluster settings. Dumps global settings config to each cluster settings, however, does not overwrite local cluster settings. Cluster config takes precedence over global. Use global config for generic info to be applied by default. Note: ...
bigcode/self-oss-instruct-sc2-concepts
def get_lhc_sequence_filename_and_bv(beam: int, accel: str = 'lhc'): """ Return the default sequence filename, the sequence name and the bv-flag for the given beam. Args: beam (int): beam to use. accel (str): accelerator name ('lhc' or 'hllhc'). """ as_built = '_as-built' if accel.l...
bigcode/self-oss-instruct-sc2-concepts
def fatorial(a, show=False): """ Calcula o fatorial do valor param: a: valor a ser calculado param: show: (bool opcional) mostra o calculo return: resultado no fatorial """ f = 1 for i in range(a, 0, -1): f *= i if show: if i == 1: ...
bigcode/self-oss-instruct-sc2-concepts
def key2struct(jsonkey:str): """ string key of type my_key --> MyKey """ parts = jsonkey.split('_') ret = "" for w in parts: ret += w.capitalize() return ret
bigcode/self-oss-instruct-sc2-concepts
def calc_dihedral(v1, v2, v3, v4): """Calculate dihedral angle method. Calculate the dihedral angle between 4 vectors representing 4 connected points. The angle is in ]-pi, pi]. :param v1, v2, v3, v4: the four points that define the dihedral angle :type v1, v2, v3, v4: L{Vector} """ ab...
bigcode/self-oss-instruct-sc2-concepts
def nodes_cut_fully(graph, dest): """ Return the nodes divided up fully into separate partitions. Order is established by BFS. """ return [[v["id"]] for v in graph.bfsiter(dest)]
bigcode/self-oss-instruct-sc2-concepts
def encode_literal_num(n: int, size: int) -> bytes: """Send numbers as literal string in decimal `size`: target length of the byte str example: 123 -> ["0","0",... , "1","2","3"] """ s = str(n) s = "0" * (size - len(s)) + s # prevent overflow assert s[0] == "0" return s.encode("utf-8...
bigcode/self-oss-instruct-sc2-concepts
def centerstring(string,width): """ Pad a string to a specific width """ return " "*((width-len(string))/2)+string
bigcode/self-oss-instruct-sc2-concepts
def calculate_dc_dT_CTM(temp): """ Seabird eq: dc/dT = 0.1 * (1 + 0.006 * [temperature - 20]) """ dc_dT = 0.1 * (1 + 0.006 * (temp - 20)) return dc_dT
bigcode/self-oss-instruct-sc2-concepts
def get_default_semantics(n_dim): """ Generate default semantics for n_dim dimensions. Parameters ---------- n_dim : int Number of dimensions. Indicating the number of variables of the model. Returns ------- semantics: dict Generated model description. """ sem...
bigcode/self-oss-instruct-sc2-concepts
def slice_to_list(s): """ Converts a slice object to a list of indices """ step = s.step or 1 start = s.start stop = s.stop return [x for x in range(start,stop,step)]
bigcode/self-oss-instruct-sc2-concepts
def stoi(n): """String to integer. Handles negative values.""" return int(str(n).replace("-", "")) * -1 if "-" in n else int(n)
bigcode/self-oss-instruct-sc2-concepts
def default_iid_function(sample): """ The default function for turning a Bgen sample into a two-part :attr:`pysnptools.distreader.DistReader.iid`. If the Bgen sample contains a single comma, we split on the comma to create the iid. Otherwise, the iid will be ('0',sample) >>> default_iid_fun...
bigcode/self-oss-instruct-sc2-concepts
def vis_params_rgb(bands=['R', 'G', 'B'], minVal=0, maxVal=3000, gamma=1.4, opacity=None): """ Returns visual parameters for a RGB visualization :param bands: list of RGB bandnames, defaults to ['R', 'G', 'B'] :param minVal: value to map to RGB value 0, defaults to 0 :param maxVal: value to map to R...
bigcode/self-oss-instruct-sc2-concepts
def nonzero(matrix, row): """ usage: >>> from scipy.sparse import csr_matrix >>> m = csr_matrix([[1, 0, 2], [3, 0, 0]]) >>> print nonzero(m, 0) set([0, 2]) >>> print nonzero(m, 1) set([0]) """ return set(matrix[row].indices)
bigcode/self-oss-instruct-sc2-concepts
import math def qubits_needed(number_of_sides): """ The number of qubits needed for a die of n faces. """ return int(math.ceil(math.log(number_of_sides, 2)))
bigcode/self-oss-instruct-sc2-concepts
def asURN(epsg): """ convert EPSG code to OGC URN CRS ``urn:ogc:def:crs:epsg::<code>`` notation """ return "urn:ogc:def:crs:epsg::%d" % int(epsg)
bigcode/self-oss-instruct-sc2-concepts
import string import random def random_string( length: int, characters: str = string.ascii_letters + string.digits ) -> str: """ Generates a random string of a given length from a given character set. Args: length: The length of the string to generate. characters: A string containing ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_config_dir() -> Path: """Returns the path to the config dir""" return Path(__file__).resolve().parent.parent / 'config'
bigcode/self-oss-instruct-sc2-concepts
def merge(user, default): """Merges a user configuration with the default one. Merges two dictionaries, replacing default values of similar matching keys from user. Parameters: user (dict): A user defined dictionary default (dict): Returns: A new merged diction...
bigcode/self-oss-instruct-sc2-concepts
def main(event: dict, context: dict) -> dict: """ Simple lambda handler to echo back responses :param event: A JSON-formatted document that contains data for a Lambda function to process. :param context: Provides methods and properties that provide information about the invocation, function, and ru...
bigcode/self-oss-instruct-sc2-concepts
def tuple_scale(tup: tuple, factor) -> tuple: """Return the tuple with each entry scaled by a factor and rounded.""" return tuple(round(i * factor, 5) for i in tup)
bigcode/self-oss-instruct-sc2-concepts
def first_word(sentence): """Return first word of a string.""" try: return sentence.split(' ', 1)[0] except: return None
bigcode/self-oss-instruct-sc2-concepts
def remove_if(rng, pred): """ Remove each element from `rng` for which `pred` evaluates to true by swapping them to the end of the sequence. The function returns the number of elements retained. """ j = 0 for i, x in enumerate(rng): if pred(x): continue if i != j...
bigcode/self-oss-instruct-sc2-concepts
def c_linker_options(ctx, blacklist=[]): """Extracts flags to pass to $(CC) on link from the current context Args: ctx: the current context blacklist: Any flags starts with any of these prefixes are filtered out from the return value. Returns: A list of command line flags """ cpp = ctx.fra...
bigcode/self-oss-instruct-sc2-concepts
def stack_projection_args(cli_args): """ Converts the flat processing options into nested JSON Args: cli_args (dict): arguments parsed from the CLI Returns: dict: nested dictionary grouped by types/usage Example: >>> stack_projection_args({'target_projection': 'utm', 'zone': 1...
bigcode/self-oss-instruct-sc2-concepts
def validate_reviews(df): """ Enrich no review records with default review scores. """ df['first_review'].fillna(value='1991-01-01', inplace=True) df['last_review'].fillna(value='0', inplace=True) df['review_scores_rating'].fillna(value=0, inplace=True) df['review_scores_accuracy'].fillna(value...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def _create_stack_id(name: str) -> str: """ Creates a stack name that should be unique within the region. Args: name (str): Name of the project for which to create the stack ID. Returns: (str): The generated stack name. """ dt_string = datetime.n...
bigcode/self-oss-instruct-sc2-concepts
def parse_version(vers_string): """Parse a version string into its component parts. Returns a list of ints representing the version, or None on parse error.""" vers_string = vers_string.strip() vers_parts = vers_string.split('.') if len(vers_parts) != 4: return None try: major =...
bigcode/self-oss-instruct-sc2-concepts
def matrix_block(M, rows, cols): """ Select a block of a matrix given by the row and column indices """ return M[rows,:][:,cols]
bigcode/self-oss-instruct-sc2-concepts
import random def bootstrap_sample(data): """randomly sample len(data) elements with replacement""" return [random.choice(data) for _ in data]
bigcode/self-oss-instruct-sc2-concepts
def nested_get(dictionary, keys): """Get nested fields in a dictionary""" to_return = dictionary.get(keys[0], None) for key in keys[1:]: if to_return: to_return = to_return.get(key, None) else: break return to_return
bigcode/self-oss-instruct-sc2-concepts
def format_long_time(timespan): """ Formats a long timespan in a human-readable form with a precision of a 100th of a second. """ formatted_time = [] units = (('d', 24 * 60 * 60), ('h', 60 * 60), ('m', 60), ('s', 1)) for unit, length in units: value = int(timespan / length) ...
bigcode/self-oss-instruct-sc2-concepts
def overrides(interface_class): """ To be used as a decorator, it allows the explicit declaration you are overriding the method of class from the one it has inherited. It checks that the name you have used matches that in the parent class and returns an assertion error if not """ def over...
bigcode/self-oss-instruct-sc2-concepts
def _build_param_docstring(param): """Builds param docstring from the param dict :param param: data to create docstring from :type param: dict :returns: string giving meta info Example: :: status (string) : Statuses to be considered for filter from_date (string) : Start date filter...
bigcode/self-oss-instruct-sc2-concepts
import uuid def create_api_release(client, resource_group_name, service_name, api_id, api_revision, release_id=None, if_match=None, notes=None): """Creates a new Release for the API.""" if release_id is None: release_id = uuid.uuid4().hex api_revision_to_release_and_make_current = "/apis/" + api_...
bigcode/self-oss-instruct-sc2-concepts
def predict(model, X, threshold = 0.3): """ desc: given an x dataframe, make a prediction using our model args: model (Sklearn.pipeline Pipeline) : Trained model we are going to evaluate X (pd.DataFrame): X values passed to model. returns: y (int) : 1 or 0, 1 for ...
bigcode/self-oss-instruct-sc2-concepts
def evaluate(labels, predictions): """ Given a list of actual labels and a list of predicted labels, return a tuple (sensitivity, specificity). Assume each label is either a 1 (positive) or 0 (negative). `sensitivity` should be a floating-point value from 0 to 1 representing the "true positive...
bigcode/self-oss-instruct-sc2-concepts
def fact(n): """ Return 1, if n is 1 or below, otherwise, return n * fact(n-1). """ return 1 if n <= 1 else n * fact(n - 1)
bigcode/self-oss-instruct-sc2-concepts
import tempfile def create_dir(basedir=''): """ Create a unique, temporary directory in /tmp where processing will occur Parameters ---------- basedir : str The PATH to create the temporary directory in. """ return tempfile.mkdtemp(dir=basedir)
bigcode/self-oss-instruct-sc2-concepts
def convert_dict(dicts: dict) -> dict: """ Convert all the values in a dictionary to str and replace char. For example: <class 'torch.Tensor'>(unknow type) to torch.Tensor(str type). Args: dicts (`dict`): The dictionary to convert. Returns: (`dict`) The...
bigcode/self-oss-instruct-sc2-concepts
def dimensions_match(matrix1, matrix2): """ This function checks if the orders of the given matrices match. Arguments: matrix1 {Matrix} - The first Matrix object matrix2 {Matrix} - The second Matrix object Returns: boolean-- True or False depending on if their orders match or not. """ ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from typing import Optional from typing import Union from typing import Pattern from typing import List import re def get_all_files_in_directory( path: Path, pattern: Optional[Union[Pattern, str]] = None ) -> List[Path]: """ Returns all the files in a directory structure. For...
bigcode/self-oss-instruct-sc2-concepts
def run_on_nested_arrays2(a, b, func, **param): """run func on each pair of element in a and b: a and b can be singlets, an array, an array of arrays, an array of arrays of arrays ... The return value is a flattened array """ if isinstance(a, list): if not isinstance(b, list): ra...
bigcode/self-oss-instruct-sc2-concepts
def format_output(result): """Format output to preserve consistence in output""" formatted = "WPM: %-3s " % result["wpm"] formatted += "KPS: %-3s " % result["kps"] formatted += "Error: %%-3s " % result["error"] formatted += "Strokes: %d " % result["strokes"] return formatted
bigcode/self-oss-instruct-sc2-concepts
import torch def face_area(vertices, faces): """ Computes area of each faces using cross product Args: vertices (torch.tensor): Vx3, xyz coordinates of vertices faces (torch.tensor): Fx3, index of vertices for each face Returns: (torch.tensor): F, area of each face """ ...
bigcode/self-oss-instruct-sc2-concepts
def triangular_number(x: int) -> int: """ Get the xth triangular number """ return (x * (x + 1)) // 2
bigcode/self-oss-instruct-sc2-concepts
def mnet_kwargs(config, task_id, mnet): """Keyword arguments that should be passed to the main network. In particular, if batch normalization is used in the main network, then this function makes sure that the main network chooses the correct set if batch statistics in case they are checkpointed (i.e.,...
bigcode/self-oss-instruct-sc2-concepts
from numbers import Number def dict_splicer(plot_dict,Ld,Lx): """Dictionary constructor for plotting Base-level function used by most other plotting functions to construct a list of dictionaries, each containing the passed arguments to the underlying plotting calls for each different dataset. Parameters ----...
bigcode/self-oss-instruct-sc2-concepts
def calc_bpe_exchange_current(K_standard_rate_constant, c_bulk_oxidized, c_bulk_reduced, alpha_transfer_coefficient=0.5): """ The exchange current density at a specific BPE location units: Coulombs/s*m2 Notes: K_standard_rate_constant: usually between 2 and 6 c_bulk (oxidized and reduced...
bigcode/self-oss-instruct-sc2-concepts
def safe_join(separator, values): """Safely join a list of values. :param separator: The separator to use for the string. :type separator: str :param values: A list or iterable of values. :rtype: str """ _values = [str(i) for i in values] return separator.join(_values)
bigcode/self-oss-instruct-sc2-concepts
from typing import List def keys_exists(multi_dict: dict, keys: List[str]) -> bool: """Check if multi-level dict has specific keys""" _multi_dict = multi_dict for key in keys: try: _multi_dict = _multi_dict[key] except KeyError: return False return True
bigcode/self-oss-instruct-sc2-concepts
def fix_url(url): """Add http:// prefix to url if it doesn't have one.""" if "://" not in url: if url.startswith("//"): url = "http:" + url else: url = "http://" + url return(url)
bigcode/self-oss-instruct-sc2-concepts
def get_timecode(td): """Convert a timedelta to an ffmpeg compatible string timecode. A timecode has the format HH:MM:SS, with decimals if needed. """ seconds = td.total_seconds() hours = int(seconds // 3600) seconds %= 3600 minutes = int(seconds // 60) seconds %= 60 str_seconds,...
bigcode/self-oss-instruct-sc2-concepts
def _end_of_set_index(string, start_index): """ Returns the position of the appropriate closing bracket for a glob set in string. :param string: Glob string with wildcards :param start_index: Index at which the set starts, meaning the position right behind the opening b...
bigcode/self-oss-instruct-sc2-concepts
def fix_brace_c(a, b): """Move any `}`s between the contents of line `a` and line `b` to the end of line `a`. :param a: A line of Lean code, ending with `\n' :param b: A line of Lean code, ending with `\n' :returns: A tuple `(anew, bnew, merge)`, where `anew` and `bnew` are `a` and `b` with co...
bigcode/self-oss-instruct-sc2-concepts
def f_sq(num: int) -> int: """Return [num] squared.""" return num**2
bigcode/self-oss-instruct-sc2-concepts
def container(**criteria): """ Turns keyword arguments into a formatted container criteria. """ criteria = ['%s="%s"' % (key, val) for key, val in criteria.items()] return '[%s]' % ' '.join(criteria)
bigcode/self-oss-instruct-sc2-concepts
import re def camelback2snake(camel_dict: dict): """Convert the passed dictionary's keys from camelBack case to snake_case.""" converted_obj = {} for key in camel_dict.keys(): converted_key = re.sub(r'[A-Z]', lambda x: '_' + x.group(0).lower(), key) converted_obj[converted_key] = camel_dic...
bigcode/self-oss-instruct-sc2-concepts
def find_on_grid(grid, wanted): """Find location of wanted on grid.""" for row_no, row in enumerate(grid): for col_no, col in enumerate(row): if col == wanted: return (row_no, col_no) return None
bigcode/self-oss-instruct-sc2-concepts
import re def get_r_filename(r_file): """Remove the file extension from an r_file using regex. Probably unnecessary but improves readability Parameters ---------- r_file : string name of R file including file extension Returns ------- string name of R file without f...
bigcode/self-oss-instruct-sc2-concepts
def set_show_scroll_bottleneck_rects(show: bool) -> dict: """Requests that backend shows scroll bottleneck rects Parameters ---------- show: bool True for showing scroll bottleneck rects """ return {"method": "Overlay.setShowScrollBottleneckRects", "params": {"show": show}}
bigcode/self-oss-instruct-sc2-concepts
import re def count_vocals(file_name, start=0, end=100): """ Count vocals in specified file Args: file_name (str): path to file start (int): first line in file end (int): last line in file Returns: int : number of vocals in file """ vocals_number = 0...
bigcode/self-oss-instruct-sc2-concepts
def _requirements_with_three_elements(requirements): """Return true if requirement list looks like ['<', '$ram', '1024'].""" return (isinstance(requirements, list) and len(requirements) == 3 and isinstance(requirements[0], str) and isinstance(requirements[1], str) and ...
bigcode/self-oss-instruct-sc2-concepts
def _check_mutual_preference(resident, hospital): """ Determine whether two players each have a preference of the other. """ return resident in hospital.prefs and hospital in resident.prefs
bigcode/self-oss-instruct-sc2-concepts
def posting(client, route, title_field='test title', content_field='test body', is_page=False, categories_field_0='', categories_field_1='', categories_field_2='', publish='yes', preview=None): """Helper function to create/edit posts and drafts by posting to our routes. This helper ...
bigcode/self-oss-instruct-sc2-concepts
import re def create_paired_list(value): """ Create a list of paired items from a string. :param value: the format must be 003,003,004,004 (commas with no space) :type value: String :returns: List :example: create_paired_list('003,003,004,004') [['003','003'...
bigcode/self-oss-instruct-sc2-concepts
import typing def get_ctffind_4_1_0_header_names() -> typing.List[str]: """ Returns the header names for the ctffind4 input file. Arguments: None Returns: List of names """ return [ 'DefocusU', 'DefocusV', 'DefocusAngle', 'PhaseShift', 'CtfFigu...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def _get_dataset_path_from_args(args_dataset): """Remove 'benchmark:' from the dataset name and add .csv suffix. Parameters ---------- args_dataset : str Name of the dataset. Returns ------- str Dataset name without 'benchmark:' if it started with...
bigcode/self-oss-instruct-sc2-concepts
import re def normalize_name(str): """Converts names into JavaScript-safe ascii string keys that adhere to the expected conventions.""" if not str: return str # The Tam\u2013Tara Deepcroft str = re.sub(r"\u2013", "-", str) # The <Emphasis>Whorleater</Emphasis> Extreme str = re.sub(r"...
bigcode/self-oss-instruct-sc2-concepts
def _cast_value_to_type(value, cast_type_string): """Return the value casted to the type specified by the cast_type_string, as defined in the type maps in the ReferenceGenome object's variant_key_map field """ if cast_type_string == 'Integer': return int(value) elif cast_type_string == 'Floa...
bigcode/self-oss-instruct-sc2-concepts
def merge(numbers_list): """ Mergesort algorithm :param numbers_list: list of number to order :return: new list with numbers ordered """ if len(numbers_list) <= 1: return numbers_list result = [] # identify the middle item mid = len(numbers_list) // 2 numbers_list_a = m...
bigcode/self-oss-instruct-sc2-concepts
def fizz_buzz_elif(n): """ Return the correct FizzBuzz value for n by testing divisibility in an if-elif. """ divisible_by_3 = n % 3 == 0 divisible_by_5 = n % 5 == 0 if divisible_by_3 and divisible_by_5: return "Fizz Buzz!" elif divisible_by_3: return "Fizz!" elif div...
bigcode/self-oss-instruct-sc2-concepts
def factorial(n): """ Input: a number. Output: find the factorial of the input number via iteration. """ product = 1 if n == 0: return 0 for thing in range(1, n+1): product *= thing return product
bigcode/self-oss-instruct-sc2-concepts
def npix_above_threshold(pix, thr): """ Calculate number of pixels above a given threshold Parameters ---------- pix: array-like array with pixel content, usually pe thr: float threshold for the pixels to be counted Returns ------ npix_above_threshold: float ...
bigcode/self-oss-instruct-sc2-concepts
def SplitRange(regression): """Splits a range as retrieved from clusterfuzz. Args: regression: A string in format 'r1234:r5678'. Returns: A list containing two numbers represented in string, for example ['1234','5678']. """ if not regression: return None revisions = regression.split(':') ...
bigcode/self-oss-instruct-sc2-concepts
def is_import(line): """Returns if the line is an import.""" return "import " in line or "__import__" in line
bigcode/self-oss-instruct-sc2-concepts
import pickle def pickle_from_file(path): """Load the pickle file from the provided path and returns the object.""" return pickle.load(open(path, 'rb'))
bigcode/self-oss-instruct-sc2-concepts
def truncate(text, max_length=1024): """Limit huge texts in number of characters""" text = str(text) if text and len(text) >= max_length: return text[:max_length//2-3] + " ... " + text[-max_length//2+3:] return text
bigcode/self-oss-instruct-sc2-concepts
def get_outliers(df, forecast, today_index, predict_days=21): """ Combine the actual values and forecast in a data frame and identify the outliers Args ---- df : pandas DataFrame The daily time-series data set contains ds column for dates (datetime types such as datetime64[ns]) and ...
bigcode/self-oss-instruct-sc2-concepts
from io import BytesIO from io import StringIO from zipfile import ZipFile import requests def get_zip_file(url, filepath): """Gets zip file from url. Args: url: A string, the url of zip file. filepath: A string, the file path inside the zip file. Returns: A String, the content of ...
bigcode/self-oss-instruct-sc2-concepts
def check_vocab_file(file, special_tokens): """Check a vocab file, adding special tokens to it. Args: file: A constant string, path of the vocab file special_tokens: A list of special tokens Returns: The size of the processed vocab. """ vocabs = set() with open(file, mo...
bigcode/self-oss-instruct-sc2-concepts
def extract_vertices_from_name(name: str) -> str: """Takes the number of vertices from a string of the form: '{type}_{num_vertices}_{k}_{rank}_{m1}_{m2}' """ suffix = name[name.find('_')+1:] return suffix[:suffix.find('_')]
bigcode/self-oss-instruct-sc2-concepts
def EncodeFileRecordSegmentReference(FileRecordSegmentNumber, SequenceNumber): """Encode a file record segment reference and return it.""" return (SequenceNumber << 48) | FileRecordSegmentNumber
bigcode/self-oss-instruct-sc2-concepts
def to_setting( checked: bool, text: str, active_style='class:toolbar-setting-active', inactive_style='', mouse_handler=None, ): """Apply a style to text if checked is True.""" style = active_style if checked else inactive_style if mouse_handler: return (style, text, mouse_handle...
bigcode/self-oss-instruct-sc2-concepts
def parse_compute_version(compute_version): """Parse compute capability string to divide major and minor version Parameters ---------- compute_version : str compute capability of a GPU (e.g. "6.0") Returns ------- major : int major version number minor : int min...
bigcode/self-oss-instruct-sc2-concepts
def remove_dup_loop(input_list): """ Remove all duplicates in list. Using loop method. Arguments: input_list -- a list input Returns: new_list -- a list remove all the duplicates. """ new_list = [] new_list.extend(i for i in input_list if i not in new_list) return new_l...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from pathlib import Path import json def load_json(ffp: Union[Path, str]): """Loads a data from a json file""" with open(ffp, "r") as f: return json.load(f)
bigcode/self-oss-instruct-sc2-concepts
def assignment_history(task): """ Return all assignments for `task` ordered by `assignment_counter`. Args: task (orchestra.models.Task): The specified task object. Returns: assignment_history ([orchestra.models.TaskAssignment]): All assignments for `task` ordere...
bigcode/self-oss-instruct-sc2-concepts
def coords_in_image(rr_cc, shape): """ Taken almost directly from skimage.draw(). Decided best not to do any formatting implicitly in the shape models. Attributes ---------- rr_cc : len(2) iter rr, cc returns from skimage.draw(); or shape_models.rr_cc shape : ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def create_filename(name_segments, part=None, num=None, extension='.jpg'): """Returns a Path object comprising a filename built up from a list of name segments. Parameters: name_segments (list): file name segments part (str): optional LOC image designator (e.g., i...
bigcode/self-oss-instruct-sc2-concepts
import logging def get_logger(name: str) -> logging.Logger: """ Create new logger. :param name: The logger domain. :return: New logger. """ return logging.getLogger(name)
bigcode/self-oss-instruct-sc2-concepts
def lag_to_suffix(lag: int) -> str: """ Return the suffix for a column, given its lag. """ if lag < 0: str_lag = "f" + str(abs(lag)) else: str_lag = "l" + str(abs(lag)) return str_lag
bigcode/self-oss-instruct-sc2-concepts
import math def nPVI(items): """Calculate the Normalized Pairwise Variability Index. :param items: (list) list of data values :returns: (float) """ if len(items) < 2: return 0. n = len(items) - 1 sumd = 0. for i in range(n): d1 = items[i] d2 = items[i+1] ...
bigcode/self-oss-instruct-sc2-concepts
def bdev_virtio_scsi_get_devices(client): """Get list of virtio scsi devices.""" return client.call('bdev_virtio_scsi_get_devices')
bigcode/self-oss-instruct-sc2-concepts