seed
stringlengths
1
14k
source
stringclasses
2 values
def lasso(number: complex, unit: str = '') -> str: """ Make a large number more readable by inserting commas before every third power of 10 and adding units """ return f'{number:,} {unit}'.strip()
bigcode/self-oss-instruct-sc2-concepts
def render_header(level_and_content): """ - level_and_content: None OR string OR list of [postive-int, string] OR tuple of (positive-int, string), the header level and content RETURN: string, the header """ if level_and_content is None: return "" if isinstance(level_and_content, st...
bigcode/self-oss-instruct-sc2-concepts
def remove_coords(cube): """ Remove non-essential coordinates from ``cube``. This should prevent a number of subsequent cube concatenation issues, plus reduce output file size. Note, however, that scalar coordinates, such as level number in the case of a vertical subset, are also removed. """ ...
bigcode/self-oss-instruct-sc2-concepts
def add_gencfg_parser_options(p): """Add `pbsv1 genenrate-config` parser options""" p.add_argument('-o', '--cfg_fn', metavar="sv.cfg", dest="cfg_fn", type=str, default=None, help="Pbsv1 config file.") return p
bigcode/self-oss-instruct-sc2-concepts
def guess_scheme(environ): """Return a guess for whether 'wsgi.url_scheme' should be 'http' or 'https' """ if environ.get("HTTPS") in ('yes','on','1'): return 'https' else: return 'http'
bigcode/self-oss-instruct-sc2-concepts
import base64 def authorization(pat_token, response_type): """ Creates the header for using api calls with PAT tokens """ authorization_base64_bytes = bytes(':'+pat_token, 'ascii') authorization_base64_encode = base64.b64encode(authorization_base64_bytes) authorization_base64_string = str(auth...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def check_and_get_subdirectory(base_dir: Path, subdir_name: str) -> Path: """ Checks existance of base_dir, NON-existance of base_dir/subdir, and returns the Path(base_dir / subdir). Raises: FileNotFoundError if the base_dir does not exist OSError if the...
bigcode/self-oss-instruct-sc2-concepts
def uncompress_indices(compressed): """Reverse of compress_indices. """ indices = [] for i in range(len(compressed) - 1): indices.extend([i] * (compressed[i+1] - compressed[i])) return indices
bigcode/self-oss-instruct-sc2-concepts
def accuracy_metrics(act, exp): """Return precision and recall for a single query Args: act (set): actual result exp (set): expected result Returns: float, float: precision and recall """ if act == exp: # Consider the edge case: act=[] exp=[] ...
bigcode/self-oss-instruct-sc2-concepts
def isgenerator(x): """ Returns `True` if the given value is sync or async generator coroutine. Arguments: x (mixed): value to check if it is an iterable. Returns: bool """ return any([ hasattr(x, '__next__'), hasattr(x, '__anext__') ])
bigcode/self-oss-instruct-sc2-concepts
def to_years_and_months(months): """ Convert a integer value into a string of years and months e.g. 27 would be represented as '2 Years 3 Months' """ whole_years = months // 12 remaining_months = months % 12 result = '' if whole_years >= 1: if whole_years == 1: result...
bigcode/self-oss-instruct-sc2-concepts
import operator def sub_wo_carry(n1, n2): """ Substract two integer strings of same length without carry >>> sub_wo_carry('9007', '1234') '8873' """ l1 = [int(x)+10 for x in str(n1)] l2 = [int(x) for x in str(n2)] res1 = map(operator.sub, l1, l2) res2 = [str(x)[-1] for x in res1] ...
bigcode/self-oss-instruct-sc2-concepts
def generate_sets_item_query(names, sets): """ Builds a query with a specified number of sets. :param list names: The name of the workout item. :param int sets: The number of sets to generate in the query. :return: SQL compatible query as a string. """ master_tuple_list = [] for name in...
bigcode/self-oss-instruct-sc2-concepts
def get_fname(dsrc,depTime,mforecast): """ Returns the name of the grib file on the NCDC server at the time requested Args: * 'dsrc' (string): type of source files for weather: either namanl or rap * 'DT (string): date and time of the grib file requested * 'mforecast' (string): ...
bigcode/self-oss-instruct-sc2-concepts
import json def _hash_task(task): """ Returns a unique hash for identify a task and its params """ params = task.get("params") if params: params = json.dumps(sorted(list(task["params"].items()), key=lambda x: x[0])) # pylint: disable=no-member full = [str(task.get(x)) for x in ["path", "int...
bigcode/self-oss-instruct-sc2-concepts
import random def RandomSample(data, size): """Returns random sample of given size """ return data.ix[random.sample(data.index, size)]
bigcode/self-oss-instruct-sc2-concepts
def check_horizontal_winner(board) -> bool: """checks for horizontal winner""" for row in board: if row[0] == row[1] == row[2] and row[0] is not None: return True return False
bigcode/self-oss-instruct-sc2-concepts
def _comment(s): """Returns a new string with "#" inserted before each line in 's'.""" if not s: return "#" res = "".join(["#" + line for line in s.splitlines(True)]) if s.endswith("\n"): return res + "#" return res
bigcode/self-oss-instruct-sc2-concepts
def flatten_string_list(arglist): """ Assemble a list of string, such as for a subprocess call. Input should be a string or a list containing only strings or similar lists. Output will be a list containing only strings. """ if isinstance(arglist, ("".__class__, u"".__class__)): retur...
bigcode/self-oss-instruct-sc2-concepts
def extract(input_data: str) -> tuple: """take input data and return the appropriate data structure""" rules = dict() messages = list() rules_input, messages_input = input_data.split('\n\n')[0:2] for rule_input in rules_input.split('\n'): rule_id, rule = rule_input.split(': ') rules...
bigcode/self-oss-instruct-sc2-concepts
import math def aika(etäisyys, nopeus): """ Laske annetun etäisyyden ajamiseen tarvitun ajan tunneissa ja minuuteissa. """ aika = etäisyys / nopeus minuutit, tunnit = math.modf(aika) return (int(tunnit), int(minuutit * 60))
bigcode/self-oss-instruct-sc2-concepts
def content_function(obj): """Just return content""" _, _, _, content = obj return 'content', content
bigcode/self-oss-instruct-sc2-concepts
import re def validate_maintenance_window(window): """Validate PreferredMaintenanceWindow for DBInstance""" days = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") day_re = r'[A-Z]{1}[a-z]{2}' hour = r'[01]?[0-9]|2[0-3]' minute = r'[0-5][0-9]' r = ("(?P<start_day>%s):(?P<start_hour>%s):(?P<s...
bigcode/self-oss-instruct-sc2-concepts
import ctypes from typing import Optional def _aligned_ptr_offset_in_object(obj: object, referent: object) -> Optional[int]: """Return the byte offset in the C representation of *obj* (an arbitrary Python object) at which is found a naturally-aligned pointer that points to *referent*. If *search_for* ...
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_classifier(model_path, vec_path): """ Loads classifier from subfolder . Parameters ---------- model_path: String The path where the classifier is stored vec_path: String The path where the vectorizer is...
bigcode/self-oss-instruct-sc2-concepts
def check_config_inputs(arg): """ Checks that all the data that should be numerical from that config can be represented as a float. Parameters __________ arg: unknown any argument can be passed. Returns _______ is_number: Boolean Value is True if the arg is a number...
bigcode/self-oss-instruct-sc2-concepts
def dim_check(dev_dist, std_min, std_max): """ Boolean: does value fall within allowed range? """ return std_min <= dev_dist <= std_max
bigcode/self-oss-instruct-sc2-concepts
import torch import operator def summarize_profiler_info(prof: torch.autograd.profiler.profile) -> str: """ Summarizes the statistics in the specified profiler. """ # create sorted list of times per operator: op2time = {} for item in prof.key_averages(): op2time[item.key] = ( ...
bigcode/self-oss-instruct-sc2-concepts
def decode(string): """Decodes a String""" dec_string = string \ .replace('&amp;', '&') \ .replace('&lt;', '<') \ .replace('&gt;', '>') return dec_string
bigcode/self-oss-instruct-sc2-concepts
import glob def _get_header_files(include_dirs): """Return a list of all extra headers to include in checks.""" headers = [] for path in include_dirs: headers += glob.glob(path + "/**/*.h", recursive=True) headers += glob.glob(path + "/**/*.hh", recursive=True) headers += glob.glo...
bigcode/self-oss-instruct-sc2-concepts
def read_file(filename, delimiter=None, startline=0): """Reads a text file into a list of lists Parameters ---------- filename : string the file path to open delimiter : string (optional) the delimiter separating the column data (default to None for all white space) startline : ...
bigcode/self-oss-instruct-sc2-concepts
def penalize_short(genotype, weight=20): """fitness function handling short notes Args: genotype ((int, int)[]): list of tuples (pitch, dur) representing genotype of a chromosome weight (int, optional): Defaults at 20. Defines penalty/reward rate Returns: int: aggregate fi...
bigcode/self-oss-instruct-sc2-concepts
import requests from bs4 import BeautifulSoup import random def grab_a_paper(base_url): """ Given an arXiv base url, grab a random paper from that URL """ links = [] titles = [] papers = {} # a dictionary of links and titles # Get webpage and initialize bs object r = requests.get(bas...
bigcode/self-oss-instruct-sc2-concepts
def smallest_side(length: int, width: int, height: int) -> int: """Multiply the smallest edges of a gift to get its smallest side Args: length (int): The length of the gift width (int): The width of the gift height (int): The height of the gift Returns: int: The area of the...
bigcode/self-oss-instruct-sc2-concepts
def _detect_fully_listened_track(remaining_duration, end_of_track_buffer) -> bool: """Performs the detection logic for whether a track was fully listened through Args: remaining_duration: The remaining duration of the track in milliseconds end_of_track_buffer: T...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def get_filename_from_query(query: List[str]) -> str: """Convert a keyword query into filenames to dump the paper. Args: query (list): List of string with keywords. Returns: str: Filename. """ filename = "_".join([k if isinstance(k, str) else k[0] for k in...
bigcode/self-oss-instruct-sc2-concepts
def get_object_type(object_id): """ Obtain object type Parameters ---------- object_id : int object identifier Returns ------- object_type : str type of object """ # https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/req/naif_ids.html if object_id < -100000: ...
bigcode/self-oss-instruct-sc2-concepts
def _import(class_path): """ Imports a module or class from a string in dot notation. """ bits = class_path.split('.') mod_name = '.'.join(bits[:-1]) cls_name = bits[-1] mod = __import__(mod_name, None, None, cls_name) return getattr(mod, cls_name)
bigcode/self-oss-instruct-sc2-concepts
def control_change_rate_cost(u, u_prev): """Compute penalty of control jerk, i.e. difference to previous control input""" return (u - u_prev) ** 2
bigcode/self-oss-instruct-sc2-concepts
def cremona_letter_code(n): """ Returns the Cremona letter code corresponding to an integer. For example, 0 - a 25 - z 26 - ba 51 - bz 52 - ca 53 - cb etc. .. note:: This is just the base 26 representation of n, where a=0, b=1, ..., z=25. This extends the old Cremona notation (counting f...
bigcode/self-oss-instruct-sc2-concepts
def compose( rf1, rf2 ): """Combines two reduction functions - normally ones which reduce over different axes - into one. Each reduction function should take a single MV as an argument and return a MV. Each should accept an optional keyword argument vid, defaulting to None.""" def rf12( mv, vid=None ):...
bigcode/self-oss-instruct-sc2-concepts
def add(x: int, y: int) -> int: """Add two numbers. >>> add(1, 2) 3 Args: x: An operand. y: An operand. Returns: x + y. """ return x + y
bigcode/self-oss-instruct-sc2-concepts
def all_subclasses(cls): """Recursively find subclasses of a class. The subclasses should already be imported for this function to work properly. Args: cls (type): Class to inspect. Returns: set[type]: The set of subclasses. """ return set(cls.__subclasses__()).union( ...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def api_image_file( test_image_path: Path, ) -> dict[str, tuple[str, bytes, str]]: """Return the dict with file needed to use post requests.""" return { "file": ( test_image_path.name, test_image_path.open("rb").read(), "image/png", ...
bigcode/self-oss-instruct-sc2-concepts
def rolling_apply(df, window, func, shift=1, *args, **kwargs): """Calculate rolling apply() to all columns of a pandas dataframe Function can be used by ApplyFunc module. :param pd.DataFrame df: input pandas dataframe :param int window: size of rolling window. :param func: function to be applied ...
bigcode/self-oss-instruct-sc2-concepts
def get_number_base(bitstring, base): """Transfer bitstring to a number in base `base`.""" nr = 0 for place, bit in enumerate(bitstring[::-1]): nr += base**place * int(bit) return nr
bigcode/self-oss-instruct-sc2-concepts
def eulers_method(f, y, dx, range): """ The Eulers method for a first order differential equation. :param f: First order differential equation to approximate the solution for. :type f: lambda :param y: The initial condition for the y-value. :type y: float, int :param dx: Step size. Smaller ...
bigcode/self-oss-instruct-sc2-concepts
def ask_confirmation(action): """ Asks the user for confirmation of action. Parameters ---------- action : str The action to take place if confirmed. Returns ------- str : The action to be executed if confirmed, aborts otherwise. """ confirmation = str(input("P...
bigcode/self-oss-instruct-sc2-concepts
import requests def buscar_avatar(usuario): """ Busca o avatar de um usuário no Github :param usuario: str com o nome de usuário no github :return: str com o link do avatar """ url = f'https://api.github.com/users/{usuario}' resp = requests.get(url) print(resp.status_code) return ...
bigcode/self-oss-instruct-sc2-concepts
def clear_refills_2016(oven_refill_ends): """ Some of the automatically found refills in 2016 are incorrect and result e.g. from short oven stops. They are cleared out with this function based on manual selection and comparison with CALS. Parameters ---------- oven_refill_ends : list of timesta...
bigcode/self-oss-instruct-sc2-concepts
def _get_precip(sel_cim_data): """Return total precipitation.""" return sel_cim_data.TotalPrecip_tavg
bigcode/self-oss-instruct-sc2-concepts
def clean_hypothesis(hyp: str) -> str: """ Remove extra words after the question mark of the generated question Parameters ---------- hyp : str Hypothesis question Returns ------- str the cleaned hypothesis question """ _loc = hyp.find("?") if _loc == -1: #...
bigcode/self-oss-instruct-sc2-concepts
def calc_gamma(Ti): """Derive gamma from Ti""" return 1.0 / Ti
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce import operator def bitor(*args): """ BITOR num1 num2 (BITOR num1 num2 num3 ...) outputs the bitwise OR of its inputs, which must be integers. """ return reduce(operator.or_, args)
bigcode/self-oss-instruct-sc2-concepts
def after_request(response): """Modify response headers including Access-Control-* headers. :param response: An instance of the response object. :return: As instance of the response object with Access-Control-* headers. """ response.headers.add( "Access-Control-Allow-Headers", "Content-Type...
bigcode/self-oss-instruct-sc2-concepts
def drop_empty_rows(rows): """Return `rows` with all empty rows removed.""" return [row for row in rows if any(val.strip() for val in row)]
bigcode/self-oss-instruct-sc2-concepts
def preprocess(theorem, chromosome): """ convert chromosome to complete Coq script Args: theorem (list): a list of string contains theorem or some pre-provided tactic. chromosome (list): a list of string. Returns: byte: a byte string will be passed to coqtop """...
bigcode/self-oss-instruct-sc2-concepts
def char_to_word_index(ci, sequence): """ Given a character-level index (offset), return the index of the **word this char is in** """ i = None for i, co in enumerate(sequence.char_offsets): if ci == co: return i elif ci < co: return i - 1 return i
bigcode/self-oss-instruct-sc2-concepts
import hashlib def md5(filename): """ Return the MD5 hash of a file. Parameters ---------- filename : str The name of the file to check. Returns ------- str The MD5 hash in hexadecimal. """ with open(filename) as fin: return hashlib.md5(fin.read().enc...
bigcode/self-oss-instruct-sc2-concepts
def get_dirs(basedir): """ Configuration of subdirectory names relative to the basedir. """ return { 'templates': basedir + '/templates', # Mako templates 'content': basedir + '/content', # Markdown files 'output': basedir + '/htdocs', 'static': basedir + '/static', ...
bigcode/self-oss-instruct-sc2-concepts
def GetTag(client, messages, tag): """Gets a tag by its name.""" get_tag_req = messages.ArtifactregistryProjectsLocationsRepositoriesPackagesTagsGetRequest( name=tag) return client.projects_locations_repositories_packages_tags.Get(get_tag_req)
bigcode/self-oss-instruct-sc2-concepts
import re def get_max_deltas(filename): """Returns maximum gap parameters for the specified CoMetGeNe result file. :param filename: CoMetGeNe result file :return: tuple representing the gap parameters for genome and metabolic pathway, respectively """ pattern = re.compile("--- delta_G = (...
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable def word_join( iterable: Iterable[str], use_repr: bool = False, oxford: bool = False, delimiter: str = ',', connective: str = "and", ) -> str: """ Join the given list of strings in a natural manner, with 'and' to join the last two elements. :param iterable: :param use_repr...
bigcode/self-oss-instruct-sc2-concepts
import torch def evaluate_acc(confidences: torch.Tensor, true_labels: torch.Tensor) -> float: """ Args: confidences (Tensor): a tensor of shape [N, K] of predicted confidences. true_labels (Tensor): a tensor of shape [N,] of ground truth labels. Returns: acc (floa...
bigcode/self-oss-instruct-sc2-concepts
def public(endpoint): """Declare an endpoint to be public, i.e., not requiring auth.""" # Store metadata on this function stating that it is unprotected endpoint.is_protected = False return endpoint
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter from functools import reduce import operator def add_dicts(*args): """ Adds two or more dicts together. Common keys will have their values added. For example:: >>> t1 = {'a':1, 'b':2} >>> t2 = {'b':1, 'c':3} >>> t3 = {'d':4} >>> add_dicts(t1, t...
bigcode/self-oss-instruct-sc2-concepts
def preprocess_image(image): """Preprocesses an image into the form suitable for machine learning model input. Args: image: The image to preprocess. Returns: The preprocessed image. """ return image / 255.0
bigcode/self-oss-instruct-sc2-concepts
def check_static_metrics(expected_metrics, error_message=""): """Create a callable to verify that the static provider response contains the expected values. To be used with the :meth:`run` function. The callable will raise an :class:`AssertionError` if the static metrics in the response are different ...
bigcode/self-oss-instruct-sc2-concepts
import re def replace_strip(text): """ Remove newline, carriage return, tabs from string and split by ',' Parameters ---------- :param text: input text </br> :return: list of words """ data = re.sub(r"[\n\r\t]", "", text.lower()).split(",") data = [item.strip() for item in data] ...
bigcode/self-oss-instruct-sc2-concepts
import json import requests def unpack_response(response): """ Fetches the JSON body of a response and returns a tuple composed of the response itself with the decoded JSON. """ try: j = response.json() except json.JSONDecodeError: j = response.text if response.status_code...
bigcode/self-oss-instruct-sc2-concepts
def format_datetime(date_time): """Generate string from datetime object.""" return date_time.strftime("%Y-%m-%d %H:%M:%S")
bigcode/self-oss-instruct-sc2-concepts
def get_download_ranges_list(range_left, range_right, parts): """ function to get a list of ranges to be downloaded by each thread """ l = range(range_left, range_right + 1) dividend, remainder = divmod(len(l), parts) ranges_list = list( l[i * dividend + min(i, remainder) : (i+1) * dividend ...
bigcode/self-oss-instruct-sc2-concepts
def read_magnum_cluster_template(client, cluster): """Get the actual template associated with the one specified in the given Magnum cluster resource. Args: client (MagnumV1Client): the Magnum client to use to connect to the Magnum service. cluster (krake.data.openstack.MagnumClu...
bigcode/self-oss-instruct-sc2-concepts
def gen_property_of_type(name, _type, doc=""): """ Generates a type-forced property associated with a name. Provides type checking on the setter (coherence between value to be set and the type specified). @param name: property name @param _type: force type @param doc: documentation for the prop...
bigcode/self-oss-instruct-sc2-concepts
def replace_quotes(match): """Replace match with « xxxxxxx ».""" length = len(match.group(0)) - 4 return "« " + length * "x" + " »"
bigcode/self-oss-instruct-sc2-concepts
import secrets def branch() -> str: """Return a branch name that is unique for every test case.""" random = secrets.token_hex(nbytes=3) return f"branch-{random}"
bigcode/self-oss-instruct-sc2-concepts
def legendre_polynomial(x: float, n: int) -> float: """Evaluate n-order Legendre polynomial. Args: x: Abscissa to evaluate. n: Polynomial order. Returns: Value of polynomial. """ if n == 0: return 1 elif n == 1: return x else: polynomials = [...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def jaccard_similarity(correct_duplicates: List, retrieved_duplicates: List) -> float: """ Get jaccard similarity for a single query given correct and retrieved file names. Args: correct_duplicates: List of correct duplicates i.e., ground truth) retrieved_duplicate...
bigcode/self-oss-instruct-sc2-concepts
def make_cygpath_function(mounts): """Creates a make function that can be used in place of cygpath. Args: mounts: A list of tuples decribing filesystem mounts. Returns: The body of a function implementing cygpath in make as a string. """ # We're building a bunch of nested patsubst ...
bigcode/self-oss-instruct-sc2-concepts
def get_item_type(code): """Get item type from code.""" item_type = {0: "Zabbix agent", 1: "SNMPv1 agent", 2: "Zabbix trapper", 3: "simple check", 4: "SNMPv2 agent", 5: "Zabbix internal", 6: "SNMPv3 agent", ...
bigcode/self-oss-instruct-sc2-concepts
def sensorsDifferenceSum(sensor_1, sensor_2): """ given two lists contains the reading of two sensors for the same place, give the total difference between there elements """ if len(sensor_1) == 0 or len(sensor_2) == 0: return 0 return abs(sensor_1[0] - sensor_2[0]) + sensorsDifferenceSu...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def message_empty(sysex_data: List[int]) -> bool: """Return whether the sysex data is an empty message packet.""" return len(sysex_data) == 2
bigcode/self-oss-instruct-sc2-concepts
def mask_string(raw_str, right_padding=4) -> str: """Mask a string with a default value of 4.""" return raw_str[-right_padding:].rjust(len(raw_str), '*')
bigcode/self-oss-instruct-sc2-concepts
def _field_set_recursively(resource, field_name, value): """Set a field for a given resource and all of its children. Args: resource (ResourceData): the resource to change. field_name (str): the field to set. value (str): the value of the field to set to. Returns: list. all...
bigcode/self-oss-instruct-sc2-concepts
def to_list(x): """ Return x if it is already a list, or return a list containing x if x is a scalar. """ if isinstance(x, (list, tuple)): return x # Already a list, so just return it. return [x]
bigcode/self-oss-instruct-sc2-concepts
def search_for_ISM(edge_IDs, transcript_dict): """ Given a list of edges in a query transcript, determine whether it is an incomplete splice match (ISM) of any transcript in the dict. Will also return FSM matches if they're there""" edges = frozenset(edge_IDs) ISM_matches = ...
bigcode/self-oss-instruct-sc2-concepts
def format_timeout(timeout): """Render server alive interval option.""" format_str = '-o ServerAliveInterval={}'.format return format_str(timeout) if timeout else ''
bigcode/self-oss-instruct-sc2-concepts
def transposed(matrix): """Returns the transpose of the given matrix.""" return [list(r) for r in zip(*matrix)]
bigcode/self-oss-instruct-sc2-concepts
def word_len(word): """Returns the length of word not counting spaces >>> word_len("a la carte") 8 >>> word_len("hello") 5 >>> word_len('') 0 >>> word_len("coup d'etat") 10 """ num = len(word) for i in range(len(word)): if word[i] == " ": num = num-1 ...
bigcode/self-oss-instruct-sc2-concepts
def pick_n_equispaced(l, n): """Picks out n points out of list, at roughly equal intervals.""" assert len(l) >= n r = (len(l) - n)/float(n) result = [] pos = r while pos < len(l): result.append(l[int(pos)]) pos += 1+r return result
bigcode/self-oss-instruct-sc2-concepts
async def get_chains(self, symbol, info='expiration_dates'): """Returns the chain information of an option. :param symbol: The ticker of the stock. :type symbol: str :param info: Will data_filter the results to get a specific value. :type info: Optional[str] :returns: Returns a dictionary of ke...
bigcode/self-oss-instruct-sc2-concepts
def message_warning(msg, *a, **kwargs): """Ignore everything except the message.""" return str(msg) + '\n'
bigcode/self-oss-instruct-sc2-concepts
def regrid_get_operator_method(operator, method): """Return the regridding method of a regridding operator. :Parameters: operator: `RegridOperator` The regridding operator. method: `str` or `None` A regridding method. If `None` then ignored. If a `str` then...
bigcode/self-oss-instruct-sc2-concepts
def is_affiliation(item: str) -> bool: """Return true if a string contains an affiliation.""" return item.startswith('(')
bigcode/self-oss-instruct-sc2-concepts
def RelationshipLengthProperty(relationship_name): """Return a property representing number of objects in relationship.""" def getter(self): relationship = getattr(self._object, relationship_name) try: return relationship.countObjects() except Exception: return le...
bigcode/self-oss-instruct-sc2-concepts
def pad_to(x, k=8): """Pad int value up to divisor of k. Examples: >>> pad_to(31, 8) 32 """ return x + (x % k > 0) * (k - x % k)
bigcode/self-oss-instruct-sc2-concepts
import types def argument(name, type): """ Set the type of a command argument at runtime. This is useful for more specific types such as mitmproxy.types.Choice, which we cannot annotate directly as mypy does not like that. """ def decorator(f: types.FunctionType) -> types.FunctionT...
bigcode/self-oss-instruct-sc2-concepts
from typing import List import bisect def get_bin(pred_prob: float, bins: List[float]) -> int: """Get the index of the bin that pred_prob belongs in.""" assert 0.0 <= pred_prob <= 1.0 assert bins[-1] == 1.0 return bisect.bisect_left(bins, pred_prob)
bigcode/self-oss-instruct-sc2-concepts
import sympy def det(x): """ Symbolic determinant :param m: matrix :type x: ndarray with symbolic elements :return: determinant :rtype: ndarray with symbolic elements .. runblock:: pycon >>> from spatialmath.base.symbolic import * >>> from spatialmath.base import rot2 ...
bigcode/self-oss-instruct-sc2-concepts
def transpose2(lists, defval=0): """ Transpose a list of list. defval is used instead of None for uneven lengthed lists. """ if not lists: return [] return map(lambda *row: [elem or defval for elem in row], *lists)
bigcode/self-oss-instruct-sc2-concepts