seed
stringlengths
1
14k
source
stringclasses
2 values
def update_parameters(parameters, grads, learning_rate): """ Update the parameters' values using gradient descent rule. Arguments --------- parameters : dict contains all the weight matrices and bias vectors for all layers. grads : dict stores all gradients (output of L_model_ba...
bigcode/self-oss-instruct-sc2-concepts
def _mk_range_bucket(name, n1, n2, r1, r2): """ Create a named range specification for encoding. :param name: The name of the range as it should appear in the result :param n1: The name of the lower bound of the range specifier :param n2: The name of the upper bound of the range specified :para...
bigcode/self-oss-instruct-sc2-concepts
def ispandigital(m, n): """return True iff m is pandigital in base n""" s = set() while m > 0: m, b = divmod(m, n) if b in s: return False s.add(b) return True
bigcode/self-oss-instruct-sc2-concepts
from typing import List def num_trainable_params(hidden_nodes: List[int], n_inputs: int, n_outputs: int): """Calculate the number of weights in a neural network Illustration: https://stats.stackexchange.com/questions/296981/formula-for-number-of-weights-in-neural-network Arg...
bigcode/self-oss-instruct-sc2-concepts
def precision_recall_f1_support(true_positives, false_positives, false_negatives): """Returns the precision, recall, F1 and support from TP, FP and FN counts. Returns a four-tuple containing the precision, recall, F1-score and support For the given true_positive (TP), false_positive (FP) and false_nega...
bigcode/self-oss-instruct-sc2-concepts
import torch def bbox_generator3d( x_start: torch.Tensor, y_start: torch.Tensor, z_start: torch.Tensor, width: torch.Tensor, height: torch.Tensor, depth: torch.Tensor, ) -> torch.Tensor: """Generate 3D bounding boxes according to the provided start coords, width, height and depth. Arg...
bigcode/self-oss-instruct-sc2-concepts
def find_freq(wvec, freq_val): """ Helper function returns the nearest index to the frequency point (freq_val) """ return min(range(len(wvec)), key=lambda i: abs(wvec[i]-freq_val))
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def str_to_date_obj(date_str, frmt='%a %d %b %Y %H:%M:%S +0000'): """ Utility function to return str date to date object. """ return datetime.strptime(date_str, frmt).date()
bigcode/self-oss-instruct-sc2-concepts
import re def parse_grant(grant): """Parse for grant number from grant annotation.""" if len(grant): grant = re.sub(r'RO', 'R0', grant) grant_info = re.search(r"([A-Z][A-Z](\s|-)*\d{3,})[ /-]", grant, re.I) if grant_info is not None: grant_number = grant_info.group(1).upper...
bigcode/self-oss-instruct-sc2-concepts
import base64 def b64_to_bytes(val: str, urlsafe=False) -> bytes: """ Convert a base 64 string to bytes """ if urlsafe: return base64.urlsafe_b64decode(val) return base64.b64decode(val)
bigcode/self-oss-instruct-sc2-concepts
def repeat_interleave(input, repeats, dim=0): """ Repeat and interleave a tensor along a given dimension. The current PyTorch implementation of `repeat_interleave` is slow and there is an open ticket for it: https://github.com/pytorch/pytorch/issues/31980 Args: input (torch.Tensor): Tensor c...
bigcode/self-oss-instruct-sc2-concepts
def get_filepaths(casedir, prefix='stdout_run', suffix='.txt', niter=5): """Get the file paths with data to read. Parameters ---------- casedir : pathlib.Path object Directory that contains the files to read. prefix : string (optional) Common prefix of the file names; default: 'stdo...
bigcode/self-oss-instruct-sc2-concepts
def temporal_decimation(data, mb=1): """ Decimate data by mb new frame is mean of decimated frames Parameters: ---------- data: np.array (T x d) array to be decimated wrt first axis mb: int contant by which to decimate d...
bigcode/self-oss-instruct-sc2-concepts
def readattr(_obj, _name, _default=None, _error_on_none=None): """ Reads an attribute value from an object :param _obj: The object :param _name: The name of the attribute :param _default: If set, the value to return if the attribute is missing or the value is None :param _error_on_none: If set, ...
bigcode/self-oss-instruct-sc2-concepts
def returncode_msg(retcode: int) -> str: """interpret retcode""" if retcode < 0: sig = -1 * retcode return f'terminated by signal {sig}' if retcode <= 125: return 'error during processing' if retcode == 126: # shouldn't happen return '' if retcode == 127: ret...
bigcode/self-oss-instruct-sc2-concepts
def row_format_resource(*fields): """Transform a variable number of fields to a `table-row` format. ``` >>> row_format_resource(a,b,c,d) '| a | b | c | d |' ``` :param fields: fields to be converted to row. """ return ('| {} ' * len(fields)).format(*fields...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def url_create_payloads(url_information: dict) -> List[dict]: """ Returns a list of payloads. Args: url_information (dict): The data retrieved from URLHaus db. Returns: payloads (list): list of payloads associated with the URL. """ ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union import logging def configure_logging( logging_level: Union[int, str] = logging.INFO, logging_fmt: str = "%(levelname)s: %(name)s: %(funcName)s: %(message)s", logger_obj: Union[None, logging.Logger] = None, ) -> logging.Logger: """ Setup logging on the root logg...
bigcode/self-oss-instruct-sc2-concepts
def roi_shape(roi): """ Shape of an array after cropping with ``roi``. Same as ``xx[roi].shape``. """ def slice_dim(s): return s.stop if s.start is None else s.stop - s.start if isinstance(roi, slice): roi = (roi,) return tuple(slice_dim(s) for s in roi)
bigcode/self-oss-instruct-sc2-concepts
import re def extract_placeholders(template): """Extract the template's placeholder names.""" return re.findall(r'{(.*?)}', template)
bigcode/self-oss-instruct-sc2-concepts
from typing import List def get_cache_types() -> List[str]: """ Return the types (aka levels) of the cache. """ return ["mem", "disk"]
bigcode/self-oss-instruct-sc2-concepts
import random def propose_random_nni(tree): """ Propose a random NNI rearrangement """ nodes = tree.nodes.values() # find edges for NNI while True: node1 = random.sample(nodes, 1)[0] if not node1.is_leaf() and node1.parent is not None: break node2 = node1.par...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def return_true(*_: Any) -> bool: """A dummy function that always returns true.""" return True
bigcode/self-oss-instruct-sc2-concepts
def take_bet(player: dict) -> float: """Prompt the player for how much money to bet.""" while True: print(f"\nYou currently have ${player['money']:.2f}") bet = input('How much money would you like to bet on this hand? (min: $20)\n> $') if not bet.isdigit() or float(bet) < 20: ...
bigcode/self-oss-instruct-sc2-concepts
def subOneThenMult(value, arg): """Subtracts one from arg then multiplies by value""" return (value) * (arg - 1)
bigcode/self-oss-instruct-sc2-concepts
import torch from typing import Optional def _weighted_mean( tensor: torch.Tensor, weight: Optional[torch.Tensor], ) -> torch.Tensor: """ Compute weighted mean. :param tensor: The tensor. :param weight: An optional weight. :return: The (weighted) mean. If weight i...
bigcode/self-oss-instruct-sc2-concepts
def conv_out_shape(in_shape, out_fms, p, k, s): """ Gets the output shape [height, width] for a 2D convolution. (Assumes square kernel). @param in_shape: The input shape [batch, height, width, channels]. @param out_fms: The number of feature maps in the output. @param p: The padding type (eithe...
bigcode/self-oss-instruct-sc2-concepts
def computeMissScore(cycles, lower, upper, full_score): """Computes the score depending on the number of cache misses.""" if cycles <= lower: return full_score if cycles >= upper: return 0 score = (cycles - lower) * 1.0 range = (upper - lower) * 1.0 return round((1 - score / ra...
bigcode/self-oss-instruct-sc2-concepts
import math def rotateSlope(m, theta): """ Rotates the given slope for a certain angle. """ return (math.sin(theta) + m * math.cos(theta)) / (math.cos(theta) - m * math.sin(theta))
bigcode/self-oss-instruct-sc2-concepts
import math def _ra_dec_conversion(ra, dec): """Given ra and dec in degrees, convert to (rahr, ramin, rasec, decsign, decdeg, decmin, decsec) where decsign is a string, either '+' or '-'""" # get ra, dec in hms, dms rahr = math.floor(ra / 15.0) if not rahr: ra_remainder = ra else: ...
bigcode/self-oss-instruct-sc2-concepts
def get_subtask(cmd_action, file_dep=None): """Return a dictionary defining a substack for string 'cmd_action'.""" if cmd_action.startswith("poetry run "): name = cmd_action.split(" ")[2] else: name = cmd_action.split(" ")[0] task = {"name": name, "actions": [cmd_action], "task_dep": ["i...
bigcode/self-oss-instruct-sc2-concepts
import json def json_unstringify(json_to_objify, default=None): """Convert a json string to a python object. Args: json_to_objify (str): The json string. default (object): The default value if no json string is passed in. Returns: object: The un-stringified object. """ tr...
bigcode/self-oss-instruct-sc2-concepts
def get_repadding(crops, d_shape): """ Returns ------- tuple padding values to restore 3D np array after it was cropped. Parameters ---------- crops : list 3 tuples in a list [(nz1,nz2), (ny1,ny2), (nx1,nx2)] d_shape : tuple or...
bigcode/self-oss-instruct-sc2-concepts
def shorten_duplicate_content_url(url): """Remove anchor part and trailing index.html from URL.""" if '#' in url: url = url.split('#', 1)[0] if url.endswith('index.html'): return url[:-10] if url.endswith('index.htm'): return url[:-9] return url
bigcode/self-oss-instruct-sc2-concepts
import random def generate(model, n, seed, max_iterations): """Generates a list of tokens from information in model, using n as the length of n-grams in the model. Starts the generation with the n-gram given as seed. If more than max_iteration iterations are reached, the process is stopped. (This is to prevent...
bigcode/self-oss-instruct-sc2-concepts
def get_edge_label(layer): """Define edge label based on layer type. """ if layer.type == 'Data': edge_label = 'Batch ' + str(layer.data_param.batch_size) elif layer.type == 'Convolution' or layer.type == 'Deconvolution': edge_label = str(layer.convolution_param.num_output) elif lay...
bigcode/self-oss-instruct-sc2-concepts
def convert_hhmmss(hhmmss): """Convert hh:mm:ss to seconds.""" fields = hhmmss.split(":") if len(fields) != 3: raise ValueError("Received invalid HH:MM:SS data: {}".format(hhmmss)) fields = [int(x) for x in fields] hours, minutes, seconds = fields return (hours * 3600) + (minutes * 60) +...
bigcode/self-oss-instruct-sc2-concepts
def _get_trids(db, id_val, id_type): """Return text ref IDs corresponding to any ID type and value.""" # Get the text ref id(s) if id_type in ['trid']: trid_list = [int(id_val)] else: id_types = ['pmid', 'pmcid', 'doi', 'pii', 'url', 'manuscript_id'] if id_type not in id_types: ...
bigcode/self-oss-instruct-sc2-concepts
def groupby(function, sequence): """ Example: >>> from m2py import functional as f >>> f.groupby(len, ['Alice', 'Bob', 'Charlie', 'Dan', 'Edith', 'Frank']) {3: ['Bob', 'Dan'], 5: ['Alice', 'Edith', 'Frank'], 7: ['Charlie']} >>> >>> >>> f.groupby(f.is_even, [1, 2, 3, 4, 5, 6, 7]) {F...
bigcode/self-oss-instruct-sc2-concepts
def is_leaf(dmrs, nodeid): """ Check if a node has no outgoing links """ return not any(dmrs.get_out(nodeid, itr=True))
bigcode/self-oss-instruct-sc2-concepts
def comparator_eval(comparator_params): """Gets BUFF score for interaction between two AMPAL objects """ top1, top2, params1, params2, seq1, seq2, movements = comparator_params xrot, yrot, zrot, xtrans, ytrans, ztrans = movements obj1 = top1(*params1) obj2 = top2(*params2) obj2.rotate(xrot, ...
bigcode/self-oss-instruct-sc2-concepts
import re def count_sentences(string: str) -> int: """ Counts quantity of sentences in given text. """ sentence_endings = re.compile("[.!?]+") return len(sentence_endings.findall(string))
bigcode/self-oss-instruct-sc2-concepts
def normalize_ssc(name): """ Convert a name in SCREAMING_SNAKE_CASE to regular notation, e.g. "Screaming snake case". Args: name: Name to convert. Returns: str: Converted name. """ if not name: return return " ".join(part for part in name.split("_")).capitalize...
bigcode/self-oss-instruct-sc2-concepts
def trim_for_encoding(wav_data, sample_length, hop_length=512): """Make sure audio is a even multiple of hop_size. Args: wav_data: 1-D or 2-D array of floats. sample_length: Max length of audio data. hop_length: Pooling size of WaveNet autoencoder. Returns: wav_data: Trimmed array. sample_le...
bigcode/self-oss-instruct-sc2-concepts
import re def alpha_only(s): """ Strip any non-alpha characters from s, and convert to lowercase """ return re.sub(r'[^A-Za-z]+', '', s.lower())
bigcode/self-oss-instruct-sc2-concepts
def swift_library_output_map(name, module_link_name): """Returns the dictionary of implicit outputs for a `swift_library`. This function is used to specify the `outputs` of the `swift_library` rule; as such, its arguments must be named exactly the same as the attributes to which they refer. Args: name: ...
bigcode/self-oss-instruct-sc2-concepts
def gen_custom_item_windows_group(description, info, value_type, members, group_name): """ Generates a custom item stanza for a windows group membership audit Args: description: string, a description of the audit info: string, info about the audit value_type: string, "POLICY_TEXT" -- inclu...
bigcode/self-oss-instruct-sc2-concepts
def convert_string_to_list_float(string): """ Convert the string of a list to the actual floating point list. """ return [float(l) for l in string[1:-1].split(", ")]
bigcode/self-oss-instruct-sc2-concepts
def find_aircraft_id(key, config): """ find_aircraft_id The aircraft identifier can be given either as a dictionary key in the yaml file or under the fields 'identifier' or 'id' in the aircraft configuration item. This function test in the parsed yaml to find the aircraft id. """ if 'ident...
bigcode/self-oss-instruct-sc2-concepts
def call_reply(msg, call_return): """Construct message used by CtrlServer when replying to API calls. :param msg: Description of API call. :type msg: string :param call_return: Return value of API call. :type call_return: string :returns: Constructed call_reply dict, ready to be sent over the w...
bigcode/self-oss-instruct-sc2-concepts
import torch def flatten(params): """ Turns a module's parameters (or gradients) into a flat numpy array params: the module's parameters (or gradients) """ with torch.no_grad(): return torch.cat([p.data.view(-1) for p in params])
bigcode/self-oss-instruct-sc2-concepts
def pk_same_public_key(key1, key2): """Return true iff key1 and key2 are the same key.""" return key1.encode_key(1) == key2.encode_key(1)
bigcode/self-oss-instruct-sc2-concepts
def safe_mathis_label(tput_true, tput_mathis): """ Returns the Mathis model label based on the true throughput and Mathis model fair throughput. If either component value is -1 (unknown), then the resulting label is -1 (unknown). """ return ( -1 if tput_true == -1 or tput_mathis == -1 el...
bigcode/self-oss-instruct-sc2-concepts
def setup_with_context_manager(testcase, cm): """Use a contextmanager to setUp a test case.""" val = cm.__enter__() testcase.addCleanup(cm.__exit__, None, None, None) return val
bigcode/self-oss-instruct-sc2-concepts
def get_item(iterable_or_dict, index, default=None): """Return iterable[index] or default if IndexError is raised.""" try: return iterable_or_dict[index] except (IndexError, KeyError): return default
bigcode/self-oss-instruct-sc2-concepts
def getDimensions(name): """Gets the rows and columns of a matrix from a text file Args: name (string): filename for matrix Returns: tuple: a tuple of the rows and columns """ file = open(name, 'r') size = file.readline().split() #split at a tab rows = size[0] cols = s...
bigcode/self-oss-instruct-sc2-concepts
def plain_text_to_html(string): """Convert plain text to HTML markup.""" string = string.replace("&", "&amp;") return string
bigcode/self-oss-instruct-sc2-concepts
def slice_doubles(doubles): """Get the heads and relations from a matrix of doubles.""" return ( doubles[:, 0:1], # heads doubles[:, 1:2], # relations )
bigcode/self-oss-instruct-sc2-concepts
import torch from typing import Dict def update_lr(lr_scheduler: torch.optim.lr_scheduler._LRScheduler) -> Dict[str, float]: """ Update lr scheduler and returns the current learning rate as a summary - Parameters: - lr_scheduler: A `torch.optim.lr_scheduler._LRScheduler` to update - Returns: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List import torch def _pad(tokenized: List[torch.Tensor], value: int) -> torch.Tensor: """Utility function that pads batches to the same length.""" batch_size = len(tokenized) max_len = max(len(t) for t in tokenized) output = torch.zeros((batch_size, max_len), dtype=tokenized[0].dty...
bigcode/self-oss-instruct-sc2-concepts
def compose_submit_url(contest: str, contest_no: int) -> str: """ 与えられたコンテスト名、コンテスト番号から 提出先のURLを生成する Parameters ---------- contest : str コンテスト名. ABC, ARC or AGC contest_no : int コンテスト番号 Returns ---------- url : str 対応する提出先のURL """ host = 'https:/...
bigcode/self-oss-instruct-sc2-concepts
def cap_at_n(lines, n=2000): """ Takes in a list of strings and joins them with `\n`, but no more than n characters. The Discord message character limit is 2000. """ text = "" for line in lines: if len(text) + len(line) + 1 < n - 3: text += line + "\n" else: text += "..."...
bigcode/self-oss-instruct-sc2-concepts
import random def improved_evaluation_function(game_state, agent, **context): """ This simple evaluation functions improves the basic one by adding some randomness when choosing among non final states. In some cases this evaluation function behaves better than the basic one since it can block oppo...
bigcode/self-oss-instruct-sc2-concepts
def str_to_bool(value): """ Convert a human readable string into a boolean. """ valuestr = str(value).lower() if valuestr in ['1', 'yes', 'enable', 'true']: return True elif valuestr in ['0', 'no', 'disable', 'false']: return False else: raise Exception("Unable to con...
bigcode/self-oss-instruct-sc2-concepts
import uuid def generate_uuid(class_name: str, identifier: str, test: str = 'teststrong') -> str: """ Generate a uuid based on an identifier :param identifier: characters used to generate the uuid :type identifier: str, required :param class_name: classname of the object to create a...
bigcode/self-oss-instruct-sc2-concepts
from typing import Type def isnestedclass(cls: Type, scope: Type) -> bool: """Returns true, if the given class ``cls`` is a member on an outer class ``scope``.""" for mroClass in scope.mro(): for memberName in mroClass.__dict__: member = getattr(mroClass, memberName) if isinstance(member, Type): if cls ...
bigcode/self-oss-instruct-sc2-concepts
def midPoint(pointA,pointB): """ Input : two points A,B. Output : Midpoint of these two points """ X = int(pointA.x+pointB.x)/2 Y = int(pointA.y+pointB.y)/2 return (X,Y)
bigcode/self-oss-instruct-sc2-concepts
def _throw_exception(exception: Exception): """Returns a function pointer for a function throwing an arbitrary exception""" def _throw(*args, **kwargs): raise exception return _throw
bigcode/self-oss-instruct-sc2-concepts
def summation(lower, upper): """returns the sum of the numbers from lower through upper""" #!base case if lower > upper: return 0 #!recursive case return lower + summation(lower + 1, upper)
bigcode/self-oss-instruct-sc2-concepts
def get_recommended_modification(simple_order, impact): """ Generate a recommendation string from an operator and the type of impact :param simple_order: simplified operator :param impact: whether the change has positive or negative impact :return: formatted recommendation string """ bigger_...
bigcode/self-oss-instruct-sc2-concepts
def grb_rate_wp(z, z_inhom=0.): """Returns the rate of Gamma-Ray Burst, per comoving volume, evaluated at the specified redshift. Ref: Wanderman, Piran: Mon.Not.Roy.Astron.Soc.406:1944-1958,2010 Args: z (float): redshift z_inhom (float): redshift where the universe becomes inhomogenous...
bigcode/self-oss-instruct-sc2-concepts
import hmac def calculate_message_signature(key: str, msg: str): """ calculate a message signature using a SHA1 HMAC :param key: the secret token :param msg: the message :return: the calculated HMAC """ return hmac.new(key.encode(), msg=msg.encode(), digestmod='sha1').hexdigest()
bigcode/self-oss-instruct-sc2-concepts
from typing import List def calculate_pages(page_range_string) -> List[int]: """ Calculate a list of pages from the ranges given as CLI parameter page-range. :param page_range_string: CLI parameter page-range :return: list of pages in given range """ page_ranges = page_range_string.split(',')...
bigcode/self-oss-instruct-sc2-concepts
def stringXor(a, b): """ Calculates the bitwise xor for every value of the arrays. The arrays need to be equally long :param a: The first array :param b: The second array :return: The calculated result """ if len(a) != len(b): raise Exception("stringXor: the two arrays must have...
bigcode/self-oss-instruct-sc2-concepts
def strip_trailing_nl(s): """If s ends with a newline, drop it; else return s intact""" return s[:-1] if s.endswith('\n') else s
bigcode/self-oss-instruct-sc2-concepts
def permdb(ind, beta=0.5): """Perm function D, BETA defined as: $$ f(x) = \sum_{i=1}^d (\sum_{j=1}^n (j^i+\beta) ((\frac{x_j}{j})^i - 1) )^2$$ with a search domain of $-n < x_i < n, 1 \leq i \leq n$. The global minimum is at $f(x_1, ..., x_n) = f(1, 1/2, ..., 1/n) = 0. """ return sum(( \ ...
bigcode/self-oss-instruct-sc2-concepts
import random def random_tuple(k, n): """ Return a random tuple of k integers lower than n, all differents, uniformaly """ t = random.sample([x for x in range(n)], k) return tuple(t)
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def dict_get(prop: str, obj: Dict[str, Any]) -> Any: """ Get value of prop within obj. This simple function exists to facilitate a partial function defined :ref:`here<is_utterance>`. :param prop: A property within a :code:`dict`. :type prop: str ...
bigcode/self-oss-instruct-sc2-concepts
def inexact(pa, pb, pc): """Direction from pa to pc, via pb, where returned value is as follows: left: + [ = ccw ] straight: 0. right: - [ = cw ] returns twice signed area under triangle pa, pb, pc """ detleft = (pa[0] - pc[0]) * (pb[1] - pc[1]) detright = (pa[1] - pc[1]) * (pb[...
bigcode/self-oss-instruct-sc2-concepts
def release_to_text(release): """ Translate this Release object into a text string that would trigger this plugin's matcher. In other words, translate the release into something that could match ReleaseTask.from_text(). :param release: txproductpages.release.Release object :returns: str, l...
bigcode/self-oss-instruct-sc2-concepts
import torch def collate_fn(batch): """ Specify batching for the torch Dataloader function :param batch: each batch of the JsonlDataset :return: text tensor, attention mask tensor, img tensor, modal start token, modal end token, label """ lens = [len(row["sentence"]) for row in batch] bsz...
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup def create_soup(path): """ Reads a file and returns a lxml-xml BeautifulSoup object. """ with open(path, encoding="utf8") as f: return BeautifulSoup(f.read(), "lxml-xml")
bigcode/self-oss-instruct-sc2-concepts
def rt_range_overlaps(rt1, rt2): """ inputs: rt1: metatlas.datastructures.metatlas_objects.RtReference rt2: metatlas.datastructures.metatlas_objects.RtReference returns: True if there is overlap in the RT min-max regions of rt1 and and rt2 """ return ((rt2.rt_min <= rt1.rt_mi...
bigcode/self-oss-instruct-sc2-concepts
def split_half(args): """ Split the given list into two parts (equal if possible, if not the right one gets one more) Arguments --------- args : list list to split Returns ------- list, list Args split in two parts """ split = int(len(args) // 2) return arg...
bigcode/self-oss-instruct-sc2-concepts
def get_fit(eq_individual): """Given an Equation object, it will return its fitness score.""" return eq_individual.get_fitness()
bigcode/self-oss-instruct-sc2-concepts
def rubygems_homepage_url(name, version, repo='https://rubygems.org/gems'): """ Return a Rubygems.org homepage URL given a name, optional version and a base rubygems `repo` web interface URL. For instance: https://rubygems.org/gems/mocha/versions/1.7.0 or https://rubygems.org/gems/mocha """ ...
bigcode/self-oss-instruct-sc2-concepts
import importlib def import_class(what): """Import a class by given full name. Args: what (str): a string with full classname to import Return: (type): a class which has been imported """ modulename, classname = what.rsplit('.', 1) module = importlib.import_module(modulename) ...
bigcode/self-oss-instruct-sc2-concepts
import math def polysum(n, s): """ n: Number of sides s: Length of each side returns: sum of the area and square of the perimeter of the regular polygon """ area = (0.25*n*s*s)/math.tan(math.pi/n) perimeter = n*s sum = area + perimeter**2 return round(sum,4)
bigcode/self-oss-instruct-sc2-concepts
def dict_join(*dicts): """Join multiple dicts into one, updating duplicate keys from left-to-right manner. Thus the items from the rightmost dict will take precedence.""" rslt = {} for d in dicts: rslt.update(d) return rslt
bigcode/self-oss-instruct-sc2-concepts
def parse_hour(hour, sep=':') -> tuple: """Returns a tuple of integer from an hour like '14:34'.""" if not isinstance(hour, str): return hour return tuple([int(x) for x in hour.split(sep)])
bigcode/self-oss-instruct-sc2-concepts
def valid_dictionary_word(word, words_list): """Function to check if the word is in the dictionary. Args: word (str): word to test words_list (list): the "dictionary" Returns: bool: wether or not the word is in the dictionary """ if word in words_list: return True ...
bigcode/self-oss-instruct-sc2-concepts
def create_multidimensional_list(shape, element=None): """Creating a multidimensional list The recusion using list comprehension was obtained from create_empty_array_of_shape() at stackoverflow. Erko added element and the possibility to let element be a list. For example shape = [2...
bigcode/self-oss-instruct-sc2-concepts
def get_transfer_stats(client, pg_vol_snap_name): """ Returns a tuple of (started time, progress) """ transfer_stats = client.list_volumes(names=pg_vol_snap_name, snap=True, transfer=True)[0] return (transfer_stats["started"], transfer_stats["progress"])
bigcode/self-oss-instruct-sc2-concepts
def _getsubnodetext(node, name): """Get an element from an XML node, raise an error otherwise. Parameters ---------- node: Element XML Element name: str Child element name Returns ------- test: str Text contents of the child nodes """ subnode = node.find...
bigcode/self-oss-instruct-sc2-concepts
import re def isNegative(phrase): """ Returns True if the input phrase has a negative sentiment. Arguments: phrase -- the input phrase to-be evaluated """ return bool(re.search(r'\b(no(t)?|don\'t|stop|end)\b', phrase, re.IGNORECASE))
bigcode/self-oss-instruct-sc2-concepts
def freq_at_bit(in_data: list, position: int) -> tuple: """Returns frequency of bit '0' and '1' in the position 'position' for input data (list of str) Args: in_data (list): list of str position (int): position to check the bit in Returns: tuple: (int, int) """ bits = [0, 0] ...
bigcode/self-oss-instruct-sc2-concepts
def pixel_points(y1, y2, line): """ Converts the slope and intercept of each line into pixel points. Parameters: y1: y-value of the line's starting point. y2: y-value of the line's end point. line: The slope and intercept of the line. """ if line is None: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def get_valid_package_keys_matching(all_keys: List, input_key: str) -> List[str]: """Return a list of keys of graph nodes that match a package input. For our use case (matching user input to package nodes), a valid key is one that ends with the ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import List from typing import Tuple def dict_flatten( attrs: dict, delim: Optional[str] = None, indent_char: Optional[str] = None, bullet_char: Optional[str] = None, ) -> List[Tuple[str, str, str]]: """Recursively flattens dictionary to its atomic elements....
bigcode/self-oss-instruct-sc2-concepts
def get_givenl(l, osc, osckey): """ Returns frequencies, radial orders, and inertias or uncertainties of a given angular degree l. Parameters ---------- l : int Angular degree between l=0 and l=2 osc : array An array containing the individual frequencies in [0,:] and the ...
bigcode/self-oss-instruct-sc2-concepts