seed
stringlengths
1
14k
source
stringclasses
2 values
import csv def read_symbols(symbol_file='symbols.csv'): """ Read symbols. Parameters ---------- symbol_file : str Path to a CSV (with ',' as delimiter) which contains one symbol label in the second colum Returns ------- list Of symbol labels """ with o...
bigcode/self-oss-instruct-sc2-concepts
def extract_inventions_dreamcoder(dc_json): """ extract the learned inventions from a dreamcoder json file and sort by length """ return sorted([prod["expression"] for prod in dc_json["DSL"]["productions"] if prod["expression"].startswith("#")], key=len)
bigcode/self-oss-instruct-sc2-concepts
def load_cluster_labels(clusterpath, one_indexed=True): """ one_indexed: if true, assume cluster index starts at 1 (e.g. as in 2018_scMCA data) """ cluster_labels = {} if one_indexed: dec = 1 else: dec = 0 # expected format of csv file is "cluster number, name" with open(...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict from typing import Any def exact_str_match_fn(targets: List[str], responses: List[str]) -> Dict[str, Any]: """Exact match between targets and responses.""" # aitor: might want to use these metrics after removing irrelevant words. # they do something like thi...
bigcode/self-oss-instruct-sc2-concepts
def parse_coverage_list(coverage_list): """ Given a coverage_list (structured as a list of coverage statements (which are strings) that define the poset, parses them into a dictionary. Parameters ---------- coverage_list : `list` list of coverage statements defining a poset, e.g.: ...
bigcode/self-oss-instruct-sc2-concepts
def author_name(author): """ Rewrite author name in a specific form: Take the last word that is present in 'author'. Set that as last name. If a different word is present, take the first letter. If not, set a default of X. e.g. the name 'Albert de Vries' gets turned into 'A. Vries'; ...
bigcode/self-oss-instruct-sc2-concepts
def update_pos(pos1,pos2): """ Get the coordinate of the bounding box containing two parts :param pos1: Coordinate of the first part. :param pos2: Coordinate of the second part. :return: Coordinate of the bounding box containing the two parts """ x1 = min(pos1[0],pos2[0]) y1 = min(pos1[1...
bigcode/self-oss-instruct-sc2-concepts
def FOG(conf, value): """Get FOG Color code from config""" if value == 1: return conf.get_color("colors", "color_fog1") else: return conf.get_color("colors", "color_fog2")
bigcode/self-oss-instruct-sc2-concepts
def is_id(argument: str) -> bool: """ Determines whether the given argument is a valid id (i.e. an integer). :param argument: the string argument to evaluate :return: true if the argument can be evaluated as an interger, false otherwise """ try: int(argument) except ValueError: ...
bigcode/self-oss-instruct-sc2-concepts
def author_clean(author): """ Clean an author and return the formatted string """ replace = [".", ";", " ", ",", "_", "-"] author_split = author.strip().split(",") clean_author = "" if len(author_split) >= 2: last_name = author_split[0] first_name = author_split[1] for rep in...
bigcode/self-oss-instruct-sc2-concepts
def fill_array(x,x_val): """ fill_array(x,x_val) If x_val[i] != None then x[i] == x_val[i]. """ constraints = [] for i in range(len(x)): if x_val[i] != None: constraints += [x[i] == x_val[i]] return constraints
bigcode/self-oss-instruct-sc2-concepts
import re def replace_version(line, new_version, regex): """ COPIED FROM TITO Attempts to replace common setup.py version formats in the given line, and return the modified line. If no version is present the line is returned as is. Looking for things like version="x.y.z" with configurable ca...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def fibonacci(num: int, *, ret_text: bool = False) -> Union[list, str]: """ Generates the sequence of Fibonacci >>> from snakypy import helpers >>> helpers.calcs.fibonacci(50) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] >>> helpers.calcs.fibonacci(50, ret_te...
bigcode/self-oss-instruct-sc2-concepts
def hex_uid(uid_raw): """ Convert key to Hex string :param uid_raw: Input UID :return: Hex string """ uid_list = list(uid_raw) uid_hex_str = "" for uid_item in uid_list: uid_hex = format(uid_item, 'x') if len(uid_hex) == 1: uid_hex = "0" + uid_hex uid_...
bigcode/self-oss-instruct-sc2-concepts
import re def search_prs(log): """ Search lines of text for PR numbers """ # Find all matches using regex iterator, using the PR # as the group match resultlist = [str(m.group(1)) for m in re.finditer(r"erge pull request #(\d+)", log)] return sorted(resultlist)
bigcode/self-oss-instruct-sc2-concepts
import csv def load_inputs(inputs_file): """Load Inputs for AutoSpider.""" with open(inputs_file, 'Ur') as f: data = list(tuple(rec) for rec in csv.reader(f, delimiter=',')) return data
bigcode/self-oss-instruct-sc2-concepts
def _quote(text): """ Quote the given string so ``_split_quoted`` will not split it up. :param str text: The string to quote: :return: A str string representing ``text`` as protected from splitting. """ return ( '"' + text.replace("\\", "\\\\").replace('"', '\\"') + ...
bigcode/self-oss-instruct-sc2-concepts
def mergeTwoListsIntoOne(list1, list2): """ Function that takes two lists and assembles them into one list such that each entry of the final list is a list containing the two corresponding entries of the two input lists """ if len(list1) != len(list2): raise ValueError("Input lists not o...
bigcode/self-oss-instruct-sc2-concepts
def int_to_str(num, max_num=0): """ Converts a number to a string. Will add left padding based on the max value to ensure numbers align well. """ if num is None: num_str = 'n/a' else: num_str = '{:,}'.format(num) max_str = '{:,}'.format(int(max_num)) return num_str.rjust(...
bigcode/self-oss-instruct-sc2-concepts
def nested_haskey(x, keys): """ For a nested dictionary 'x' and list of keys, checks if all keys exist in the nested key path. """ if len(keys) == 1: return (keys[0] in x) if keys[0] in x: return nested_haskey( x[keys[0]], keys[1:]) else: return False
bigcode/self-oss-instruct-sc2-concepts
import pathlib import pkg_resources def get_path(resource_name): """ Returns a path to a resource WARNING: existence of file is not guaranteed. Use resources.exists WARNING: resource files are supposed to be used as read-only! """ resource_path = pathlib.Path( pkg_resources.resource_filen...
bigcode/self-oss-instruct-sc2-concepts
def parse_flag(value): """ Convert string to boolean (True or false) :param value: string value :return: True if the value is equal to "true" (case insensitive), otherwise False """ return value.lower() == "true"
bigcode/self-oss-instruct-sc2-concepts
def capacity_cost_rule(mod, g, p): """ The capacity cost for new-build generators in a given period is the capacity-build of a particular vintage times the annualized cost for that vintage summed over all vintages operational in the period. """ return sum( mod.GenNewBin_Build[g, v] ...
bigcode/self-oss-instruct-sc2-concepts
def nillable_dict(func): """Decorator that retuns empty dictionary if input is None""" def wrapper(cls, element): if element is None: return {} else: return func(cls, element) return wrapper
bigcode/self-oss-instruct-sc2-concepts
def get_reqs(path): """Parse a pip requirements file. :param str path: The path to the requirements file :returns list: A list of package strings """ reqs = [] with open(path) as req_file: for line in req_file: # Remove any comments line = line.split("#", 1)[0]....
bigcode/self-oss-instruct-sc2-concepts
def order_by_length(*items): """Orders items by length, breaking ties alphabetically.""" sorted_items = sorted(items, key=lambda item: (len(str(item)), str(item))) return ' '.join(sorted_items)
bigcode/self-oss-instruct-sc2-concepts
import torch def prepare_batch(batch): """This is the collate function. The mass spectra must be padded so that they fit nicely as a tensor. However, the padded elements are ignored during the subsequent steps. Parameters ---------- batch : tuple of tuple of torch.tensor A batch of d...
bigcode/self-oss-instruct-sc2-concepts
def task_type_args_are_valid(instance): """Determines whether a task type's argument fields are valid. The argument fields are valid if the argument keys in the required_arguments_default_values field are a subset of its required arguments. Arg: instance: A task type instance. Returns:...
bigcode/self-oss-instruct-sc2-concepts
def sign_split(M): """Given a matrix M, return two matrices. The first contains the positive entries of M; the second contains the negative entries of M, multiplied by -1. """ M_plus = M*(M>0).astype(int) M_minus = -M*(M<0).astype(int) return M_plus, M_minus
bigcode/self-oss-instruct-sc2-concepts
import re def get_usfm3_word_links(usfm3_line): """ Retrieves the tW links from a usfm3 word :param usfm3_line: :return: """ links = [] if usfm3_line and re.match(r'.*x-tw=', usfm3_line): links = re.findall(r'x-tw="([^"]*)"', usfm3_line, flags=re.IGNORECASE | re.UNICODE) return...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def to_datetime_from_date(value): """ converts the input date to it's equivalent python datetime. the time info will be set to `00:00:00`. :param date value: date value to be converted. :rtype: datetime """ return datetime(year=value.year, month=value.mont...
bigcode/self-oss-instruct-sc2-concepts
def jaccard_similarity(list1, list2): """ Calculate Jaccard Similarity between two sets """ intersection = len(list(set(list1).intersection((set(list2))))) union = len(list1) + len(list2) - intersection return float(intersection) / union
bigcode/self-oss-instruct-sc2-concepts
def render_menu_children(request, parent, items, menu_tag): """ Recursively render menu children. """ childs = [] output = [] for menu in items: if menu['parent_id'] == parent['id']: childs.append(menu) if childs: output.append('<%s class="ul_sublevel">' % menu_...
bigcode/self-oss-instruct-sc2-concepts
def toAdjacencyList(molecule, label='', pattern=False, removeH=False): """ Convert the `molecule` object to an adjacency list. `pattern` specifies whether the graph object is a complete molecule (if ``False``) or a substructure pattern (if ``True``). The `label` parameter is an optional string to pu...
bigcode/self-oss-instruct-sc2-concepts
def defaultBBoxDeltaFun(w): """ When we reduce the width or height of a bounding box, we use this function to compute the deltaX or deltaY , which is applied on x1 and x2 or y1 and y2 For instance, for horizontal axis x1 = x1 + deltaFun(abs(x1-x2)) x2 = x2 + deltaFun(abs(x1-x2)) ...
bigcode/self-oss-instruct-sc2-concepts
def _GetLineNumberOfSubstring(content, substring): """ Return the line number of |substring| in |content|.""" index = content.index(substring) return content[:index].count('\n') + 1
bigcode/self-oss-instruct-sc2-concepts
def is_success_type(qtype): """ Interprets a qtype (BINARY, UNKNOWN, etc.) as a "success" or "failure" """ return qtype[0] == 's'
bigcode/self-oss-instruct-sc2-concepts
import re def string_to_list(option): """Convert string to list. List may be enclosed in [], {}, (), or not enclosed. List entries must be comma delimited. Args: option (str) String to convert. Returns: (list) List of strings. """ PATTERN = r"[\{\[\(](.*)[\}\]\)]"...
bigcode/self-oss-instruct-sc2-concepts
def add_percent_sign(n): """Add a % sign to the end of x, unless x is empty""" if not isinstance(n, str): n = str(n) if len(n) > 0: return n + "%" return n
bigcode/self-oss-instruct-sc2-concepts
def _int_or_str(c): """Return parameter as type integer, if possible otherwise as type string """ try: return int(c) except ValueError: return c
bigcode/self-oss-instruct-sc2-concepts
import random def seeds(count): """Return a list of random values of the specificed length.""" return [random.randint(0, 1 << 32 - 1) for i in range(count)]
bigcode/self-oss-instruct-sc2-concepts
import math def ent(x): """ Entropy [bits] given a vector of log probabilities """ x = [ math.exp(-val) for val in x ] logs = [ math.log(val, 2) for val in x ] prods = [ a * b for a,b in zip(x, logs) ] return - sum(prods)
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def is_package_file(f: Path, sap_code: str, name_pattern: str) -> bool: """Determine if the file is the right application JSON file :param f (Path): json file path :param sap_code (str): Adobe SAP code for product being processed :param name_pattern (str): json filename patter...
bigcode/self-oss-instruct-sc2-concepts
def _str2float(s): """Cast string to float if it is not None. Otherwise return None. Args: s (str): String to convert or None. Returns: str or NoneType: The converted string or None. """ return float(s) if s is not None else None
bigcode/self-oss-instruct-sc2-concepts
def round_scores(df): """ Some labels were interpolated by the data provider, so they must be rounded to the nearest integer to be used as a label. """ return df.score.round()
bigcode/self-oss-instruct-sc2-concepts
def lint_codeblock(styleguide, tmp_path): """Fixture which runs the styleguide's `lint` subcommand when executed.""" def run_linter( codeblock, *styleguide_args, # We ignore unused import warnings as most of the codeblocks which produce this warning # are just demonstrations of ...
bigcode/self-oss-instruct-sc2-concepts
import torch def cat_batch(*args): """ Concatenates batches of tensors :return: concatenated tensor :rtype: torch.Tensor """ return torch.cat(args, dim=0)
bigcode/self-oss-instruct-sc2-concepts
import hashlib def _rehash(value, salt2=""): """Rehash a value.""" for idx in range(1, 20): value = hashlib.sha256(f"{value}{idx}{salt2}".encode()).hexdigest() return value
bigcode/self-oss-instruct-sc2-concepts
def format_variable_assignment(step): """Format an assignment statement.""" asn = step['detail'] lhs, rhs, binary = asn['lhs'], asn['rhs-value'], asn['rhs-binary'] binary = '({})'.format(binary) if binary else '' return '{} = {} {}'.format(lhs, rhs, binary)
bigcode/self-oss-instruct-sc2-concepts
def create_internal_cookie(name, value, expires): """Create individual cookie to be stored inside Target cookie""" return { "name": name, "value": value, "expires": expires }
bigcode/self-oss-instruct-sc2-concepts
def inflate_lvol_bdev(client, name): """Inflate a logical volume. Args: name: name of logical volume to inflate """ params = { 'name': name, } return client.call('inflate_lvol_bdev', params)
bigcode/self-oss-instruct-sc2-concepts
import requests import json def get_token_data(oauth_service, token): """ Gets the OAuth2 user attributes using the supplied token :param OAuthSSHCertSigningService oauth_service: an OAuthSSHCertSigningService object :param basestring token: an OAuth2 token :return: a json object of user a...
bigcode/self-oss-instruct-sc2-concepts
def add_sort_list( l1: list, l2: list, ) -> list: """Add two lists and sort them Parameters ---------- l1 : list The first list to be added l2 : list The second list to be added Returns ------- list The added and sorted list """ # Add ...
bigcode/self-oss-instruct-sc2-concepts
def trapezoidal(f, a, b, n=10000): """trapez method for numerical integration""" s = 0.0 h = (b - a) / n for i in range(0, n): s += f(a + i * h) return h * (s + 0.5 * (f(a) + f(b)))
bigcode/self-oss-instruct-sc2-concepts
import optparse def parse_args(argvish): """ Build OptionParser and evaluate command line arguments. """ parser = optparse.OptionParser() parser.add_option('-r', '--region', type="int", help="Region") parser.add_option('-z', '--zone', type="int", hel...
bigcode/self-oss-instruct-sc2-concepts
import json def jsonify(*args, **kwargs): """ Helper based on flask jsonify and helsp convert lists and dicts into valid reponses. """ indent = None separators = (',', ':') headers = {'Content-Type': 'application/json'} headers.update(kwargs.get('headers', {})) if args and kwargs: ...
bigcode/self-oss-instruct-sc2-concepts
def adjust_asymp_with_chronic(asymp_column, chronic_column): """ Remove asymptomatic flag for people with chronic disease Parameters ---------- asymp_column : A boolean array storing people with asymptomatic infection chronic_column : A boolean array storing people with chronic diseas...
bigcode/self-oss-instruct-sc2-concepts
def modulus(angka1: float, angka2: float) -> float: """ hasil dari modulus antara angka1 dan angka2 >>> modulus(3.0, 2.0) 1.0 """ return angka1 % angka2
bigcode/self-oss-instruct-sc2-concepts
def flip_dict_of_lists(dict_of_lists, dict_type=None, key_func=lambda k: k): """ Returns a "flipped" dictionary of lists from the given dictionnary of lists. What I mean by "flipped" is this: >>> d = {'a': [1, 2], 'b': [3, 1], 'c': [2]} >>> flip_dict_of_lists(d) {1: ['a', 'b'], 2: ['a', 'c'], ...
bigcode/self-oss-instruct-sc2-concepts
def wrap_text (text, font, base_width): """Wraps given text into multiple lines to fit into the given width Breaks the given text into a list of lines, so that the text when rendered with font won't horizontally overflow beyond base_width. If possible, lines are broken after complete words. Args: ...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def HashFile(file_path): """Calculate the sha256 hash of a file. Args: file_path: (str) path to the file. Returns: [str]: The sha256 hash of the file. """ sha256 = hashlib.sha256() with open(file_path, 'rb') as f: for b in iter(lambda: f.read(2048), b''): sha256.update(b...
bigcode/self-oss-instruct-sc2-concepts
import re def do_slugify(inp): """Convert an arbitrary string into a url-safe slug.""" inp = re.sub(r'[^\w\s-]+', '', inp) return re.sub(r'\s+', '-', inp).lower()
bigcode/self-oss-instruct-sc2-concepts
def find_count(substring, string): """finds the number of occurences of substring in string""" counter = 0 index = string.find(substring) while index >= 0: counter += 1 index = string.find(substring, index + 1) return counter
bigcode/self-oss-instruct-sc2-concepts
def HSVtoRGB(h, s, v): """ Convert Hue-Saturation-Value into Red-Green-Blue equivalent. Parameters: h - Hue between [0.0, 360.0) degrees. red(0.0) to violet(360.0-). s - Staturation [0.0, 1.0] v - Value [0.0, 1.0] Return Value: (r, g, b) 3-tuple with each color betw...
bigcode/self-oss-instruct-sc2-concepts
import torch def squared_distance(x1, x2=None): """ Given points x1 [n1 x d1] and x2 [n2 x d2], return a [n1 x n2] matrix with the pairwise squared distances between the points. Entry (i, j) is sum_{j=1}^d (x_1[i, j] - x_2[i, j]) ^ 2 """ if x2 is None: return squared_distance(x1, x1) ...
bigcode/self-oss-instruct-sc2-concepts
import math def straightness_imperfection(z, length, delta_global, oos_axis, **kwargs): """ Returns the out-of-straightness imperfection of the node. :param float z: z coordinate of node :param float length: total length of the component :param float delta_global: maximum amplitude of the out-of-stra...
bigcode/self-oss-instruct-sc2-concepts
def filter_hsv_to_h(hsv, output_type="int", display_np_info=True): """ Obtain hue values from HSV NumPy array as a 1-dimensional array. If output as an int array, the original float values are multiplied by 360 for their degree equivalents for simplicity. For more information, see https://en.wikipedia.o...
bigcode/self-oss-instruct-sc2-concepts
def get_viewstate_value(page): """ Find for content of the viewState param in source code :param page: The code of the page for search in it :return: The content of the viewstate param or None """ page = str(page).replace("\\n", "\n") full_param = "name=\"javax.faces.ViewState\"" for i ...
bigcode/self-oss-instruct-sc2-concepts
def count(seq): """Count the number of items in sequence that are interpreted as true.""" return sum(map(bool, seq))
bigcode/self-oss-instruct-sc2-concepts
def convert_inf(x): """ The tqdm doesn't support inf values. We have to convert it to None. """ if x == float('inf'): return None return x
bigcode/self-oss-instruct-sc2-concepts
def number_to_digits(num): """Return sorted list of digits in number.""" return sorted(int(ch) for ch in str(num))
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup def parseCategoryHTML(HTML_Source): """ カテゴリページを解析し、ランキングページのURLを取得する。 Parameters ---------- HTML_Source : str カテゴリページHTMLソース。 Returns ------- ranking_pg_list : str[] ランキングページリスト。 """ soup = BeautifulSoup(HTML_Source, 'html.parse...
bigcode/self-oss-instruct-sc2-concepts
def strescape(txt): """ Convert bytes or text to a c-style escaped string. """ if type(txt) == bytes: txt = txt.decode("cp1251") txt = txt.replace("\\", "\\\\") txt = txt.replace("\n", "\\n") txt = txt.replace("\r", "\\r") txt = txt.replace("\t", "\\t") txt = txt.replace('"',...
bigcode/self-oss-instruct-sc2-concepts
def get_counts_and_averages(ID_and_ratings_tuple): """Given a tuple (bookID, ratings_iterable) returns (bookID, (ratings_count, ratings_avg)) """ nratings = len(ID_and_ratings_tuple[1]) return ID_and_ratings_tuple[0], (nratings, float(sum(x for x in ID_and_ratings_tuple[1]))/nratings)
bigcode/self-oss-instruct-sc2-concepts
def get_edge_label_dict(graph, attr_type="label"): """ Return a dict with edge tuple as key and edge attr/label as value. If both are required, the label will be the first entry in the list, and the remaining attributes will come after""" d = {} if len(graph.es.attributes()) > 0: if len(att...
bigcode/self-oss-instruct-sc2-concepts
def get_parameters(function, **kwargs): """ Return a list of parameters from a SSM function, like describe_parameters or get_parameters_by_path. """ next_token = "" response = function(**kwargs) parameter_list = response["Parameters"] while "NextToken" in response: next_token = r...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def _decode(str_like: Union[str, bytes]) -> str: """Convert to string from bytes/str/... """ if isinstance(str_like, bytes): return str(str_like, 'utf-8') return str(str_like)
bigcode/self-oss-instruct-sc2-concepts
def format_time(start, end): """ Format length of time between start and end. :param start: the start time :param end: the end time :return: a formatted string of hours, minutes, and seconds """ hours, rem = divmod(end-start, 3600) minutes, seconds = divmod(rem, 60) return "{:0>2}:{...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _ternary_search(array: List[int], value, low: int, high: int) -> int: """ The implementation detail of the recursive implementation of ternary search. :param array: is the array to search. :param value: is the value to search for. :param low: is the lower bound of the p...
bigcode/self-oss-instruct-sc2-concepts
def encode_dict_in_bash(dictionary: dict) -> str: """ Make dict into a series of key value pairs readable on command line. """ pairs = [] for key, value in dictionary.items(): pairs.append(f"{key}={value}") return " ".join(pairs)
bigcode/self-oss-instruct-sc2-concepts
def create_address(house_number, post_code): """ Creates immutable address data structure :param house_number: user's house number (string) :param post_code: user's post code (string) :return: (tuple) """ return (house_number, post_code)
bigcode/self-oss-instruct-sc2-concepts
def chunks(items, size): """ Split list into chunks of the given size. Original order is preserved. Example: > chunks([1,2,3,4,5,6,7,8,9], 2) [[1, 2], [3, 4], [5, 6], [7, 8], [9]] """ return [items[i:i+size] for i in range(0, len(items), size)]
bigcode/self-oss-instruct-sc2-concepts
def strpar(cfg, section, key): """String representation of a section/key combination""" return "[{}] {} = {}".format(section, key, cfg[section][key])
bigcode/self-oss-instruct-sc2-concepts
def add_commas(n): """ Receives integer n, returns string representation of n with commas in thousands place. I'm sure there's easier ways of doing this... but meh. """ strn = str(n) lenn = len(strn) i = 0 result = '' while i < lenn: if (lenn - i) % 3 == 0 and i != 0:...
bigcode/self-oss-instruct-sc2-concepts
def split_args(args): """ Split a list of argument strings into a dictionary where each key is an argument name. An argument looks like ``crop``, ``crop="some option"`` or ``crop=my_var``. Arguments which provide no value get a value of ``True``. """ args_dict = {} for arg in args: ...
bigcode/self-oss-instruct-sc2-concepts
def phi_psi_omega_to_abego(phi: float, psi: float, omega: float) -> str: """ :param: phi: The phi angle. :param: psi: The psi angle. :param: omega: The omega angle. :return: The abego string. From Buwei https://wiki.ipd.uw.edu/protocols/dry_lab/rosetta/scaffold_generation_with_piecewise_blue...
bigcode/self-oss-instruct-sc2-concepts
def disqus_id_for(obj): """ Returns a unique identifier for the object to be used in DISQUS JavaScript. """ return "%s-%s" % (obj._meta.object_name, obj.id)
bigcode/self-oss-instruct-sc2-concepts
import codecs def complete_vocabulary(filename, initial_words, wordlength, vocsize, encoding="utf-8"): """ Reads words of length <wordlength>, from <filename>, until the number_of_words_read+len(initial_words)=vocsize. Returns a dictionary of words and their frequency. :param filename: text file, without...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import Optional import re def get_error_code(error_field: Union[str, None]) -> Optional[int]: """Get the error code part of the `error\ <https://docs.cometd.org/current/reference/#_code_error_code>`_, message \ field :param error_field: `Error\ <https://docs.c...
bigcode/self-oss-instruct-sc2-concepts
def hill_equation(val, diss_cf, hill_cf): """ Hill equation :param val: input value :param diss_cf: dissociation coefficient :param hill_cf: Hill coefficient :return: Hill equation for input *val* """ if val == 0: return 0 else: return 1 / (1 + (diss_cf / val) ** hill...
bigcode/self-oss-instruct-sc2-concepts
def get_words_prob(test_words_list:list, normal_words_freq:dict, spam_words_freq:dict, normal_file_number:int, spam_file_number:int, max_prob_num:int): """ Calculate the probability of spam for every words, p(s|wi) Args: test_words_list: the words list to test normal_words...
bigcode/self-oss-instruct-sc2-concepts
def list_materials(client, file_=None, material=None): """List materials on a part. Args: client (obj): creopyson Client. `file_` (str, optional): File name. Defaults is currently active model. material (str, optional): Material name pattern. ...
bigcode/self-oss-instruct-sc2-concepts
def heading(title, fgcol, bgcol,extras='',add='&nbsp;<br>'): """Format a page heading.""" return ''' <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading"> <tr bgcolor="%s"> <td valign=bottom>%s <font color="%s" face="helvetica, arial">&nbsp;<br>%s</font></td ><td a...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable def contains(substring: str, false_prob: float = 0.0, true_prob: float = 1.0) -> Callable: """Generate a function that checks whether a substring is present.""" def call(value: object) -> float: if not isinstance(value, str): return 0.0 retu...
bigcode/self-oss-instruct-sc2-concepts
import requests def perform_query(query): """Performs a SPARQL query to the wikidata endpoint Args: query: A string containing a functional sparql query Returns: A json with the response content. """ endpoint_url = "https://query.wikidata.org/sparql" try: response =...
bigcode/self-oss-instruct-sc2-concepts
import six def first_where(pred, iterable, default=None): """Returns the first element in an iterable that meets the given predicate. :param default: is the default value to use if the predicate matches none of the elements. """ return next(six.moves.filter(pred, iterable), default)
bigcode/self-oss-instruct-sc2-concepts
def size_mb(size): """ Helper function when creating database :param size: interger (size in Mb) :return: integer (bytes) """ return int(1024*1024*size)
bigcode/self-oss-instruct-sc2-concepts
def flatten(lists): """ Return a new (shallow) flattened list. :param lists: list: a list of lists :return list """ return [item for sublist in lists for item in sublist]
bigcode/self-oss-instruct-sc2-concepts
def createExportString(clip, delimiter=" ", badValue="nan"): """Create a line of text for the exporter Inputs: ------------ clip A clipboard object Optional Inputs: ----------------- delimiter: (string) The character, or set of characters to separate elements ...
bigcode/self-oss-instruct-sc2-concepts
def air_flux(air_flow: float, co2_source: float, co2_target: float) -> float: """ Equation 8.46 Args: co2_source, co2_target: CO2-concentration at location (mg m^-3) air_flow: the air flux from location 1 to location 2 (m^3 m^-2 s^-1) return: CO2 flux accompanying an air flux from locat...
bigcode/self-oss-instruct-sc2-concepts