seed
stringlengths
1
14k
source
stringclasses
2 values
def add_newline_chars_to_list(list_of_filelines): """ adds a newline character to each string in a list :param list_of_filelines: list of strings :return: list of strings """ new_filelines = [] for i in range(len(list_of_filelines)): new_filelines.append(list_of_filelines[i] + "...
bigcode/self-oss-instruct-sc2-concepts
import uuid def uuid4(short: bool = False) -> str: """ Create custom version of uuid4. :param short: If ``True`` only returns the first 8 chars of the uuid, else, 18 :return: UUID of 18 chars """ return str(uuid.uuid4())[:18 if not short else 8]
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import Tuple def parse_lat_lng(kwargs) -> Union[Tuple[float, float], Tuple[None, None]]: """Parses latitude and longitude values stated in kwargs. Can be called with an object that has latitude and longitude properties, for example: lat, lng = parse_lat_lng(objec...
bigcode/self-oss-instruct-sc2-concepts
def polynomial_3(x, a, b, c, d): """Polynomial order 3 where f(x) = a + b * x + c * x**2 + d * x**3""" return a + x * (b + x * (c + x * d))
bigcode/self-oss-instruct-sc2-concepts
def get_config_part(config_parent, match_key, match_value): """ helper function to filter a dict by a dict key :param dict_: ``dict`` :param key: dict key :param value: dict key value :returns: filtered ``dict`` """ return {k: v for (k, v) in config_parent.items() if v[match_key] == m...
bigcode/self-oss-instruct-sc2-concepts
from typing import MutableMapping def test_mock_nested_dict() -> MutableMapping: """Mock nested dictionary.""" return {"a": 1, "c": {"a": 2, "b": {"x": 5, "y": 10}}, "d": [1, 2, 3]}
bigcode/self-oss-instruct-sc2-concepts
def _get_updated_values(before_values, after_values): """ Get updated values from 2 dicts of values Args: before_values (dict): values before update after_values (dict): values after update Returns: dict: a diff dict with key is field key, value is tuple of (before_va...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union import re def extract_id_from_message(content: str) -> Union[int, None]: """ Scans string to extract user/guild/message id\n Can extract IDs from mentions or plaintext :return: extracted id """ # matching string that has 18 digits surrounded by non-digits or start/end ...
bigcode/self-oss-instruct-sc2-concepts
import requests import json def getReqJSON(url, args={}): """Generic function to get json from an api request""" if url.endswith("/"): url = url[:-1] arg_str = "" if isinstance(args, dict): if len(args) > 0: arg_str = "?" + "&".join([str(k) + "=" + str(args[k]) for k in ar...
bigcode/self-oss-instruct-sc2-concepts
def geojson_crs(epsg): """Generate a GeoJSON CRS member from an EPSG code.""" epsg = int(epsg) if epsg == 4326: coordinate_order = [1, 0] else: coordinate_order = [0, 1] return { 'type': 'EPSG', 'properties': {'code': epsg, 'coordinate_order': coordinate_order}}
bigcode/self-oss-instruct-sc2-concepts
def page_not_found(e): """Return a custom 404 error.""" return '<h1>Sorry, nothing at this URL.<h1>', 404
bigcode/self-oss-instruct-sc2-concepts
import re import unicodedata def slugify(name, allow_periods=False): """ Returns a tuple with slug and lowered slug based on name """ RE_NON_ALPHA_ETC = re.compile(r'[^.\w]+' if allow_periods else r'[^\w]+') slug = RE_NON_ALPHA_ETC.sub('-', # replace non ". alphanum_" sequences into single - ...
bigcode/self-oss-instruct-sc2-concepts
def sqkm2sqmiles(field_name, item, **kwargs): """ Convert square killometers to square miles """ sqkm_field = kwargs['source'] sqkm = item[sqkm_field].replace(',','') return '{:,}'.format(int(float(sqkm)*0.386102159))
bigcode/self-oss-instruct-sc2-concepts
import inspect import warnings def check_model_functionality(model_object: object, require_probabilities: bool = False, suppress_warning: bool = False) -> bool: """ Checks whether a model object has all the required functionality. Examines a ``m...
bigcode/self-oss-instruct-sc2-concepts
def adlist_top3_by_comment(cur): """ top 3 adlists by comment """ sql = "SELECT comment, count(*) FROM adlist GROUP BY comment LIMIT 3" cur.execute(sql) return cur.fetchall()
bigcode/self-oss-instruct-sc2-concepts
import torch def lengths_to_mask(*lengths, **kwargs): """ Given a list of lengths, create a batch mask. Example: >>> lengths_to_mask([1, 2, 3]) tensor([[ True, False, False], [ True, True, False], [ True, True, True]]) >>> lengths_to_mask([1, 2, 2], ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any from typing import List def to_list(obj: Any) -> List: """Converts an object to a list. If the object is already a list, does nothing. :param obj: Object to convert """ return obj if isinstance(obj, list) else [obj]
bigcode/self-oss-instruct-sc2-concepts
import re def split_column_name(column): """Split column name into a (name, unit) tuple.""" match = re.match(r"\s*([^ ([<]+)\s*[([<]?([^] )>]*)[])>]?", column) if not match: return column, "" name, unit = match.groups() return name, unit
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable from datetime import datetime def on_date(month: int, day: int) -> Callable[[datetime], bool]: """ Filter that allows events that match a specific date in any year Args: - month (int): the month as a number (1 = January) - day (int): the day as a number Re...
bigcode/self-oss-instruct-sc2-concepts
def a_source_username(plugin_ctx, fsm_ctx): """send source username.""" src_username = plugin_ctx.src_username fsm_ctx.ctrl.sendline(src_username) return True
bigcode/self-oss-instruct-sc2-concepts
def filter_datastores_by_hubs(hubs, datastores): """Get filtered subset of datastores corresponding to the given hub list. :param hubs: list of PbmPlacementHub morefs :param datastores: all candidate datastores :returns: subset of datastores corresponding to the given hub list """ filtered_dss ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _length_of_longest_path(file_paths: List[List[str]]) -> int: """Determines the length of the longest path out of all the paths Args: file_paths (List[List[str]]): a list containing all file paths which are lists of the parts Ex.: [['home', 'usr', 'dir1'], [...
bigcode/self-oss-instruct-sc2-concepts
def _resource_id_from_record_tuple(record): """Extract resource_id from HBase tuple record """ return record[1]['f:resource_id']
bigcode/self-oss-instruct-sc2-concepts
def is_following(user_, other_user): """Is this user following `other_use`?""" found_user_list = [user for user in user_.following if user == other_user] return len(found_user_list) == 1
bigcode/self-oss-instruct-sc2-concepts
def _identity_dynamics(x): """Returns same input as output.""" return x
bigcode/self-oss-instruct-sc2-concepts
def normalize_ip(ip): """ Transform the address into a fixed-length form, such as:: 192.168.0.1 -> 192.168.000.001 :type ip: string :param ip: An IP address. :rtype: string :return: The normalized IP. """ theip = ip.split('.') if len(theip) != 4: raise ValueError(...
bigcode/self-oss-instruct-sc2-concepts
def _var_key(var): """Key for representing a primary variable, for looking up slots. In graph mode the name is derived from the var shared name. In eager mode the name is derived from the var unique id. If distribution strategy exists, get the primary variable first. Args: var: the variable. Returns:...
bigcode/self-oss-instruct-sc2-concepts
def has_abba(code): """Checks for existence of a 4-letter palindromic substring within `code` The palindromic substring must contain 2 unique characters """ palindrome = None for i in range(len(code) - 4 + 1): # substring = code[i:i + 4] if code[i] == code[i + 3] and code[i + 1] == c...
bigcode/self-oss-instruct-sc2-concepts
import ast def genAssignStraight(to: ast.Name, fieldName: str, processorFunc: ast.Attribute, o: ast.Name) -> ast.Assign: """Returns `to.fieldName = processorFunc(o.fieldName)`""" return ast.Assign( targets=[ast.Attribute(value=to, attr=fieldName, ctx=ast.Store())], value=ast.Call( func=processorFunc, arg...
bigcode/self-oss-instruct-sc2-concepts
def deploy_contract(revert_chain, deploy_contract_txhash): """Returns a function that deploys a compiled contract""" def fn( web3, deployer_address, abi, bytecode, args, ): contract = web3.eth.contract(abi=abi, bytecode=bytecode) tx...
bigcode/self-oss-instruct-sc2-concepts
def min_encoded_value(n_bits): """The minimum value encoded by a signed bit-width.""" return 0 if n_bits >= 0 else -(2 ** (abs(n_bits)))
bigcode/self-oss-instruct-sc2-concepts
from typing import List def get_paragraphs(text: str) -> List[str]: """ Returns a list containing all paragraphs. Input(s): 1) text - Original source text. Output(s): 1) paragraphs - List containing all paragraphs. """ paragraphs = text.splitlines() paragraphs = list(filter(lamb...
bigcode/self-oss-instruct-sc2-concepts
import re def get_name_and_email(address): """ Function to get name and email from addresses like Company <contact@company.com>, returned as tuple (name, email) """ custom_sender_name = re.search(r'^([^<>]+)\s<([^<>]+)>$', address) if custom_sender_name: return custom_sender_name.group...
bigcode/self-oss-instruct-sc2-concepts
import base64 def s_to_b64s(s: str) -> str: """convert string to base 64 string :param s: input string :type s: str :return: output base 64 string :rtype: str """ b64s = base64.b64encode(s.encode('utf8')).decode('utf8') return b64s
bigcode/self-oss-instruct-sc2-concepts
def format_error_message(exception_message): """Improve the formatting of an exception thrown by a remote function. This method takes a traceback from an exception and makes it nicer by removing a few uninformative lines and adding some space to indent the remaining lines nicely. Args: exception_message...
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence from typing import List def make_beat_cycle( beat_cycle: Sequence, num_bars: int, ) -> List: """Given a beat cycle, extends it for the given number of bars. """ result = [] i = 0 while i < num_bars: bar = [] for j in range(beat_cycle[i % len(be...
bigcode/self-oss-instruct-sc2-concepts
def trim(s: str) -> str: """ Remove leading spaces """ for i, c in enumerate(s): if c != ' ': return s[i:] return ''
bigcode/self-oss-instruct-sc2-concepts
def module_path_from_object(o): """Returns the fully qualified class path of the instantiated object.""" return o.__class__.__module__ + "." + o.__class__.__name__
bigcode/self-oss-instruct-sc2-concepts
import json def read_bundles(bundle_list_file): """Read bundles in to a dict from a file. This function expects the JSON file follows a pre-defined schema: [ {"bundle_uuid": XXX, "bundle_version": XXX}, {"bundle_uuid": XXX, "bundle_version": XXX} ] Args: b...
bigcode/self-oss-instruct-sc2-concepts
import json def login_response_to_authorization_header(response): """ given a response from login or register, return a dictionary containing a header for Authorization """ return dict( Authorization='Bearer ' + json.loads( response.data.decode() ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def extract_hosts_from_arm(arm: str) -> Tuple[str, str]: """Arm names have the following format: host1.metric1-host2.metric2 Extracts and returns the name of the two hosts from the arm them. The names of the host might be the same. Args: arm (string): Name of the a...
bigcode/self-oss-instruct-sc2-concepts
import mmap def file_contains(path, needle): """Check if the file residing on the given path contains the given needle """ # Since we have no idea if build.log is valid utf8, let's convert our ASCII # needle to bytes and use bytes everywhere. # This also allow us to use mmap on Python 3. # Be ...
bigcode/self-oss-instruct-sc2-concepts
def parse_str(value: str) -> str: """ Clean string. :param str value: Original str. :return: str: Cleaned str. """ return value.strip()
bigcode/self-oss-instruct-sc2-concepts
import ast def parse_webhook(webhook_data): """ This function takes the string from tradingview and turns it into a python dict. :param webhook_data: POST data from tradingview, as a string. :return: Dictionary version of string. """ data = ast.literal_eval(webhook_data) return data
bigcode/self-oss-instruct-sc2-concepts
def users_to_string(users): """ Return users emails with <br> element for using them in tooltip's title. User will hover over the text and see all emails. """ to_return_string = "" for user in users: to_return_string += user.email + "<br/>" return to_return_string[:-5]
bigcode/self-oss-instruct-sc2-concepts
def onedim_conversion(length_or_speed: float, mm_per_pixel: float): """ :param length_or_speed: in [px] or [px/s] :param mm_per_pixel: in [mm/px] :return: length i [mm] or speed in [mm/s] """ return length_or_speed * mm_per_pixel
bigcode/self-oss-instruct-sc2-concepts
def concatenateDates(fullDates, yearMonthDates, years): """This function combines several dates in a human readable fashion. >>> concatenateDates(set(['1988-04-25']), set(['1988-05']), set()) '1988-04-25 or 1988-05' >>> concatenateDates(set(['1988-04-25', '1988-04-24']), set(['1988-05']), set()) '1988-04-24...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def hdf5_01_encode(uid: str, cksum: str, dset: int, dset_idx: int, shape: Tuple[int]) -> bytes: """converts the hdf5 data has spec to an appropriate db value Parameters ---------- uid : str the file name prefix which the data is written to. cksu...
bigcode/self-oss-instruct-sc2-concepts
def verify_variant_type(variants, variant_type, pos, length): """"Helper function for checking a specific variant type. Args: variants: List of variants to look through. variant_type: The type of variant to verify. pos: Position of the variant. length: Size of the variant. ...
bigcode/self-oss-instruct-sc2-concepts
import math def euclidian_distance(x, y): """Get euclidian distance between two segments. Parameters ---------- x : float length of the first edge y : float length of the second edge Return: float euclidian distance between the two edges """ return math.sqrt(x...
bigcode/self-oss-instruct-sc2-concepts
def get_overlaps(inds_1, inds_2): #verified. """ Calculate the overlaps between two reads and the distance spanned by them. The reads are each assumed to comprise two arms, a left and a right arm. inds_1 and inds_2: [left start, left stop, right start, right stop] Returns overlap_l, overlap_r, span_...
bigcode/self-oss-instruct-sc2-concepts
import random def get_random_cluster_service_component(client, cluster, service) -> dict: """ Get random cluster service component Args: client: ADCM client API objects cluster: some cluster object service: some service object in cluster Raises: :py:class:`ValueError`...
bigcode/self-oss-instruct-sc2-concepts
def base_repr(number, base=2, padding=0): """ Return a string representation of a number in the given base system. Parameters ---------- number : int The value to convert. Positive and negative values are handled. base : int, optional Convert `number` to the `base` number system...
bigcode/self-oss-instruct-sc2-concepts
def stringify(obj): """Converts all objects in a dict to str, recursively.""" if isinstance(obj, dict): return {str(key): stringify(value) for key, value in obj.items()} elif isinstance(obj, list): return [stringify(value) for value in obj] else: return str(obj)
bigcode/self-oss-instruct-sc2-concepts
def make_c_string(string): """Render a Python string into C string literal format.""" if string == None: return "\"\"" string = string.replace("\n", "\\n") string = string.replace("\t", "\\t") string = string.replace('"', '\\"') #string = string.replace("'", "\\'") string = '"' + str...
bigcode/self-oss-instruct-sc2-concepts
def get_fromtos_line(linestring_coords): """ Converts a list of linestring coordinates to a list of 'from-to' dictionaries. """ line_coordinates_list_froms = linestring_coords[:-1] line_coordinates_list_tos = linestring_coords[1:] i = 0 fromtos = [] for i, val in enumerate(line_coo...
bigcode/self-oss-instruct-sc2-concepts
def get_bucket_names(s3): """ Purpose: Return an Bucket Names in S3 Args: s3 (S3 Resource Object): S3 Object owning the Bucket Return: bucket_names (List of Strings): Name of buckets in S3 """ return [bucket.name for bucket in s3.buckets.all()]
bigcode/self-oss-instruct-sc2-concepts
def get_element_tag(element): """Returns the tag name string without namespace of the passed element.""" return element.tag.rsplit('}')[1]
bigcode/self-oss-instruct-sc2-concepts
import re def clean_len(s): """ Calculate the length of a string without it's color codes """ s = re.sub(r'\x1b\[[0-9;]*m', '', s) return len(s)
bigcode/self-oss-instruct-sc2-concepts
def get_models(model_key: str, model_type, json_dict: dict) -> list: """This converts json lists into a list of the specified SUSHI model type :param model_key: The target key to get the list of JSONObjects :param model_type: The target model type, e.g PerformanceModel :param json_dict: The JSON dict t...
bigcode/self-oss-instruct-sc2-concepts
def remove_dash(item): """ Remove the first character in a string. :param item: String :return: input string, with first character removed """ return item[1:]
bigcode/self-oss-instruct-sc2-concepts
def func_calc_density(M,T,Tc,Pc,Vc,Tb): """ Function to calculate density Parameters: Tc : Critical temperature (K) Pc : Critical pressure (bar) Vc : Critical molar volume (cm^3/mol) Tb : Normal boiling temperature (K) M : Molecular weight (g/mol) ...
bigcode/self-oss-instruct-sc2-concepts
def create_auto_profile(role_session, user_session, session_name, source_profile_name, role_arn): """Create the profile that'll be stored in the credentials file for autoawsume. Parameters ---------- - role_session - the session credentials from the assume-role api call - user_session - the session...
bigcode/self-oss-instruct-sc2-concepts
def monthly_savings(future_savings, years_to_retirement, interest_rate, compounds_per_year=2, startwith=0): """ Calculates how much you need to save per month to retire given the parameters """ r, m, n = interest_rate, compounds_per_year, years_to_retirement * 12 efr = (1 + r/m) ** (m / 12) - 1 ...
bigcode/self-oss-instruct-sc2-concepts
def subject_module_id() -> str: """Return the Protocol Engine module ID of the subject.""" return "subject-module-id"
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict def sort_list_of_dicts_by_first_key(dicts: List[Dict]) -> List[Dict]: """Sorts a list of dictionaries by their first key.""" return sorted(dicts, key=lambda d: list(d.keys())[0])
bigcode/self-oss-instruct-sc2-concepts
import logging def GFFAddIDAttributes(gff_data): """ Construct & insert a ID attribute for all features without one For each feature in the input GFF data that doesn't already have an an ID attribute, insert one of the form: ID=<feature>:<Parent>:<n> where <feature> is the feature type (e.g...
bigcode/self-oss-instruct-sc2-concepts
import functools def simple(func): """ Simple Decorator This is a simple decorator function. It takes the function being decorating as input and returns a wrapped version of that function as output. This makes it possible to inject custom logic berore and after the function execution. """...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def convert_time(y): """Convert time string and reformat :param str y: Time string to convert :return: Time string :rtype: datetime """ time = datetime.strptime(y, '%H:%M:%S').time() return time
bigcode/self-oss-instruct-sc2-concepts
def get_timeout(run_type): """Get timeout for a each run type - daily, hourly etc :param run_type: Run type :type run_type: str :return: Number of seconds the tool allowed to wait until other instances finish :rtype: int """ timeouts = { 'hourly': 3600 / 2, 'daily': 24...
bigcode/self-oss-instruct-sc2-concepts
def _get_var_names(posterior): """Extract latent and observed variable names from pyro.MCMC. Parameters ---------- posterior : pyro.MCMC Fitted MCMC object from Pyro Returns ------- list[str], list[str] observed and latent variable names from the MCMC trace. """ sample_...
bigcode/self-oss-instruct-sc2-concepts
import csv def transform_csv(input_file, output_file, header_fx=None, row_fx=None): """ Transforms a csv using streaming technique. Calls a header function that allows the caller to modify the header; also calls a row function that allows the caller to modify each row in csv. Allows the caller to pass arbitrar...
bigcode/self-oss-instruct-sc2-concepts
def preconvert_discriminator(discriminator): """ Converts the given `discriminator` to an acceptable value by the wrapper. Parameters ---------- discriminator : `str` or `int` The discriminator of an user to convert. Returns ------- discriminator : `int` Raises...
bigcode/self-oss-instruct-sc2-concepts
def xact_name(xact): """Returns the payee of a transaction""" return xact["name"]
bigcode/self-oss-instruct-sc2-concepts
import pickle def cargar_objeto(nombre_archivo): """ Carga un objeto en Python, desde un archivo Pickle cuya ubicación es determinada por el usuario. :param nombre_archivo: (str). Ubicación del archivo que contiene el objeto que se desea cargar. :return: (objeto Python). Objeto en Python contenido e...
bigcode/self-oss-instruct-sc2-concepts
import operator def sorted_dict_items(d, reverse=False): """Sorted (key, value) pairs by value. """ result = sorted(d.items(), key=operator.itemgetter(1)) if reverse: return result[::-1] else: return result
bigcode/self-oss-instruct-sc2-concepts
def identify_climate_scenario_run(scen_info, target_scen): """Identify the first matching run for a given climate scenario. Returns ---------- * str or None, run id """ for scen in scen_info: if target_scen in scen_info[scen]['climate_scenario']: return scen # End for ...
bigcode/self-oss-instruct-sc2-concepts
import torch def create_coref_tensors(pos_coref_mention_pairs, pos_eds, neg_coref_mention_pairs=None, neg_eds=None): """ Combines positive and negative corefeference samples into tensors """ neg_coref_mention_pairs = neg_coref_mention_pairs if neg_coref_mention_pairs else [] neg_e...
bigcode/self-oss-instruct-sc2-concepts
import re def to_kebabcase(string): """ Converts the given string to kebab-case. >>> to_kebabcase('HelloWorld') 'hello-world' >>> to_kebabcase('__Init__File__') 'init-file' >>> to_kebabcase('') '' >>> to_kebabcase('already-kebab-case') 'already-kebab-case' >>> to_kebabcase...
bigcode/self-oss-instruct-sc2-concepts
import torch def batch_mse_torch(estimation, origin): """ batch-wise mse caculation for multiple audio files. estimation: (batch, nsource, frames, freq_bins) origin: (batch, nsource, frames, freq_bins) nsource = 2 """ mse1 = torch.sqrt(torch.pow(estimation - origin, 2).mean([3])).mean([1,2...
bigcode/self-oss-instruct-sc2-concepts
import re def split_msg(msg): """ splits msg example: this: is, some msg -> [this, is, some, msg] """ return re.findall(r"[^\s]+", msg)
bigcode/self-oss-instruct-sc2-concepts
def direction_color_red_green(val: str) -> str: """Adds color tags to the Direction information: Buy -> Green, Sell -> Red Parameters ---------- val : str Direction string - either Buy or Sell Returns ------- str Direction string with color tags added """ color = "g...
bigcode/self-oss-instruct-sc2-concepts
def hashing(file,pp): """ Map an input file and a postprocessing config to an unique hash. The hash is used to store the item in the database. It needs to be persistent across different python implementations and platforms, so we implement the hashing manually. """ file = file.lower() file...
bigcode/self-oss-instruct-sc2-concepts
def _mapping_table_for(domain_table): """ Get name of mapping table generated for a domain table :param domain_table: one of the domain tables (e.g. 'visit_occurrence', 'condition_occurrence') :return: mapping table name """ return '_mapping_' + domain_table
bigcode/self-oss-instruct-sc2-concepts
def url_get_parent(url): """ http://one/two/three => http://one/two http://one => http://one """ index = url.rfind("/") if index > 8: # avoid https:// return url[0:index] else: return url
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple import math def get_xy_components(lon: float, lat: float) -> Tuple[int, int]: """For a given longitude and latitude, returns the relevant components of the name of the zip file containing the SRTM data (for example "35" and "02" in "srtm_35_02.zip"). """ mod_lon = (int(mat...
bigcode/self-oss-instruct-sc2-concepts
def recursive_merge(original, addition): """Merge the content of ``addition`` into ``original``, recursing when both arguments have a dictionary for the same key. """ for key, value in addition.iteritems(): if key in original: source = original[key] if isinstance(source,...
bigcode/self-oss-instruct-sc2-concepts
import torch def bounding_box_x0y0x1y1_to_xcycwh(bounding_boxes: torch.Tensor) -> torch.Tensor: """ This function converts a given bounding bix of the format [batch size, instances, 4 (x0, y0, x1, y1)] to [batch size, instances, 4 (x center, y center, width, height)]. :param bounding_boxes: Bounding b...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any from typing import MutableSequence from typing import Tuple def is_edge_list(item: Any) -> bool: """Returns whether 'item' is an edge list.""" return (isinstance(item, MutableSequence) and all(isinstance(i, Tuple) for i in item) and all(len(i) == 2 for i in item...
bigcode/self-oss-instruct-sc2-concepts
import collections def getDictFromAngles(angles): """ Converts angles of a JointState() to a dictionary :param angles (sensor_msgs.msg.JointState): angles to be converted :return (dict): dictionary with angles """ d=dict(zip(angles.name,angles.position)) return collection...
bigcode/self-oss-instruct-sc2-concepts
def process_status(pid, run): """ Return the status of a process, obtained using the ps command. The run option is used to run the command (so it could run on a remote machine). The result is a dictionary; it is empty if the given process is not running. """ fields = ['%cpu', '%mem', 'etime...
bigcode/self-oss-instruct-sc2-concepts
def freq_str(freq_list): """ Function that transforms the array of frequency values into a string of comma separated entries. The array is converted into a string and the square brackets are removed form it. The resulting string will be the list of frequencies to sweep over, organized into com...
bigcode/self-oss-instruct-sc2-concepts
import json def incident_to_incident_context(incident): """ Creates an incident context of a incident. :type incident: ``dict`` :param incident: Single detection object :return: Incident context representation of a incident :rtype ``dict`` """ ...
bigcode/self-oss-instruct-sc2-concepts
def getSelectionShape(selection): """ Return the shape of the given selection. Examples (selection -> returned shape): [(3,7,1)] -> [4] [(3, 7, 3)] -> [1] [(44, 52, 1), (48,52,1)] -> [8, 4] """ shape = [] rank = len(selection) for i in range(rank): s = selection[i] ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def make_sim_exp_name(config): """Helper to create a simulator directory name using datetime and config""" time = datetime.now().strftime('%Y%m%d_%H%M%S') n_nonmot = config['exp_params']['n_non_motile'] n_mot = config['exp_params']['n_motile'] return f'{time}_sim_ma...
bigcode/self-oss-instruct-sc2-concepts
def _remove_extension(path, extension): """ Removes the extension from a path. """ return path[:-len(extension)] if path.endswith(extension) else path
bigcode/self-oss-instruct-sc2-concepts
def get_mock_loss_function(mock_value): """ A loss function that just returns a hardcoded value. Used for testing only. :param mock_value: :return: """ def mock_loss(y_true, y_pred): return mock_value return mock_loss
bigcode/self-oss-instruct-sc2-concepts
def feature_dict_map(weights): """construct a dict with features from a weights dictionary :param weights: dictionary mapping features to numeric weights :return: dictionary from features to a (index, weight) """ if type(weights) is dict: result = {k: (i, weights[k]) for i, k in enumerate(...
bigcode/self-oss-instruct-sc2-concepts
def average(l): """The average value of a list""" if len(l) == 0: return 0 return sum(l)/len(l)
bigcode/self-oss-instruct-sc2-concepts
def letters_only(word:str, lower_case:bool = True): """ Return only letters of string input parameter Parameters ---------- word : str String from which letters are being returned lower_case : bool If set to True (default) return lower-case letters Returns ------- ...
bigcode/self-oss-instruct-sc2-concepts