seed
stringlengths
1
14k
source
stringclasses
2 values
def generate_time_str(time): """convert time (in seconds) to a text string""" hours = int(time // 60**2) minutes = int((time - hours*60**2) // 60) seconds = int((time - hours*60**2 - minutes*60) // 1) ret = '' if hours: unit = 'hr' if hours == 1 else 'hrs' ret += f'{hours} {unit...
bigcode/self-oss-instruct-sc2-concepts
import json def load_json(fil): """ Loads a json file. """ dat = None with open(fil, "rt") as fh: dat = json.load(fh) return dat
bigcode/self-oss-instruct-sc2-concepts
def _aperture_mean_nomask(ap, image, **kwargs): """ Calculate the mean flux of an image for a given photutils aperture object. Note that we do not use ``_aperture_area`` here. Instead, we divide by the full area of the aperture, regardless of masked and out-of-range pixels. This avoids problems ...
bigcode/self-oss-instruct-sc2-concepts
def RB_decay_to_gate_fidelity(rb_decay, dimension): """ Derived from eq. 5 of [RB] arxiv paper. Note that 'gate' here typically means an element of the Clifford group, which comprise standard rb sequences. :param rb_decay: Observed decay parameter in standard rb experiment. :param dimension: Dimens...
bigcode/self-oss-instruct-sc2-concepts
def add(summand_a: int, summand_b: int) -> int: """Adds to integers and returns its sum""" return summand_a + summand_b # x = 'this is very very very very long script that has no obvious reason to exist'
bigcode/self-oss-instruct-sc2-concepts
import glob def case_insensitive_glob(pattern, **kwargs): """ Glob without case sensitivity Args: pattern (:obj:`str`): glob pattern **kwargs Returns: :obj:`list` of :obj:`str`: path of files that match the glob pattern """ def either(c): if c.isalpha(): ...
bigcode/self-oss-instruct-sc2-concepts
import requests def fetch_player_history(player_id): """ Fetch JSON of a single player's FPL history. """ url = "https://fantasy.premierleague.com/drf/element-summary/{}".format(player_id) r = requests.get(url) return r.json()["history_past"]
bigcode/self-oss-instruct-sc2-concepts
import copy def sanity_check_states(states_spec): """ Sanity checks a states dict, used to define the state space for an MDP. Throws an error or warns if mismatches are found. Args: states_spec (Union[None,dict]): The spec-dict to check (or None). Returns: Tuple of 1) the state space des...
bigcode/self-oss-instruct-sc2-concepts
def rr_and_single(x, y, nx, ny): """Dimensionless production rate for a gene regulated by two repressors with AND logic in the absence of leakage with single occupancy. Parameters ---------- x : float or NumPy array Concentration of first repressor. y : float or NumPy array ...
bigcode/self-oss-instruct-sc2-concepts
def quadsplit(quad): """Split ccw quad to two triangles""" v1, v2, v3, v4 = quad return [ [v1, v2, v3], [v3, v4, v1]]
bigcode/self-oss-instruct-sc2-concepts
import torch def synthetic_data(w, b, num_examples): #@save """Generate y = X w + b + noise.""" X = torch.zeros(size=(num_examples, len(w))).normal_() y = torch.matmul(X, w) + b y += torch.zeros(size=y.shape).normal_(std=0.01) return X, y
bigcode/self-oss-instruct-sc2-concepts
def rivers_with_station(stations): """ Returns a set of all rivers monitored by 'stations'. 'stations' is a list of 'MonitoringStation' objects. Documentation for object 'station' can be found by importing 'station' from 'floodsystem' and typing 'help(station.MonitoringStation)' """ river_lis...
bigcode/self-oss-instruct-sc2-concepts
def newton_sqrt1(x): """Return the square root of x using Newton's method""" val = x while True: last = val val = (val + x / val) * 0.5 if abs(val - last) < 1e-9: break return val
bigcode/self-oss-instruct-sc2-concepts
def prepend_indent(string, indent_level): """ Add a given indent before every line of the string :string: string to which we want to append the indent :indent_level: integer number of spaces to prepend """ indented = "".join("{}{}\n".format(" "*indent_level, line) for line in string.splitlines(...
bigcode/self-oss-instruct-sc2-concepts
def get_is_head_of_word(naive_tokens, sequence_tokens): """ Return a list of flags whether the token is head(prefix) of naively split tokens ex) naive_tokens: ["hello.", "how", "are", "you?"] sequence_tokens: ["hello", ".", "how", "are", "you", "?"] => [1, 0, 1, 1, 1, 0] *...
bigcode/self-oss-instruct-sc2-concepts
def half_period_uncoupled(t, x, par): """ Returns the event function Zero of this function is used as the event criteria to stop integration along a trajectory. For symmetric periodic orbits this acts as the half period event when the momentum coordinate is zero. Parameters ---------- t :...
bigcode/self-oss-instruct-sc2-concepts
def part_device(part_number): """Given partition number (but string type), return the device for that partition.""" return "/dev/mmcblk0p" + part_number
bigcode/self-oss-instruct-sc2-concepts
def wrap_to_pm(x, to): """Wrap x to [-to,to).""" return (x + to)%(2*to) - to
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import List def create_dict(n: int) -> Dict[int, List[int]]: """Returns Dictionary with numbers from 0 to n as keys which are mapped to lists containing squares and cubes of the respective keys. doctests: >>> create_dict(1) {0: [0, 0], 1: [1, 1]} ...
bigcode/self-oss-instruct-sc2-concepts
def err_response(reqid, code, msg, data=None): """ Formats a JSON-RPC error as a dict with keys: 'jsonrpc', 'id', 'error' """ err = {"code": code, "message": msg} if data: err["data"] = data return {"jsonrpc": "2.0", "id": reqid, "error": err}
bigcode/self-oss-instruct-sc2-concepts
def magic_square_params(diagonal_size): """ This is a helper function to create the gene_set, optimal_fitness and the expected sum of all the rows, columns and diagonals. :param diagonal_size: The diagonal length of the magic square. :type diagonal_size: int """ numbers = list(range(1, ...
bigcode/self-oss-instruct-sc2-concepts
def get_translate_str(type_name: str, namespace_: str, name: str) -> str: """ 规范得到翻译序列 :param type_name: 类型 :param namespace_: 命名空间 :param name: 名称 :return: 翻译序列 """ return f"{type_name}.{namespace_}.{name}"
bigcode/self-oss-instruct-sc2-concepts
def quick_pow(n: int, k: int, p: int) -> int: """Find n^k % p quickly""" if k == 0: return 1 tmp = quick_pow(n, k // 2, p) ** 2 return tmp % p if k % 2 == 0 else tmp * n % p
bigcode/self-oss-instruct-sc2-concepts
import itertools def combine_bucket( parts: list, threshold: int, truncate: bool = False, keep_remain: bool = False) -> list: """ Convert parts to buckets with given length(threshold). Parameters ---------- parts: the given parts. threshold: bucket length. ...
bigcode/self-oss-instruct-sc2-concepts
def remove_dataset_id(df, ds1_trend_column, ds2_trend_column): """deletes the data set id from a given ptcf :param df: PTCF data frame :ds1_trend_column: column name ds 1 :ds2_trend_column: column name ds 2 :return: ds without data set information """ df[ds1_trend_column] = df[ds1_trend_column].str.split('...
bigcode/self-oss-instruct-sc2-concepts
import re def strip_number(number): """Strips the number down to just digits.""" number = re.sub("[^0-9]", "", number) return number
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Tuple def stretch_in_row_or_column( stretched_list: list, two_coordinates: tuple ) -> List[Tuple[int, int]]: """ Update a list of coordinates by coordinates between two boundaries of a line. Form a line in horizontal or vertical direction. Args: ...
bigcode/self-oss-instruct-sc2-concepts
import math def normalize_function(foo, interval=(0, 1), precision=100): """ Normalizes function on given interval. Args: foo (function): Function to be normalized. interval (tuple): Interval of normalization. precision (int): Precision of numerical calculations. Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def num_in_base(num, base): """Converts an integer to its representation in base in big-endian. e.g., num_in_base(14, 2) = [1, 1, 1, 0]. Args: num: the number to convert. base: the base of the representation. Returns: The list of digits in big-endian. """ if num == 0: return [0] digits...
bigcode/self-oss-instruct-sc2-concepts
def compare_lists(list1: list, list2: list): """Returns the diff of the two lists. Returns ------- - (added, removed) ``added`` is a list of elements that are in ``list2`` but not in ``list1``. ``removed`` is a list of elements that are in ``list1`` but not in ``list2``. """ added = ...
bigcode/self-oss-instruct-sc2-concepts
import time def get_local_time_str(for_file_name=False) -> str: """Return current time str in the format %Y-%m-%d %H:%M:%S""" if not for_file_name: cur_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) else: cur_time = time.strftime("%Y-%m-%d--%H-%M-%S", time.localtime()) ret...
bigcode/self-oss-instruct-sc2-concepts
import importlib def load_module(module_name): """ Dynamically imports the specified module and returns it. :param str module_name: Name of the module to be imported as a string. """ return importlib.import_module(module_name)
bigcode/self-oss-instruct-sc2-concepts
def item_empty_filter(d): """return a dict with only nonempty values""" pairs = [(k, v) for (k, v) in d.items() if v] return dict(pairs)
bigcode/self-oss-instruct-sc2-concepts
def unicode_double_escape(s: str) -> str: """Remove double escaped unicode characters in a string.""" return bytes(bytes(s, "ascii").decode("unicode-escape"), "ascii").decode( "unicode_escape" )
bigcode/self-oss-instruct-sc2-concepts
def write_csv_file(dataframe, path): """ Write new file with provided dataframe path: the path to the new file dataframe: the data that need to be saved """ file_name = path+".csv" dataframe.to_csv(file_name, sep='\t', encoding='utf-8') print( "File {}.csv created".format(path)) ret...
bigcode/self-oss-instruct-sc2-concepts
import pathlib import xxhash def _get_xxhash(file_path: pathlib.Path) -> str: """Compute the hash of the content of file_pathpath""" n = file_path.stat().st_size x = xxhash.xxh128() m = 2 ** 23 # read 8MB each time with file_path.open('rb') as f: if n < m * 128: # <= 1GB, check the whole ...
bigcode/self-oss-instruct-sc2-concepts
def find_image_essex(client, image_name): """ Looks up the image of a given name in Glance. Returns the image metadata or None if no image is found. """ images = client.get_images(filters={'name': image_name}) if images: return images[0] else: return None
bigcode/self-oss-instruct-sc2-concepts
def parse_remote(path,loopback=False,login_flag=False): """parse remote connection string of the form ``[[user@]host:]path`` Args: path (str): remote connection string. loopback (bool, default=False): if True, ensure *host* is used. login_flag (bool, default=False): if True, prepend use...
bigcode/self-oss-instruct-sc2-concepts
def one_api(testCase, core): """ Get the only API registered against a given MimicCore. :return: 2-tuple of ``region`` and ``service_id`` """ service_id = None api = None # Since there is only 1 API it can be assumed to be either an internal # or external API. if len(core._uuid_to_...
bigcode/self-oss-instruct-sc2-concepts
def compose1(f, g): """Return the composition function which given x, computes f(g(x)). >>> add_one = lambda x: x + 1 # adds one to x >>> square = lambda x: x**2 >>> a1 = compose1(square, add_one) # (x + 1)^2 >>> a1(4) 25 >>> mul_three = lambda x: x * 3 # multiplies 3 to x ...
bigcode/self-oss-instruct-sc2-concepts
def parsenumber(v, strict=False): """ Attempt to parse the value as a number, trying :func:`int`, :func:`long`, :func:`float` and :func:`complex` in that order. If all fail, return the value as-is. .. versionadded:: 0.4 .. versionchanged:: 0.7 Set ``strict=True`` to get an exception if...
bigcode/self-oss-instruct-sc2-concepts
def missing_layers(dm_layers, ds_layers): """Find missing datamodel-layers in datasets.""" layers = [i.lower() for i in ds_layers] layers = [i for i in dm_layers if i not in layers] return layers
bigcode/self-oss-instruct-sc2-concepts
import requests def get_installation_token(installation_id, integration_jwt): """Create a GitHub token for an integration installation. Parameters ---------- installation_id : `int` Installation ID. This is available in the URL of the integration's **installation** ID. integration...
bigcode/self-oss-instruct-sc2-concepts
def make_words(text): """ make a list of words from a large bunch of text Strips all the punctuation and other stuff from a large string, and returns a list of words """ replace_punc = [('-', ' '), (',', ''), (',', ''), ('.', ''), ...
bigcode/self-oss-instruct-sc2-concepts
def is_external(config): """ Checks if the configuration is for an external transport. :param dict config: configuration to check :return: True if external, False otherwise :rtype: bool """ return config.get("external") == "1"
bigcode/self-oss-instruct-sc2-concepts
def obj_frequencies(df): """Total number of occurrences of individual objects over all frames.""" return df.noraw.OId.value_counts()
bigcode/self-oss-instruct-sc2-concepts
import re def check_file(file_contents: str) -> bool: """Check file for the snippet""" return bool(re.search(r"^if __name__ == \"__main__\":", file_contents, re.M))
bigcode/self-oss-instruct-sc2-concepts
def getInnerText(node): """ Get all the inner text of a DOM node (recursively). """ # inspired by http://mail.python.org/pipermail/xml-sig/2005-March/011022.html inner_text = [] for child in node.childNodes: if child.nodeType == child.TEXT_NODE or child.nodeType == child.CDATA_SECTION_NO...
bigcode/self-oss-instruct-sc2-concepts
import yaml def load_yaml(path): """Load YAML file into Python object.""" with open(path, "r") as file_data: data = yaml.safe_load(file_data) return data
bigcode/self-oss-instruct-sc2-concepts
def dot(a, b, out=None): """ Dot product of two arrays. Specifically, - If both `a` and `b` are 1-D arrays, it is inner product of vectors (without complex conjugation). - If both `a` and `b` are 2-D arrays, it is matrix multiplication, but using ``a @ b`` is preferred. - If either `a...
bigcode/self-oss-instruct-sc2-concepts
def labeller(n, symbol="q"): """Autogenerate labels for wires of quantum circuits. Parameters ========== n : int number of qubits in the circuit symbol : string A character string to precede all gate labels. E.g. 'q_0', 'q_1', etc. >>> from sympy.physics.quantum.circuitplot import ...
bigcode/self-oss-instruct-sc2-concepts
def _get_api_name(func): """e.g. Convert 'do_work' to 'Do Work'""" words = func.__name__.split('_') words = [w.capitalize() for w in words] return ' '.join(words)
bigcode/self-oss-instruct-sc2-concepts
def _fix_uppercase(kwargs): """ Properly handle uppercase arguments which are normalized by click. """ if 'c' in kwargs: kwargs['C'] = kwargs.pop('c') return kwargs
bigcode/self-oss-instruct-sc2-concepts
import math def inverse_kinematic(x, y, a1, a2): """ :param x: x position of end effector :param y: y position of end effector :param a1: length of member 1 :param a2: length of member 2 :return: angles of a 2 joint same plane robot arm """ # find q2 angle of the second joint num ...
bigcode/self-oss-instruct-sc2-concepts
import requests def get_current_microsoft_public_keys(ms_signing_key_url='https://login.microsoftonline.com/common/discovery/keys'): """Returns the list of currently in use public keys. Args: ms_signing_key_url: The known url for the public keys .. note:: These guys are updated approxim...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def get_season_url( base_url: str, year: Optional[int] = None, season: Optional[str] = None ) -> str: """Creates the URL for the season endpoint.""" if year is None or season is None: return f"{base_url}/season" return f"{base_url}/season/{year}/{season.lower()}"
bigcode/self-oss-instruct-sc2-concepts
def intersection(lista, listb): """Return the intersection between two lists. Note, for duplicate values, each duplicate will be returned as we merely check if item in lista, is in listb.""" return [item for item in lista if item in listb]
bigcode/self-oss-instruct-sc2-concepts
def bed4_to_node2coordinates(bed4): """Compute the node2coordinates DataFrame: exon name, chrom, start, end""" node2coordinates = bed4\ [["name", "chrom", "chrom_start", "chrom_end"]]\ .set_index("name") return node2coordinates
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def count_layer_types(model): """Count layers by layer type. Parameters ---------- model : keras.engine.training.Model A Keras model. Returns ------- collections.Counter Counter object containing number of layers in the model by layer type. ...
bigcode/self-oss-instruct-sc2-concepts
async def prefix_getter_static(prefix, message): """ Returns a prefix for the message. This function is a coroutine. Parameters ---------- prefix : `str` The prefix to return. message : ``Message`` The received message to parse the prefix from. Returns ...
bigcode/self-oss-instruct-sc2-concepts
import torch def silu(x): """ Smoothed ReLU (Sigmoid-ReLU) """ return x*torch.sigmoid(x)
bigcode/self-oss-instruct-sc2-concepts
def use_kd_tree(request): """Whether to use the KD Tree in CVTArchive.""" return request.param
bigcode/self-oss-instruct-sc2-concepts
def _zero_based_index(i, l, start=True): """Compute the 0-based index from the slice index i in a list of length l Assuming step is 1. Examples -------- >>> _concrete_index(2, 100) 2 >>> _concrete_index(2, 100, start=False) 2 >>> _concrete_index(-1, 100, start=False) 99 >>> ...
bigcode/self-oss-instruct-sc2-concepts
def checksum(spreadsheet): """ Calculate the checksum of a spreadsheet by summing up the ranges of all lines. >>> checksum([ ... [5, 1, 9, 5], ... [7, 5, 3], ... [2, 4, 6, 8] ... ]) 18 """ return sum( max(line) - min(line) for line in spreadsheet ...
bigcode/self-oss-instruct-sc2-concepts
def lsymm(self, ncomp="", nl1="", nl2="", ninc="", kinc="", noelem="", imove="", **kwargs): """Generates lines from a line pattern by symmetry reflection. APDL Command: LSYMM Parameters ---------- ncomp Symmetry key: X - X symmetry (default). Y - Y symmetry. ...
bigcode/self-oss-instruct-sc2-concepts
def comp_masses(self): """Compute the masses of the Lamination Parameters ---------- self : Lamination A Lamination object Returns ------- M_dict: dict Lamination mass dictionary (Mtot, Mlam, Mteeth, Myoke) [kg] """ rho = self.mat_type.struct.rho V_dict = self....
bigcode/self-oss-instruct-sc2-concepts
def get_xpath_parent(xpath, level=1): """ Get the parent xpath at any level, 1 is parent just above the input xpath. Args: xpath (str): Input xpath level (int, optional): Parent level. Defaults to 1. Returns: str: Parent xpath """ if not xpath.startswith("/"): rais...
bigcode/self-oss-instruct-sc2-concepts
def pad_list(xs, pad_value=0., pad_left=False): """Convert list of Tensors to a single Tensor with padding. Args: xs (list): A list of length `[B]`, which contains Tensors of size `[T, input_size]` pad_value (float): pad_left (bool): Returns: xs_pad (FloatTensor): `[B, T, inp...
bigcode/self-oss-instruct-sc2-concepts
def get_cube_diff(cube_1, cube_2): """ Take the difference of two Iris data cubes. Computed as cube_1 - cube_2. Parameters ---------- cube_1 : Iris cube. cube_2 : Iris cube. Return ------ Iris cube containing the difference of cube_1 - cube_2 """ diff_cube = cu...
bigcode/self-oss-instruct-sc2-concepts
def and_from_dict(kwargs): """ Generate a SQL And statement from a dict of keyword args :param kwargs: Keyword arguments dict :return: String AND statement """ return " AND ".join(f"{x} = %({x})s" if kwargs[x] is not None else f"{x} is %({x})s" for x in kwargs)
bigcode/self-oss-instruct-sc2-concepts
def PNewOTFTable (inOTF, access, tabType, tabVer, err, numDet=1, numPoly=0, numParm=0): """ Return the specified associated table inOTF = Python OTF object access = access code 1=READONLY, 2=WRITEONLY, 3=READWRITE tabType = Table type, e.g. "OTFSoln" tabVer = table...
bigcode/self-oss-instruct-sc2-concepts
import re def uncamel(val): """Return the snake case version of :attr:`str` >>> uncamel('deviceId') 'device_id' >>> uncamel('dataCenterName') 'data_center_name' """ s = lambda val: re.sub('(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))', '_\\1', val).lower().strip('_') return s(val)
bigcode/self-oss-instruct-sc2-concepts
def GetGroup(node,groupName,verbose=False): """ **GetGroup** - Gets the requested group node within the netCDF Loop Project File Parameters ---------- rootGroup: netCDF4.Group A group node of a Loop Project File Returns ------- dict {"errorFlag","errorString"/"value"} ...
bigcode/self-oss-instruct-sc2-concepts
def remove_blank_wrap(value, context): """ Remove blank and text wrap in the value. """ return "".join(value.split())
bigcode/self-oss-instruct-sc2-concepts
import torch def _onenorm_matrix_power_nnm(A, p): """ Compute the 1-norm of a non-negative integer power of a non-negative matrix. Parameters ---------- A : a square ndarray or matrix or sparse matrix Input matrix with non-negative entries. p : non-negative integer The power t...
bigcode/self-oss-instruct-sc2-concepts
import torch def log_int_prod_gaussians(N1: dict, N2: dict) -> torch.Tensor: """Calculate log integral N(x; m1, cov1) * N(x; m2, cov2) dx Args: N = {'mean': torch.Tensor(k, d), 'cov': torch.Tensor(k, d, d)} Returns: k1-by-k2 matrix """ # get number of components k1, d = N1['mean'].sh...
bigcode/self-oss-instruct-sc2-concepts
def as_macro_define(m, v): """Return as a C preprocessor command line macro definition""" if v: return '-D%s=%s' % (m, v) return '-D%s' % (m,)
bigcode/self-oss-instruct-sc2-concepts
def get_ants_transforms(in_affine_transformation, in_bspline_transformation): """Combine transformations for antsApplyTransforms interface.""" return [in_bspline_transformation, in_affine_transformation]
bigcode/self-oss-instruct-sc2-concepts
def prandtl(viscosity: float, Cp: float, KAPPA=0.026) -> float: """Calculatres the Prandtl number. Args: viscosity (float): Air dynamic vicosity [Ns/(m^2)]. Cp (float): Spectfic Heat Constant Pressure [J/kg*K]. KAPPA (float, optional): W/(mK) air. Defaults to 0.026. Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def connection_requires_http_tunnel( proxy_url=None, proxy_config=None, destination_scheme=None ): """ Returns True if the connection requires an HTTP CONNECT through the proxy. :param URL proxy_url: URL of the proxy. :param ProxyConfig proxy_config: Proxy configuration from poolman...
bigcode/self-oss-instruct-sc2-concepts
def tmp_working_directory_path(tmp_path) -> str: """ Return a path to a temporary working directory (different path for each test). """ destination = tmp_path.joinpath("obfuscation_working_dir") destination.mkdir() return str(destination)
bigcode/self-oss-instruct-sc2-concepts
from typing import MutableMapping def _toc_enabled(env: MutableMapping) -> bool: """Is there a valid ToC definition in the Markdown?""" opts = env["mdformat-toc"]["opts"] return bool(opts)
bigcode/self-oss-instruct-sc2-concepts
def harmonic_oscillator(grids, k=1.): """Potential of quantum harmonic oscillator. Args: grids: numpy array of grid points for evaluating 1d potential. (num_grids,) k: strength constant for potential vp = 0.5 * k * grids ** 2 Returns: vp: Potential on grid. (num_grid,) """ vp = 0.5 *...
bigcode/self-oss-instruct-sc2-concepts
def insertion_sort(list): """ Takes in a list and sorts the list using an insertion sort method. Modifies the list in place, but returns it for convenience. """ round_number = 1 curr = round_number while round_number < len(list): while curr > 0: if list[curr] < list[curr ...
bigcode/self-oss-instruct-sc2-concepts
def get_users_without_name(conn): """Get users with empty name column""" res = conn.execute(""" SELECT id FROM people WHERE name='' """) ids = [person[0] for person in res.fetchall()] return ids
bigcode/self-oss-instruct-sc2-concepts
def build_annual_urls(first_url,year): """ This method takes the first SD url and creates a list of urls which lead to the following pages on SD which will be scraped. The page list is for a given year. """ page_urls = [] for i in range(20): url_100 = first_url.replace('&show=25','&...
bigcode/self-oss-instruct-sc2-concepts
def unit_vector(v): """Return the unit vector of the points v = (a,b)""" h = ((v[0]**2)+(v[1]**2))**0.5 if h == 0: h = 0.000000000000001 ua = v[0] / h ub = v[1] / h return (ua, ub)
bigcode/self-oss-instruct-sc2-concepts
import unittest import torch def require_cpu(test_case): """ Decorator marking a test that must be only ran on the CPU. These tests are skipped when a GPU is available. """ return unittest.skipUnless(not torch.cuda.is_available(), "test requires only a CPU")(test_case)
bigcode/self-oss-instruct-sc2-concepts
def escape(s): """ Replace potential special characters with escaped version. For example, newline => \\n and tab => \\t """ return s.replace('\n', '\\n').replace('\t', '\\t').replace('\r', '\\r')
bigcode/self-oss-instruct-sc2-concepts
def bresenham(x1, y1, x2, y2): """ Return a list of points in a bresenham line. Implementation hastily copied from RogueBasin. Returns: List[Tuple[int, int]]: A list of (x, y) points, including both the start and end-points. """ points = [] issteep = abs(y2-y1) > abs(x2...
bigcode/self-oss-instruct-sc2-concepts
def Affine(x, w, b): """Computes the affine transformation. Args: x: Inputs w: Weights b: Bias Returns: y: Outputs """ # y = np.dot(w.T, x) + b y = x.dot(w) + b return y
bigcode/self-oss-instruct-sc2-concepts
def lines_from_geometry(geo): """Convert an iterable of geometry to lines. Suitable for passing directly to `matplotlib.collections.LineCollection`. :param geo: An iterable of geometry items. If cannot be coverted to a line, then ignored. :return: A list of coordinates. """ ...
bigcode/self-oss-instruct-sc2-concepts
def enumerate_dataset(start=0): """A transformation that enumerates the elements of a dataset. It is similar to python's `enumerate`. For example: ```python # NOTE: The following examples use `{ ... }` to represent the # contents of a dataset. a = { 1, 2, 3 } b = { (7, 8), (9, 10) } # The nested st...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from datetime import datetime def get_timestamp(tstamp: Optional[datetime] = None) -> object: """Get a string representing the a time stamp. Args: tstamp: datetime.datetime object representing date and time. If set to None, the current time is taken. Retur...
bigcode/self-oss-instruct-sc2-concepts
def determine_wgtflag(vwgt, adjwgt): """Determine the wgtflag used in many parallel partitioning routines """ if vwgt is None and adjwgt is None: return 0 if vwgt is None: return 1 return 2 if adjwgt is None else 3
bigcode/self-oss-instruct-sc2-concepts
import inspect def get_method_arguments(method, exclude=None): """ Return the method's argument, associated with a boolean describing whether or not the given argument is required. """ signature = inspect.getfullargspec(method) args_count = len(signature.args) if signature.args else 0 ...
bigcode/self-oss-instruct-sc2-concepts
def load(attr, element, default=None): """ Helper function for loading XML attributes with defaults. """ if not element in attr.__dict__: return default return attr[element]
bigcode/self-oss-instruct-sc2-concepts
def to_int(s, fallback=0): """Try to cast an int to a string. If you can't, return the fallback value""" try: result = int(s) except ValueError: # logging.warning("Couldn't cast %s to int" % s) result = fallback except TypeError: # logging.warning("Couldn't cast %s to int...
bigcode/self-oss-instruct-sc2-concepts
def get_list(node, tag): """ Get sub-nodes of this node by their tag, and make sure to return a list. The problem here is that xmltodict returns a nested dictionary structure, whose substructures have different *types* if there's repeated nodes with the same tag. So a list of one thing ends up bein...
bigcode/self-oss-instruct-sc2-concepts
def get_center(centers, vector, distance_function): """ Determines which center is closest to the given vector. The given distance function will be used to calculate the distance between the vector and possible centers. The centers should be a list of numpy vectors, and vector should be a numpy ...
bigcode/self-oss-instruct-sc2-concepts