seed
stringlengths
1
14k
source
stringclasses
2 values
def create_cast_date_column_query(dbms: str, date_format: str, date_column: str) -> str: """ Create query that cast date column into yyyy-MM-dd format :param dbms: data warehouse name :param date_format: format of date column :param date_column: name of the column with periods :return: query to...
bigcode/self-oss-instruct-sc2-concepts
def build_geometry(self, sym=1, alpha=0, delta=0): """Build the geometry of the machine Parameters ---------- self : Machine Machine object sym : int Symmetry factor (1= full machine, 2= half of the machine...) alpha : float Angle for rotation [rad] delta : complex ...
bigcode/self-oss-instruct-sc2-concepts
def get_gear_ratio(g: int, gear_ratios: dict): """get gear ratio Args: g (int): gear gear_ratios (dict): mapping of gear to gear ratio Returns: [float]: gear ratio """ return gear_ratios[g]['ratio']
bigcode/self-oss-instruct-sc2-concepts
def fill_leaf_values(tree): """ Recursive function that populates empty dict leaf nodes. This function will look for all the leaf nodes in a dictionary and replace them with a value that looks like the variable in the template - e.g. {{ foo }}. >>> fill_leaf_values({'a': {}, 'b': 'c': {}})...
bigcode/self-oss-instruct-sc2-concepts
import json import collections def load_json_file(filename, use_ordered_dict=True): """ Load a dictionary from a file Parameters ---------- * filename: string \tThe path to the saved json file. * use_ordered_dict: bool \tIf set to True dicts are read as OrderedDicts. """ tmp = Non...
bigcode/self-oss-instruct-sc2-concepts
def _all_none(*args): """Returns a boolean indicating if all arguments are None""" for arg in args: if arg is not None: return False return True
bigcode/self-oss-instruct-sc2-concepts
def pad(block, block_length): """ Pads a block with padding bytes to make it to the required length, in this case, 128 bits. PKCS5 padding Parameters ---------- block : string Block to be padded written in hexadecimal as string. block_length : int Block length in ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def instantiate_datetime_object(datetime_stamps): """Takes a datestamp as a string and instatiates it into an object. >>> datetime_stamps = [u'2016-09-10T15:35-07:00', u'2016-09-10T16:48-07:00'] >>> instantiate_datetime_object(datetime_stamps) [datetime.datetime(2016, 9,...
bigcode/self-oss-instruct-sc2-concepts
def hr_sub(match): """Matches a horizontal rule.""" return '\n\n<hr/>\n\n'
bigcode/self-oss-instruct-sc2-concepts
def parse_line(line): """0 <-> 454, 528, 621, 1023, 1199""" line = line.split(" ") return {"id": int(line[0]), 'connected': list(map(lambda num: int(num.replace(",", "")), line[2:]))}
bigcode/self-oss-instruct-sc2-concepts
import math def get_objectives(data): """Get a list of all first chromosomes' objective values.""" objectives = [math.log(population[0]["objective"]) for population in data] # objectives = [population[0]["objective"] for population in data] return objectives
bigcode/self-oss-instruct-sc2-concepts
def get_raw_instances(self): """ Documentation: --- Description: Associate each EC2 instance ID with its EC2 instance object. --- Returns: raw_instances : dict Dictonary where the keys are EC2 instance IDs and the values ar...
bigcode/self-oss-instruct-sc2-concepts
import re def camel_to_snake_case(camel_cased_string): """Convert the format of the given string from CamelCase to snake_case. Args: camel_cased_string: the string in CamelCase format. Returns: the same string, but in snake_case format. """ return re.sub(r"(?<!^)(?=[A-Z])", "_", cam...
bigcode/self-oss-instruct-sc2-concepts
import types def is_function(obj): """Check if obj is function(lambda function or user defined method) or not""" return isinstance(obj, (types.FunctionType, types.MethodType, types.LambdaType))
bigcode/self-oss-instruct-sc2-concepts
def _LoadWords(dict_file): """Returns a set of all the words in the dict file.""" words = set(word.strip().upper() for word in open(dict_file)) # Remove all single letter words except A, I. for c in 'BCDEFGHJKLMNOPQRSTUVWXYZ': words.remove(c) return words
bigcode/self-oss-instruct-sc2-concepts
def process(data, template_name_key, split_char=";", **kwargs): """ Function to split templates. e.g. if ``template_name_key`` value contains several templates, this processor will split them using ``split_char`` and produce data item for each template coping data accordingly. :param data:...
bigcode/self-oss-instruct-sc2-concepts
def get_required_attribute(el, key): """ Get attribute key of element *el*. :raises: :exc:`ValueError` if key not found """ val = el.get(key) if val == None: raise ValueError('required attribute missing: ' + key) return val
bigcode/self-oss-instruct-sc2-concepts
def calc_histograms(img_to_show): """Calculate histograms Get R, G, B histogram values from an image. Args: img_array (image obj): image object to use Returns: r (list): list of histogram values for red pixels g (list): list of histogram values for green pixels b (list)...
bigcode/self-oss-instruct-sc2-concepts
def get_frame_index(d): """Get frame index from the whole dictionary E.g., '{'index': 'data/Deploy/KLAC/KLAC0570/KLAC0570_12.jpg', 'prediction': ..., 'label': ...}' ==> (int) 12 """ return int(d['index'].split('_')[-1][:-4])
bigcode/self-oss-instruct-sc2-concepts
def q_normalize(q): """Return a normalized quaternion""" mag = (q[0]*q[0] + q[1]*q[1] + q[2]*q[2] + q[3]*q[3]) if mag != 0: for i in range(4): q[i] /= mag; return q
bigcode/self-oss-instruct-sc2-concepts
def get_dc(si, name): """ Get a datacenter by its name. """ for dc in si.content.rootFolder.childEntity: if dc.name == name: return dc raise Exception('Failed to find datacenter named %s' % name)
bigcode/self-oss-instruct-sc2-concepts
def granularity_to_ms(time_string): """Returns millisecond representation of granularity time string""" magnitude = int("".join([c for c in time_string if c.isdigit()])) unit = "".join([c for c in time_string if c.isalpha()]) unit_in_ms = { "s": 1000, "second": 1000, "m": 60000, ...
bigcode/self-oss-instruct-sc2-concepts
def is_curious_fraction(numerator, denominator): """ Determine if two numbers form a curious fraction. A curious fraction is where removing a number common to the numerator and denominator is equal to the original fraction. :param numerator: The numerator of the fraction as an int. :param den...
bigcode/self-oss-instruct-sc2-concepts
import requests def get_files(master_url, pr_url, headers): """ Returns the contents of the current version of the file and of the modified version of the file in a tuple. Args: master_url (str): URL to the current version of the file pr_url (str): URL to the modified version of the f...
bigcode/self-oss-instruct-sc2-concepts
def contour(ax, x, y, z, labels=True, **kwargs): """ Wrapper around Matplotlib's contour plot. We add a small convenience argument `labels` that allows to simply add clabels with a simple `labels=True`. """ cs = ax.contour(x, y, z, **kwargs) if labels: ax.clabel(cs, inline=1, fontsi...
bigcode/self-oss-instruct-sc2-concepts
def gc_content(seq): """ GC content of a given sequence. """ seq = seq.upper() return (seq.count('G') + seq.count('C'))/len(seq)
bigcode/self-oss-instruct-sc2-concepts
def get_int(row, key, ignore_start=0, ignore_end=None): """ row is the csv row to get an integer from, key is that row's column that we want to cast as int, start/end is the number of leading/trailing characters to ignore. return 0 if could not convert """ try: s = row[key][ignore_star...
bigcode/self-oss-instruct-sc2-concepts
def binary(dataframe, entity_id, feature_id): """ Create binary feature dataframe using provided dataset, entity, and feature. :param dataframe: Input dataframe to create binary features :type dataframe: cudf.DataFrame :param entity_id: Entity ID. Must be a column within `dataframe` :type entit...
bigcode/self-oss-instruct-sc2-concepts
def filterl_index(predicate, List): """ Return the index of elements that satisfy the predicate function. :param predicate: :param List: :return: """ result = [] for idx, e in enumerate(List): if predicate(e): result.append(idx) return result
bigcode/self-oss-instruct-sc2-concepts
def parse_feats(feats): """ Helper function for dealing with the feature values that Stanza returns. They look like "Case=Nom|Gender=Fem|Number=Sing" and we convert it to a dictionary with keys "Case" (e.g. "NOM"), "Gender" (e.g. "FEM"), "Number" (e.g. "SIN"). We capitalize the values and make them 3 charac...
bigcode/self-oss-instruct-sc2-concepts
import random def random_agent(network,agent1): """ Chooses a random agent relative to another agent. Meaning, if one picks 'A' and wants another random agent to make a pair, 'A' will not be chosen. Sets up a connection between two random agents. Parameters ---------- network: Cayley netw...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def fibo(nth: int) -> List[int]: """Fibonacci numbers up to the `nth` term starting with 0 and 1.""" fibos = [0, 1] for _ in range(nth - 2): # - 2 because we already have the first two fibos.append(fibos[-1] + fibos[-2]) return fibos
bigcode/self-oss-instruct-sc2-concepts
def parameterize_cases(argnames, cases): """ This is used for parametrizing pytest test cases. argnames: a comma separated string of arguments that the test expects. cases: a dictionary of test cases. """ argnames_list = [i.strip() for i in argnames.split(',')] argvalues = [tuple(i[k] for k...
bigcode/self-oss-instruct-sc2-concepts
def add_newlines_by_spaces(string, line_length): """Return a version of the passed string where spaces (or hyphens) get replaced with a new line if the accumulated number of characters has exceeded the specified line length""" replacement_indices = set() current_length = 0 for i, char in enumerate(st...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any import inspect def isdata(the_object: Any) -> bool: """Check if an object is of a type that probably means it's data.""" return not ( inspect.ismodule(the_object) or inspect.isclass(the_object) or inspect.isroutine(the_object) or inspect.isframe(the_objec...
bigcode/self-oss-instruct-sc2-concepts
def bool_to_pass_fail(value:bool) -> str: """Converts a boolean True to "Pass" and False to "Fail" Parameters ---------- value : bool A boolean value representing True for Pass and False for Fail Returns ------- str "Pass" or "Fail" """ if value: return "Pa...
bigcode/self-oss-instruct-sc2-concepts
def get_logical_switch(client_session, logical_switch_name): """ :param client_session: An instance of an NsxClient Session :param logical_switch_name: The name of the logical switch searched :return: A tuple, with the first item being the logical switch id as string of the first Scope found with the ...
bigcode/self-oss-instruct-sc2-concepts
import json def load_json(json_file): """ Opens json-file and returns it as dictionary :param json_file: path to json-file :type json-file: string :returns: the content of the json file as dictionary """ with open(json_file) as infile: content = json.load(infile) ret...
bigcode/self-oss-instruct-sc2-concepts
import re def sanitize_for_url(word): """ Sanitizing of a word with a regex search string - everything that is not alphanumeric, a space or a colon is substituted by an empty set Args: word (str): Word to sanitize Returns: str: Sanitized string """ return re.sub('[^a-zA-Z\s:]', '', word)
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def normalize_counts(counts): """Return a normalized Counter object.""" normed = Counter() total = float(sum(list(counts.values()), 0.0)) assert total > 0 # cannot normalize empty Counter for key, ct in list(counts.items()): normed[key] = ct / total return n...
bigcode/self-oss-instruct-sc2-concepts
def set_icon_image(icon): """ Set Icon image or set None """ # Icon message files: https://stackoverflow.com/questions/37783878/ # is-it-possible-to-get-tkinter-messagebox-icon-image-files # ::tk::icons::warning # ::tk::icons::error # ::tk::icons::information # ::tk::icons::question if i...
bigcode/self-oss-instruct-sc2-concepts
def read_seq_from_fasta(fasta): """retrieves the sequence of a fasta file, returns it as string """ with open(fasta, "r") as f: seq = "" for line in f: if line: if not line.startswith(">"): # ignore header seq += line.strip() return seq.up...
bigcode/self-oss-instruct-sc2-concepts
def bump_build_number(d): """ Increase the build number of a recipe, adding the relevant keys if needed. d : dict-like Parsed meta.yaml, from get_meta() """ if 'build' not in d: d['build'] = {'number': 0} elif 'number' not in d['build']: d['build']['number'] = 0 d['b...
bigcode/self-oss-instruct-sc2-concepts
def reduce_score_to_chords(score): """ Reforms score into a chord-duration list: [[chord_notes], duration_of_chord] and returns it """ new_score = [] new_chord = [[], 0] # [ [chord notes], duration of chord ] for event in score: new_chord[0].append(event[1]) # Append new note...
bigcode/self-oss-instruct-sc2-concepts
def _get_prepped_model_field(model_obj, field): """ Gets the value of a field of a model obj that is prepared for the db. """ try: return model_obj._meta.get_field(field).get_prep_value(getattr(model_obj, field)) except: return getattr(model_obj, field)
bigcode/self-oss-instruct-sc2-concepts
import re def substitute(string, substitutions): """ Take each key in the substitutions dict. See if this key exists between double curly braces in string. If so replace with value. Example: substitute("my name is {{name}}.",{version:1,name=John}) > "my name is John" """ for key, valu...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from typing import List def get_candidate_paths(parent: Path, name: str) -> List[Path]: """ Combines all of the candidate paths for each file for simplicity. The previous method of defining candidates individually was getting complicated. """ candidates = [ # The usual locations for t...
bigcode/self-oss-instruct-sc2-concepts
import functools def remove_all(string, substrs): """Removes a whole list of substrings from a string, returning the cleaned string. Args: string (str): A string to be filtered substrs (:obj:`list` of :obj:`strs`): The substrings to remove from the string Returns: str: string...
bigcode/self-oss-instruct-sc2-concepts
def make_array_of_dicts_from_response_json(response_json, index): """ Makes array of dicts from stats.nba.com response json :param dict response_json: dict with response from request :param int index: index that holds results in resultSets array :return: list of dicts with data for each row :rt...
bigcode/self-oss-instruct-sc2-concepts
def cyccalc(self, fileprefix="", fileformat="", **kwargs): """Calculates results from a cyclic harmonic mode-superposition analysis APDL Command: CYCCALC using the specifications defined by CYCSPEC. Parameters ---------- fileprefix Each result table (corresponding to each CYCSPEC speci...
bigcode/self-oss-instruct-sc2-concepts
def data_transformer(x, y, xfactor, yfactor, **kwargs): """Multiplies x or y data by their corresponding factor.""" return {"x": x * xfactor, "y": y * yfactor}
bigcode/self-oss-instruct-sc2-concepts
def length_average(length, logprobs, alpha=0.): """ Returns the average probability of tokens in a sequence. """ return logprobs / length
bigcode/self-oss-instruct-sc2-concepts
def is_valid_name(name, parameters, kw): """Checks if name is a valid script variable name. Returns the error.""" if not name.isidentifier(): return "Variable name '{}' is not a valid identifier.".format(name) if name in kw.KEYWORDS: return "Variable name '{}' is a keyword.".format(name) ...
bigcode/self-oss-instruct-sc2-concepts
def equal_string_modulo_digits(s1, s2): """Returns whether two strings without their digits are the same """ s1 = (c for c in s1 if not c.isdigit()) s2 = (c for c in s2 if not c.isdigit()) return all(c1 == c2 for c1, c2 in zip(s1, s2))
bigcode/self-oss-instruct-sc2-concepts
def _has_magic(instream, magic): """Check if a binary stream matches the given signature.""" return instream.peek(len(magic)).startswith(magic)
bigcode/self-oss-instruct-sc2-concepts
def make_dic(doc_id=None, root=None, date=None, author=None, text=None, favorite=None): """make dictionary form argument and return dictionary Keyword Arguments: doc_id {int} -- documnet ID (default: {None}) root {string} -- xml file name (default: {None}) date {string} -- ...
bigcode/self-oss-instruct-sc2-concepts
def get_users(f_path): """ Getting user name and password hash from file """ out = {} with open(f_path) as file: for d in file: h = d.split(':')[1] if h != '*': u = str(d.split(':')[0]).strip() if len(u) > 0: out[u]...
bigcode/self-oss-instruct-sc2-concepts
import six def is_jid(jid): """ Returns True if the passed in value is a job id """ if not isinstance(jid, six.string_types): return False if len(jid) != 20 and (len(jid) <= 21 or jid[20] != "_"): return False try: int(jid[:20]) return True except ValueError...
bigcode/self-oss-instruct-sc2-concepts
def format_legacy_response(response, skills, category): """Format responses appropriately for legacy API. # noqa: E501 Examples: >>> skills = ["Strength", "Hitpoints", "Ranged", "Magic", "Slayer", "Farming"] >>> category = "xp" >>> response = [ ... { ... 'skills': { ... ...
bigcode/self-oss-instruct-sc2-concepts
import re def GetFormatCount(format_): """ Get format prefix count @param format_: format specifier @return: prefix count or 1 if not specified """ if isinstance(format_, str): match = re.search("\s*(\d+)", format_) if match: return int(match.grou...
bigcode/self-oss-instruct-sc2-concepts
def generate_wrapper(name, module, original_docstring, num_threads): """Generate a wrapper function. Parameters ---------- name : string Name of the function wrapped. module : string Name of the module the wrapped function is part of. original_docstring : string Docstrin...
bigcode/self-oss-instruct-sc2-concepts
def domain_level(host): """ >>> domain_level('') 0 >>> domain_level(' ') 0 >>> domain_level('com') 1 >>> domain_level('facebook.com') 2 >>> domain_level('indiana.facebook.com') 3 """ if host.strip() == '': return 0 else: raw_parts = host.strip()...
bigcode/self-oss-instruct-sc2-concepts
def _test_if_all_vals_equal(vals1, vals2): """Checks if the union of two iterables is 1 and returns True if that is the case. Is used in test_num_feats to check if two lists of values have only the same value and nothing else. :param vals1: :param vals2: :return: """ # build union between v...
bigcode/self-oss-instruct-sc2-concepts
import copy def convert_chord_label(ann): """Replace for segment-based annotation in each chord label the string ':min' by 'm' and convert flat chords into sharp chords using enharmonic equivalence Notebook: C5/C5S2_ChordRec_Eval.ipynb Args: ann (list): Segment-based annotation with chord la...
bigcode/self-oss-instruct-sc2-concepts
def copy_file_request(drive_service, file_id, body): """Send copy request to gdrive""" response = drive_service.files().copy( fileId=file_id, body=body, fields='id,webViewLink,name' ).execute() return response
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional async def get_sample_owner(db, sample_id: str) -> Optional[str]: """ A Shortcut function for getting the owner user id of a sample given its ``sample_id``. :param db: the application database client :param sample_id: the id of the sample to get the owner for :retur...
bigcode/self-oss-instruct-sc2-concepts
def format_password(password): """ Formats password for printing to the terminal. This is done so that the password is not returned as plain text. """ return password[0] + "*" * (len(password) - 1)
bigcode/self-oss-instruct-sc2-concepts
def is_equivalent(a, b): """Checks if two strings are equivalent This only does a == b, and will not replace anything. For testing. """ return a == b
bigcode/self-oss-instruct-sc2-concepts
import csv def read_csv(read_path, delim=','): """Reads a generic CSV file. Args: - read_path - string path to read from. - delim - delimiter to use for the CSV format. Returns: - rows - list of rows where each row is a string list of cell values. """ rows = [] with open(read_pat...
bigcode/self-oss-instruct-sc2-concepts
def unzip(items): """The inverse of zip Parameters ---------- items : a nested iteratable Returns ------- list The unzipped items Examples -------- >>> from t2t.util import unzip >>> unzip([[1, 2], ['a', 'b']]) [[1, 'a'], [2, 'b']] """ if items: ...
bigcode/self-oss-instruct-sc2-concepts
def Rayleigh_KD(f, alpha): """ Calculate partitioning of trace element (TE) as a function of Rayleigh fractionation. Parameters ---------- f : array-like Fraction of Ca remaining in the biomineralisation reservoir. alpha : array-like Partition coefficient for extraction of TE fr...
bigcode/self-oss-instruct-sc2-concepts
def find_smallest_int(arr): """ Given an array of integers find the smallest number. :param arr: an array of integers. :return: the smallest number within the array. """ return min(arr)
bigcode/self-oss-instruct-sc2-concepts
import colorsys import random def generate_colors(class_names): """Generates different colours for all classes. Args: class_names (list of `str`): List containing names of all classes. Returns: list: List containing colours for corresponding classes. """ hsv_tuples = ...
bigcode/self-oss-instruct-sc2-concepts
def _is_national_number_suffix_of_other(numobj1, numobj2): """Returns true when one national number is the suffix of the other or both are the same. """ nn1 = str(numobj1.national_number) nn2 = str(numobj2.national_number) # Note that endswith returns True if the numbers are equal. return nn...
bigcode/self-oss-instruct-sc2-concepts
def format_time_filter(start, stop, field): """Formats a time filter for a given endpoint type. Args: start (str): An ISO date string, e.g. 2020-04-20. stop (str): An ISO date string, e.g. 2021-04-20. field (str): The time field to filter by. """ start_date = start.split('-') ...
bigcode/self-oss-instruct-sc2-concepts
def get_hypothesis(x, theta): """ :param x : scalar of a given sample :param theta : 1D array of the trainable parameters """ hypothesis = 0.0 for t in range(len(theta)): # compute prediction by raising x to each power t hypothesis += theta[t] * (x ** t) ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import json def load_ambient_sensor(session_path): """ Load Ambient Sensor data from session. Probably could be extracted to DatasetTypes: _ibl_trials.temperature_C, _ibl_trials.airPressure_mb, _ibl_trials.relativeHumidity Returns a list of dicts one dict per trial. ...
bigcode/self-oss-instruct-sc2-concepts
def isSliceUnitSUV(dcmSlice): """Take a dcm slice in input and returns true if the voxels are expressed in SUV - Standardized uptake value. Return false otherwise.""" # 00541001 corresponds to the tag index of the voxel unit in the dcm file units = dcmSlice[0x00541001].value.lower() unitIsSUV = "su...
bigcode/self-oss-instruct-sc2-concepts
def get_primes(length: int = 26, min_prime: int = 2, max_prime: int = 101) -> list: """Get list of primes. Given a length, minimum, and maximum prime number, return a list of prime numbers. Args: length (int): Number of prime numbers to return. Defaults to ``26``. min_pr...
bigcode/self-oss-instruct-sc2-concepts
def autocomplete_configuration_path(actions, objects): """ Returns current configuration_path for object. Used as a callback for `default_value`. Args: actions: Transition action list objects: Django models objects Returns: configuration_path id """ configuration_pa...
bigcode/self-oss-instruct-sc2-concepts
import string def is_segment(pattern): """Test if pattern begins with a segment variable.""" return (type(pattern) is list and pattern and len(pattern[0]) > 2 and pattern[0][0] == '?' and pattern[0][1] == '*' and pattern[0][2] in string.ascii_letters...
bigcode/self-oss-instruct-sc2-concepts
def convert_word_index_to_sentence(word_idx, vocab): """Convert word indices to sentence.""" s = "" for ind in range(len(word_idx)): w_idx = word_idx[ind] if w_idx> 0: s += vocab[w_idx-1] if ind < len(word_idx)-1: s+= " " return s
bigcode/self-oss-instruct-sc2-concepts
def thickest_clouds(cloud_thickness_and_base_list): """ Given a list of tuples indicated cloud thickness and base, return the tuple with the thickest clouds """ return max(cloud_thickness_and_base_list, key=lambda c: c[0])
bigcode/self-oss-instruct-sc2-concepts
def validate_run(cards): """ a run is 3 to 10 consecutive cards of the same suit :param cards: list of Card objects :return: Boolean """ if len(cards) < 3 or len(cards) > 10: return False if not all(card.suit == cards[0].suit for card in cards): return False ranks = sort...
bigcode/self-oss-instruct-sc2-concepts
def get_plural_string(word: str, amount: int) -> str: """Returns singular or plural of the word depending on the amount. Example: word = 'piece', amount = 0 -> '0 pieces' word = 'piece', amount = 1 -> '1 piece' word = 'piece', amount = 5 -> '5 pieces'""" if amount == 1: return f'1 {word}' else: return f'{...
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce from typing import Mapping def deep_get(dictionary: dict, *keys, default=None): """Safely return the value of an arbitrarily nested map Inspired by https://bit.ly/3a0hq9E """ return reduce( lambda d, key: d.get(key, default) if isinstance(d, Mapping) else default, keys, dictionary ...
bigcode/self-oss-instruct-sc2-concepts
def get_description(repo_info): """Return repository description""" try: return repo_info.find('p').text.strip() except AttributeError: return
bigcode/self-oss-instruct-sc2-concepts
def _exact_compare(tree1, tree2): """Simultaneously compares the name, length, and support of each node from two trees. Parameters ---------- tree1: skbio.TreeNode first tree to compare tree2: skbio.TreeNode second tree to compare Returns ------- bool `True`...
bigcode/self-oss-instruct-sc2-concepts
def readthrough_in_bedpe(record, annotation, rt_threshold): """ Determine if the two genes in the record are within `rt_threshold` bp of each other on the same chromosome. :param BEDPE record: A BEDPE line from the input file :param dict(str, GTFRecord) annotation: see `read_fusions:gene_annotation...
bigcode/self-oss-instruct-sc2-concepts
import random def choose(char): """ Randomly choose upper or lower case to return """ return char.upper() if random.choice([0, 1]) else char.lower()
bigcode/self-oss-instruct-sc2-concepts
def A008588(i: int) -> int: """Nonnegative multiples of 6.""" return i * 6
bigcode/self-oss-instruct-sc2-concepts
def int_(num: str) -> int: """ Take an integer in the form of a string, remove any commas from it, then return it as an ``int``. Args: num: A string containing only numeric characters or commas. Returns: An integer version of the string. """ return int(num.replace(",", ""))
bigcode/self-oss-instruct-sc2-concepts
def median(lst): """ Return a list's median :param lst: List (sorted or not) of int :return: int """ lst.sort() length = len(lst) if length == 0: return None elif length % 2 == 0: # Even number of elements return (lst[int((length+1)/2 - 1)] + lst[i...
bigcode/self-oss-instruct-sc2-concepts
import json def is_json_serializable(item): """ Test if an object is serializable into JSON :param item: (object) The object to be tested for JSON serialization. :return: (bool) True if object is JSON serializable, false otherwise. """ # Try with try-except struct. json_serializable = Tru...
bigcode/self-oss-instruct-sc2-concepts
import math def getLOG(rawEMGSignal): """ LOG is a feature that provides an estimate of the muscle contraction force.:: LOG = e^((1/N) * sum(|xi|)) for x i = 1 --> N * Input: * raw EMG Signal * Output = * LOG :param rawEMGSignal: the raw EMG signal :type ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def parse_element_time(element): """Extract and format time from an html element.""" unixtime = int(element.find(class_="odate")["class"][1].split("_")[1]) return datetime.utcfromtimestamp(unixtime).strftime("%Y-%m-%d %H:%M:%S")
bigcode/self-oss-instruct-sc2-concepts
import math def calculateTierSize(imageWidth, imageHeight, tileSize=256): """ The function calculate the number of tiles per tier Arguments: imageWidth {Float} imageHeight {Float} tileSize {Integer} Default is 256 pixel Return: {Array} """ tierSizeInTiles = [] ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def last_leap_year(date=None): """ Return the last complete leap year from today or a specified date. """ if date is None: date = datetime.utcnow() leap = (date.year - 1) - ((date.year - 1) % 4) return leap
bigcode/self-oss-instruct-sc2-concepts
def to_uri(uri_data): """ Convenient function to encase the resource filename or data in url('') keyword Args: uri_data (str): filename or base64 data of the resource file Returns: str: the input string encased in url('') ie. url('/res:image.png') """ return ("url('...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def password_hash(password: str) -> bytes: """Create a hash of a password to transform it to a fixed-length digest. Note this is not meant for secure storage, but for securely comparing passwords. """ return hashlib.sha256(password.encode()).digest()
bigcode/self-oss-instruct-sc2-concepts