seed
stringlengths
1
14k
source
stringclasses
2 values
import socket def __try_op__(op_name, op, retries, *args): """ A helper function to retry an operation that timed out on a socket. After the retries are expired a socket.timeout is raised. Parameters ---------- op_name : str The operations name op : Callable The operation ...
bigcode/self-oss-instruct-sc2-concepts
import time def delay(ticks: int) -> int: """pause the program for an amount of time Will pause for a given number of nanoseconds. This function will use the processor (rather than sleeping) in order to make the delay more accurate than nygame.time.wait(). Parameters ---------- ticks ...
bigcode/self-oss-instruct-sc2-concepts
def fib(n): """This function returns the nth Fibonacci number.""" i = 0 j = 1 n = n - 1 while n >= 0: i, j = j, i + j n = n - 1 return i
bigcode/self-oss-instruct-sc2-concepts
def name(data): """ Get the assigned name of the entry. """ return data["marker_name"]
bigcode/self-oss-instruct-sc2-concepts
import json def dumps_json(value): """ dumps json value to indented string Args: value (dict): raw json data Returns: str: indented json dump string """ return json.dumps(value, indent=2, ensure_ascii=False)
bigcode/self-oss-instruct-sc2-concepts
def fn_example(values): """ function / method with built-in unit test example; this example computes the arithmetic mean of a list of numbers. Args: values: list of integers Returns: integer Examples: >>> print(fn_example([20, 30, 70])) 40.0 """ return sum(values) / len(values)
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import Hashable from typing import List def _unique_order_preserving(iterable: Iterable[Hashable]) -> List[Hashable]: """Remove items from an iterable while preserving the order.""" seen = set() return [i for i in iterable if i not in seen and not seen.add(i)]
bigcode/self-oss-instruct-sc2-concepts
def _tests_in_suite(suite_name, tests): """Check if the suite includes tests. :param suite_name: Name of the suite to be checked. :param tests: Set of tests :type suite_name: str :type tests: pandas.Series :returns: True if the suite includes tests. :rtype: bool """ for key in test...
bigcode/self-oss-instruct-sc2-concepts
import re def fixFlagsQuoting(text): """Replaces e.g. /DFOO with /D "FOO" and /DFOO=X with /D FOO=X.""" return re.sub(r'\/([DIid]) ([^ \"=]+)([ $])', r'/\1 "\2"\3', re.sub(r'\/([DIid]) ([^ \"=]+)=([^ \"]*)([ $])', r'/\1 \2=\3\4', text))
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import Dict def create_field_list_query(field_type: Optional[str] = None, field_documentation: bool = True) -> Dict: """Create a FieldListRequest dictionary request. Args: field_type: One of {'All', 'Static', 'RealTime'} field_documentation: Return fiel...
bigcode/self-oss-instruct-sc2-concepts
def parse_videos(video): """ Parse data from the video JSON structure Parameters ---------- video : JSON object of strings The video search result requested from YouTube API v3 Returns ---------- video_dict : dictionary of strings The dictionary contianing video titl...
bigcode/self-oss-instruct-sc2-concepts
def create_log_line(log_msg): """ Create a line for the log files from a LogMessage """ # determine log line contents tstamp = round(log_msg.tstamp.timestamp()) direction = "IN" sender = log_msg.sender if log_msg.own: direction = "OUT" sender = "you" msg = log_msg.ms...
bigcode/self-oss-instruct-sc2-concepts
def _filter(regex, expr): """ Build an `filter(<regex>, <expr>)` type query expression. `regex` is a regex matched on the rule names from `expr` `expr` is a query expression of any supported type. """ return "filter('{}', {})".format(regex, expr)
bigcode/self-oss-instruct-sc2-concepts
def getAuthorAndName(ctx): """ Takes the context variable from the calling function and returns the author object and the author display name, formatted. @param ctx the context passed to the calling function @return author the author object @return authorName the display name of the author "...
bigcode/self-oss-instruct-sc2-concepts
def format_percentage(number): """ Formats a number into a percentage string :param number: a number assumed to be between 0 and 1 :return: str """ return '{}%'.format(round(number * 100))
bigcode/self-oss-instruct-sc2-concepts
def is_numeric(s): """ It's a useful function for checking if a data is a numeric. This function could identify any kinds of numeric: e.g. '0.1', '10', '-2.', 2.5, etc Parameters ---------- s : int, float or string. The input could be any kind of single value except the scalable ...
bigcode/self-oss-instruct-sc2-concepts
def acs(concept, paragraph, model, min_length, stop_words=[]): """ :param concept: str, the concept word for the concept :param paragraph: list, a list of the tokens in the paragraph :param model: gensim.models.Word2Vec, model containing word vectors :return: float, the distance between the concept ...
bigcode/self-oss-instruct-sc2-concepts
import re def get_tab_info(root): """ Returns the prefix, separator, and max index for a set of jQueryUI tabs """ hrefs = [y.attrib['href'] for y in [x.find('a') for x in root.find('ul').findall('li')] ] splits = [r.groups() for r in [re.match('#(.*)([-_...
bigcode/self-oss-instruct-sc2-concepts
import json def read_json_file(path): """ Reads and return the data from the json file at the given path. Parameters: path (str): Path to read Returns: dict,list: The read json as dict/list. """ with open(path, 'r', encoding='utf-8') as f: data = json.load(f) re...
bigcode/self-oss-instruct-sc2-concepts
def split_with_square_brackets(input_str): """ Split a string using "," as delimiter while maintaining continuity within "[" and "]" Args: input_str: Input string Returns: substrings: List of substrings """ substrings = [] bracket_level = 0 current_substr = [] for ne...
bigcode/self-oss-instruct-sc2-concepts
import string def splitNum(name, digits=string.digits): """ Split a string that ends with a number between the 'body' of the string and its numeric suffix. Both parts are returned as strings. :param name: The string to split. :keyword digits: The set of numeric characters. Default...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def get_nb_tile_from_img(img_shape: Tuple[int, int], tile_size: int) -> int: """ return the number of tile inside an image currently the number of tile are computed without overlaping and by rounding so union of all tiles are smaller than image. Tile are square. Para...
bigcode/self-oss-instruct-sc2-concepts
def get_negation(token): """Get the negation of some token""" sign = True for child in token.children: if child.dep_ == "neg": sign = False break return sign
bigcode/self-oss-instruct-sc2-concepts
def block_num_to_hex(block_num): """Converts a block number to a hex string. This is used for proper index ordering and lookup. Args: block_num: uint64 Returns: A hex-encoded str """ return "{0:#0{1}x}".format(block_num, 18)
bigcode/self-oss-instruct-sc2-concepts
def forward_differences(f, h, x): """ Forward Finite Differences. Approximating the derivative using the Forward Finite Method. Parameters: f : function to be used h : Step size to be used x : Given point Returns: Approximation """ return (f(x + h) - f(x)) / h
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def bool_(buffer: bytes, offset: int = 0) -> Tuple[bool, int]: """ Unpack bool from Starbound save file. :param buffer: Starbound save file :param offset: position in Starbound save file :return: bool, new offset """ return bool(buffer[offset]), offset + 1
bigcode/self-oss-instruct-sc2-concepts
def get_job_main_info(job): """ Return a dictionary with the pieces of information that will be presented on the terminal. :param job: A Job object provided by ScrapingHub :return: A dictionary """ info = job.info main_info = { 'id': job.id, 'spider': info.get('spider'), ...
bigcode/self-oss-instruct-sc2-concepts
import json def user_io_loop(settings: dict): """ This function is run on the main process as it interacts with the user. It asks for some command and it executes the proper task if the input was recgonized. Parameters ---------- settings : proxy dict shared dictionary with inform...
bigcode/self-oss-instruct-sc2-concepts
def remove_action(actions, name): """ Find all the occurrences of actions with a given name and return them and remove them from the list :param actions: List of actions :param name: str name to find :returns: List of actions matching the given name """ matching = [action for action in ac...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def get_dag_id(this_dag_name: str, parent_dag_name: Optional[str] = None) -> str: """Generates the name for a DAG, accounting for whether it is a SubDAG. Args: this_dag_name: A name for this individual DAG. parent_dag_name: The name of the parent DAG of this DAG...
bigcode/self-oss-instruct-sc2-concepts
def get_tagstring(refid, tags): """Creates a string from a reference ID and a sequence of tags, for use in report filenames.""" return "_".join([refid] + [t[0] + "." + (t[1] if t[1] else "None") for t in tags])
bigcode/self-oss-instruct-sc2-concepts
import itertools def all_liouville_subspaces(hilbert_subspace): """ Given a Hilbert subspace, return a comma separated list with all included Liouville subspaces Example ------- >>> all_liouville_subspaces('ge') 'gg,ge,eg,ee' """ return ','.join(''.join(s) for s ...
bigcode/self-oss-instruct-sc2-concepts
def normalize_btwn_0_1(list_obj): """ Takes a list and normalizes the values from 0 (smallest) to 1(largest) """ return (list_obj-min(list_obj))/(max(list_obj)-min(list_obj))
bigcode/self-oss-instruct-sc2-concepts
def get_light_positions(rays_i, img_light_pos): """Extracts light positions given scene IDs. Args: rays_i: [R, 1] float tensor. Per-ray image IDs. img_light_pos: [N, 3] float tensor. Per-image light positions. Returns: rays_light_pos: [R, 3] float tensor. Per-ray light positions. ...
bigcode/self-oss-instruct-sc2-concepts
def has_sublist(superlist, sublist): """ Does a list contain another list within it? Not very efficient. If 'eq' is given, this will be used to compare items. """ return any( superlist[i : i + len(sublist)] == sublist for i in range(len(superlist) - len(sublist) + 1) )
bigcode/self-oss-instruct-sc2-concepts
def MSEevaluation(y, predict): """ Evaluate predictions the mean sqaured error :param y: original values :param predict: predicted values :return: the mean squared error of the predicted values """ n = len(y) # number of...
bigcode/self-oss-instruct-sc2-concepts
def get_xml_node_value (root, name): """ return the value from an XML node, if it exists """ node = root.find(name) if node: return node.text else: return None
bigcode/self-oss-instruct-sc2-concepts
def get_first_arg(args, kwargs, name): """Returns named argument assuming it is in first position. Returns None if not found. Args: args (tuple or list): args from function. kwargs (dict): kwargs from function. name (str): argument name """ try: return kwargs[name] ...
bigcode/self-oss-instruct-sc2-concepts
def simpleVoigt(vsh,vsv): """ seis_model.simpleVoigt(vsh,vsv) voigt average of horizontal and vertical shear wave velocities v = 0.5 * (vsh + vsv) Parameters ----------- vsh horizontal shear wave velocity, array or scalar vsv vertical shear wave velocity, array or scalar ...
bigcode/self-oss-instruct-sc2-concepts
import functools def noop_if_no_unpatch(f): """ A helper for PatchTestCase test methods that will no-op the test if the __unpatch_func__ attribute is None """ @functools.wraps(f) def wrapper(self, *args, **kwargs): if getattr(self, '__unpatch_func__') is None: return ...
bigcode/self-oss-instruct-sc2-concepts
def communicator(manager): """Get the ``Communicator`` instance of the currently loaded profile to communicate with RabbitMQ.""" return manager.get_communicator()
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Optional from typing import Dict def package_item(errorHandlerTest: bool, failureHandlerTest: bool, data: str, aggregateList: List) -> Optional[Dict]: """Package item task definition. Args: errorHandlerTest (bool): One can set this flag (i.e. throught the AP...
bigcode/self-oss-instruct-sc2-concepts
import re def get_table_dividers(table): """ Receives a results table Returns a list of divider rows (------) """ return [len(re.findall(r"^-{3,}$", line)) for line in table.split("\n")]
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def timestamp_to_weekday(timestamp): """ Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. """ return int(datetime.fromtimestamp(timestamp / 1000.0).strftime("%w"))
bigcode/self-oss-instruct-sc2-concepts
def get_hook_config(hook_api, module_name, key): """ Get user settings for hooks. Args: module_name: The module/package for which the key setting belong to. key: A key for the config. Returns: The value for the config. ``None`` if not set. The ``get_...
bigcode/self-oss-instruct-sc2-concepts
def get_turn_off_descriptions(get_turn_off, initial_state, current_state): """ Get all 'turn off' descriptions from the current state (if any). Parameters ---------- get_turn_off: function Function that gets the color of light which is off. initial_state: nd.array Initial state o...
bigcode/self-oss-instruct-sc2-concepts
import torch def compute_Xty(X_t, y_t, cm_t, csd_t): """ cm: column means of X csd: column SDs of X """ ytX_t = torch.mm(y_t.T, X_t) # scale Xty scaled_Xty_t = ytX_t.T / csd_t.reshape(-1,1) # center Xty centered_scaled_Xty_t = scaled_Xty_t - cm_t.reshape(-1,1)/csd_t.reshape(-1,1) *...
bigcode/self-oss-instruct-sc2-concepts
import logging def get_logger(name): """ Return a logger with the specified name, creating it if necessary. :param name: module name :return: logging.Logger """ logging.basicConfig(level=logging.INFO, format="%(asctime)s:%(levelname)s:%(name)s: %(message)s", ...
bigcode/self-oss-instruct-sc2-concepts
def UseExistingBootDisk(disks): """Returns True if the user has specified an existing boot disk.""" return any(disk.get('boot') == 'yes' for disk in disks)
bigcode/self-oss-instruct-sc2-concepts
import configparser import re def _get_dict_cases(config_file, cases=('LAMMPS', 'GROMACS')): """ Function to return a dictionary with regex patterns for the given cases and a rating of those. Reads in the config_file. Parameters ---------- config_file : str or List[str] File path to t...
bigcode/self-oss-instruct-sc2-concepts
def smiley(message): """ IMPORTANT: You should NOT use loops or list comprehensions for this question. Instead, use lambda functions, any, map, and/or filter. Make a function that converts specific characters to smiley faces. >>> smiley("DSC20:(") 'DSC20:)(:' >>> smiley(":e)k3o(") ...
bigcode/self-oss-instruct-sc2-concepts
import calendar def get_last_friday_of_month(year, month): """Return the date of the last Friday in the month as an int.""" # calendar_for_month is a 2D list of days of the month, grouped by week. # For example, December 2018 looks like this: # [[ 0, 0, 0, 0, 0, 1, 2], # [ 3, 4, 5, 6, 7...
bigcode/self-oss-instruct-sc2-concepts
def _lerp(A, B, t): """Perform Linear interpolation in 1D""" return A * (1.0 - t) + B * t
bigcode/self-oss-instruct-sc2-concepts
def _interpolate(a, b, fraction): """Returns the point at the given fraction between a and b, where 'fraction' must be between 0 and 1. """ return a + (b - a) * fraction
bigcode/self-oss-instruct-sc2-concepts
def identity(x): """Identity function: useful for avoiding special handling for None.""" return x
bigcode/self-oss-instruct-sc2-concepts
def zenodo_get_children(data, resource_id, is_record): """ Get the children of the requested resource. Only going down one level. Parameters ---------- data : dict The project path data resource_id : str The resource id of the children is_record : bool Is this a Zen...
bigcode/self-oss-instruct-sc2-concepts
def triangle_geometry(triangle): """ Compute the area and circumradius of a triangle. Parameters ---------- triangle : (1x3) array-like The indices of the points which form the triangle. Returns ------- area : float The area of the triangle circum_r : float ...
bigcode/self-oss-instruct-sc2-concepts
def find_col_index_with_name(name, trained_schema): """ finds the index of the column with name 'name' and returns the index :param name: name of the column to look for :type name: str :param trained_schema: :type trained_schema: List(dict) :return: index of the element in trained_schema tha...
bigcode/self-oss-instruct-sc2-concepts
def anagram(word_1: str, word_2: str) -> bool: """Anagram check example :param word_1: {str} :param word_2: {str} :return: {bool} """ word_1 = word_1.lower() word_2 = word_2.lower() return sorted(word_1) == sorted(word_2)
bigcode/self-oss-instruct-sc2-concepts
def get_month(date): """Extract month as form receiving string dd/mm/yyyy or mm/yyyy Args: date (string): Date formate dd/mm/yyyy Returns: mm: string with month. """ num_chars = len(date) if num_chars == 10: return date.split("/")[1] elif num_chars == 7: ret...
bigcode/self-oss-instruct-sc2-concepts
def get_index(l, key, value): """Find the index of an element by key value, for lists of dicts Return: index or -1 """ return next((index for index, d in enumerate(l) if d[key] == value), -1)
bigcode/self-oss-instruct-sc2-concepts
def midi_to_ansi_note(midi_note): """ returns the Ansi Note name for a midi number. ::Examples:: >>> midi_to_ansi_note(21) 'A0' >>> midi_to_ansi_note(102) 'F#7' >>> midi_to_ansi_note(108) 'C8' """ notes = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'] num...
bigcode/self-oss-instruct-sc2-concepts
def intersect(index, keys): """ Utility method to compute the intersection of all the sets in index that correspond to the given keys keys. Args: index, hash for format {key -> set()} keys, list of strings Returns: set, the intersection of all the sets in index that correspond to...
bigcode/self-oss-instruct-sc2-concepts
import base64 def b64_encode(byte_string: bytes) -> str: """Base 64 encode a byte string and return a unicode string.""" b64_bytes = base64.b64encode(byte_string) return b64_bytes.decode("utf-8")
bigcode/self-oss-instruct-sc2-concepts
def func_name(func): """Get a readable name.""" return '.'.join([func.__module__ or "", func.__name__])
bigcode/self-oss-instruct-sc2-concepts
def unique(sorted_list): """Return a new list containing all unique elements in their original order Keyword arguments: sorted_list -- a list of comparable elements in which all duplicates are next to one another """ res = [] last = None for element in sorted_list: ...
bigcode/self-oss-instruct-sc2-concepts
import math def compute_quaternion_w( x, y, z ): """Computes the Quaternion W component from the Quaternion X, Y and Z components. """ # extract our W quaternion component w = 1.0 - (x ** 2) - (y ** 2) - (z ** 2) if w < 0.0: w = 0.0 else: w = math.sqrt( w ) return w
bigcode/self-oss-instruct-sc2-concepts
import re def clean_fn(filename): """ 移除文件名中的特殊字符 :param filename: 文件名 :return: 处理后的文件名 """ return re.sub(r'[\\/:*?"<>|]+', '', filename)
bigcode/self-oss-instruct-sc2-concepts
def is_in_any_txt(txt, within_txts_list, case_insensitive=False): """is "txt" in any of the texts list ?""" for within_txt in within_txts_list: if case_insensitive: # slower if txt.lower() in within_txt.lower(): return True else: if txt in within_...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime async def do_request(client, url, headers, params=None): """Run request to `url` with the provided `params` and `headers`.""" def requester(url): if params: return client.post(url, headers=headers, json=params) else: return client.get(url,...
bigcode/self-oss-instruct-sc2-concepts
def html_suffix(string): """Replace or add an html extension to a filename string.""" e = string.split('.') return '.'.join(e[:-1]) + '.html' if len(e) > 1 else e[0] + '.html'
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import Any def range(query: Tuple[int, int], field_name: str, object: Any) -> bool: """ Check if value of object is in range of query """ return query[0] < getattr(object, field_name) < query[1]
bigcode/self-oss-instruct-sc2-concepts
import dataclasses def to_arg_format(cfg): """ Converts the values of a config in dictionary format to tuples (type, value). This is needed to separate dtype from default value for argument parsing. We treat `None` and `MISSING` as `str`, which is a useful default for parsing command line argumen...
bigcode/self-oss-instruct-sc2-concepts
def reshape_flattened_frames(array): """ Reshapes array shaped [frames, height*width] into array of shape [frames, height, width] Parameters ---------- array : np.array flattened array (frames, height*width) Returns ------- np.array reshaped array (frames, height, widt...
bigcode/self-oss-instruct-sc2-concepts
def _CanReportAnalysis(analysis): """Returns True if the analysis can be reported, False otherwise.""" return analysis.start_time and analysis.end_time
bigcode/self-oss-instruct-sc2-concepts
import ast def unwrap_unary_node(node: ast.AST) -> ast.AST: """ Returns a real unwrapped node from the unary wrapper. It recursively unwraps any level of unary operators. Returns the node itself if it is not wrapped in unary operator. """ if not isinstance(node, ast.UnaryOp): return n...
bigcode/self-oss-instruct-sc2-concepts
import random def load_word_set(filename): """loads the words used as bingo labels, first line is the center""" lines = open(filename).readlines() if len(lines) < 25: raise Exception("Not enough labels in %s" % filename) total_word_list = [x.strip() for x in lines] center_word = total_wor...
bigcode/self-oss-instruct-sc2-concepts
def _get_editable_repo_dir(script, package_name): """ Return the repository directory for an editable install. """ return script.venv_path / 'src' / package_name
bigcode/self-oss-instruct-sc2-concepts
def scaling_model_auto_rules(experiment): """Use dials.scale rules for determining suitable parameters.""" osc_range = experiment.scan.get_oscillation_range() scan_width = osc_range[1] - osc_range[0] if scan_width < 5.0: scale_interval, decay_interval = (1.0, 1.5) elif scan_width < 10.0: ...
bigcode/self-oss-instruct-sc2-concepts
def sign(value): """Returns the sign of the given value as either 1 or -1""" return value / abs(value)
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from datetime import datetime def time_from_timestamp(timestamp_in: Union[int, float]) -> datetime: """ Convert timestamp to :py:class:`datetime <datetime.datetime>` object. :param timestamp_in: Number representing the epoch. :return: :py:class:`datetime <datetime.datetime>` ...
bigcode/self-oss-instruct-sc2-concepts
def format_html(html): """ Helper function that formats HTML in order for easier comparison :param html: raw HTML text to be formatted :return: Cleaned HTML with no newlines or spaces """ return html.replace('\n', '').replace(' ', '')
bigcode/self-oss-instruct-sc2-concepts
def _transform_array(data, is_array, is_scalar): """Transform an array into a scalar, single value array or return in unmodified.""" if not is_array: return data[0] if is_scalar: return [data[0]] return data
bigcode/self-oss-instruct-sc2-concepts
def check_bounds(bounds): """ Check a bounds array is correct, raise ValueError if not Parameters: bounds - the bounds array to check. Of form (minx, miny, maxx, maxy) or (left, bottom, right, top). Returns: the bounds array, if valid """ if not ((bounds[0] <= bound...
bigcode/self-oss-instruct-sc2-concepts
def curtail_string(s, length=20): """Trim a string nicely to length.""" if len(s) > length: return s[:length] + "..." else: return s
bigcode/self-oss-instruct-sc2-concepts
def sort_summoner_name(name, name2, name3): """Adds spacebar formatting for names """ if name2 == "": return name else: concat_name = name + "%20" + name2 if name3 != "": concat_name += "%20" + name3 return concat_name
bigcode/self-oss-instruct-sc2-concepts
def icingByteFcnSEV(c): """Return severity value of icing pixel. Args: c (unicode): Unicode icing pixel. Returns: int: Value of severity portion of icing pixel. """ return (ord(c) >> 3) & 0x07
bigcode/self-oss-instruct-sc2-concepts
def iterate_items(dictish): """ Return a consistent (key, value) iterable on dict-like objects, including lists of tuple pairs. Example: >>> list(iterate_items({'a': 1})) [('a', 1)] >>> list(iterate_items([('a', 1), ('b', 2)])) [('a', 1), ('b', 2)] """ if hasattr(di...
bigcode/self-oss-instruct-sc2-concepts
def extract_test_prefix(raw_fullname): """Returns a (prefix, fullname) tuple corresponding to raw_fullname.""" fullname = raw_fullname.replace('FLAKY_', '').replace('FAILS_', '') test_prefix = '' if 'FLAKY_' in raw_fullname: test_prefix = 'FLAKY' elif 'FAILS_' in raw_fullname: # pragma: no cover te...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def make_combo_header_text( preposition: str, combo_dict: Dict[str, str], pop_names: Dict[str, str], ) -> str: """ Programmatically generate text to populate the VCF header description for a given variant annotation with specific groupings and subset. For example, if prepositi...
bigcode/self-oss-instruct-sc2-concepts
import torch def get_all_predictions(model, loader, device): """Get All predictions for model Args: model (Net): Trained Model loader (Dataloader): instance of dataloader device (str): Which device to use cuda/cpu Returns: tuple: all predicted values and their targets ...
bigcode/self-oss-instruct-sc2-concepts
def format_path(template, name, delimiter): """Fills the placeholders to get the path. Args: template (str): A string that contains blanks to be filled. name (str): An option name of section defined in settings.txt. delimiter (str): The signal of a blank's beginning position. Retur...
bigcode/self-oss-instruct-sc2-concepts
def m_p_s_to_km_p_hr(m_p_s): """Convert to km/hr.""" return m_p_s * 3.6
bigcode/self-oss-instruct-sc2-concepts
def get_utc_time(cur): """Get current time in UTC timezone from Central Server database""" cur.execute("""select current_timestamp at time zone 'UTC'""") return cur.fetchone()[0]
bigcode/self-oss-instruct-sc2-concepts
import re def validate_ip(ip): """ Validates an IPv4 or IPv6 IP address """ regex = re.compile('^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.)' '{3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$|' '(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}| ' ...
bigcode/self-oss-instruct-sc2-concepts
def extract_name_from_job_arn(arn): """Returns the name used in the API given a full ARN for a training job or hyperparameter tuning job. Args: arn: """ slash_pos = arn.find("/") if slash_pos == -1: raise ValueError("Cannot parse invalid ARN: %s" % arn) return arn[(slash_pos...
bigcode/self-oss-instruct-sc2-concepts
def convert_to_binary(fb_id_list): """Change the fb ids column in to a minary list. If an id is present represent the value as 1. If none represent as 0. """ final_list = [] for item in fb_id_list: if item == None: final_list.append(0) else: final...
bigcode/self-oss-instruct-sc2-concepts
def kmers(s, k): """create an array with kmers from one string""" if len(s) <= k: return [s] return [s[i:(i+k)] for i in range(len(s)-k+1)]
bigcode/self-oss-instruct-sc2-concepts
import pickle def read_file(filename='bins.prdb'): """ Read binner from file :param filename: Path to file :return: Binner instance """ with open(filename, 'rb') as inp: binner = pickle.load(inp) return binner # бининг в файл
bigcode/self-oss-instruct-sc2-concepts
def _add_dicts(*dicts): """ Creates a new dict with a union of the elements of the arguments """ result = {} for d in dicts: result.update(d) return result
bigcode/self-oss-instruct-sc2-concepts