seed
stringlengths
1
14k
source
stringclasses
2 values
def no_decompress(data): """Don't decompress""" return data
bigcode/self-oss-instruct-sc2-concepts
import re def sanitize(string): """ Cleanses a string so it is safe to use in a file path """ return re.sub(r'[:/\\<>|?*\'\"]', '_', string)
bigcode/self-oss-instruct-sc2-concepts
import traceback def _format_exc_value(e: BaseException, limit=None, chain=True): """Like traceback.format_exc() but takes an exception object.""" list = traceback.format_exception( type(e), e, e.__traceback__, limit=limit, chain=chain ) str = "".join(list) return str
bigcode/self-oss-instruct-sc2-concepts
def adjust_widget(widget,window_title=None,size=None,**kwargs): """Apply some adjustments to a widget. Unused kwargs are returned.""" if window_title is not None: widget.setWindowTitle(window_title) if size is not None: widget.resize(*size) return kwargs
bigcode/self-oss-instruct-sc2-concepts
def converter_farenheight(temp: int) -> int: """Converts from kelvin to fahrenheit""" # formula = (K − 273.15) × 9/5 + 32 = F return round((temp - 273.15) * 9/5 + 32)
bigcode/self-oss-instruct-sc2-concepts
def calc_tpr_protected(actual, predicted, sensitive, unprotected_vals, positive_pred, is_tnr=False): """ Returns P(C=YES|Y=YES, sensitive=privileged) and P(C=YES|Y=YES, sensitive=not privileged) in that order where C is the predicited classification and where all not privileged values are considered equ...
bigcode/self-oss-instruct-sc2-concepts
def has_open_sequence(text: str) -> bool: """Figures out if the given text has any unclosed ANSI sequences. It supports standard SGR (`\\x1b[1mHello`), OSC (`\\x1b[30;2ST\\x1b\\\\`) and Kitty APC codes (`\x1b_Garguments;hex_data\\x1b\\\\`). It also recognizes incorrect syntax; it only considers a tag c...
bigcode/self-oss-instruct-sc2-concepts
def _get_attribute(attributes, key, all=False): """Safely get the LDAP attribute specified by ``key``. If the attribute doesn't exist, ``None`` will be returned if ``all=False`` and ``[]`` will be returned if ``all=True``. If the attribute does exist, its first value will be returned by default. I...
bigcode/self-oss-instruct-sc2-concepts
def client(app): """ Returns session-wide Flask test client. """ return app.test_client()
bigcode/self-oss-instruct-sc2-concepts
def TransformFloat(r, precision=6, spec=None, undefined=''): """Returns the string representation of a floating point number. One of these formats is used (1) ". _precision_ _spec_" if _spec_ is specified (2) ". _precision_" unless 1e-04 <= abs(number) < 1e+09 (3) ".1f" otherwise. Args: r: A JSON-serializ...
bigcode/self-oss-instruct-sc2-concepts
import struct def uint32_unpack(buf): """Unpack 32 bit integer from a stream""" return struct.unpack('<L', buf)[0]
bigcode/self-oss-instruct-sc2-concepts
def check_retry(status): """ Checks is the job needs to be retried. Jobs are retried if max_retries is not reached and the tower status is temporarily unreachable. Args: status (:obj:`str`): the tower status. Returns: :obj:`bool`: True is the status is "temporarily unreachable"...
bigcode/self-oss-instruct-sc2-concepts
def _try_call(fn, args, kwargs): """Convenience function for evaluating argument `fn`.""" if fn is None: return args[0] try: return fn(*args, **kwargs) except TypeError: return fn(*args)
bigcode/self-oss-instruct-sc2-concepts
import re def normalize_whitespace(value): """Replace multiple spaces into one""" return re.sub(r"\s+", " ", value)
bigcode/self-oss-instruct-sc2-concepts
def assign_colors_to_indices(indices_subsets): """ Assigns different colors to different subsets of indices. """ # If there are no highlighted elements, return no colors. if indices_subsets is None: return [], {} # Define the colors that will be used for highlighting different groups of elemen...
bigcode/self-oss-instruct-sc2-concepts
def p(F, d=2): """ Given the fidelity of a gate in :math:`d` dimensions, returns the depolarizating probability of the twirled channel. :param float F: Fidelity of a gate. :param int d: Dimensionality of the Hilbert space on which the gate acts. """ return (d * F - 1) / (d - 1)
bigcode/self-oss-instruct-sc2-concepts
def get_return_name(i): """ Given some integer i, return the name of the ith return. :param i: A nonnegative integer :return: The name of the return identifier according to our internal naming """ return '$return_%d' % i
bigcode/self-oss-instruct-sc2-concepts
def fuel_used(pos, list_): """gives the fuel amount for a specific position""" return sum([abs(pos - i) for i in list_])
bigcode/self-oss-instruct-sc2-concepts
import requests def handle_429(response, default_delay=70): """ Handle 429: output warning and suuggested next steps The user has exceeded their rate limit. This method will return the number of seconds the caller should wait based on the dictated rate-limiting logic specified by the API. Parame...
bigcode/self-oss-instruct-sc2-concepts
def is_even(value): """ Checks if a given value is even. If value is even the function returns True, otherwise it returns False. """ return value % 2 == 0
bigcode/self-oss-instruct-sc2-concepts
def ismacro(o): """ Is the given object a macro? """ return hasattr(o, 'macroName')
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from pathlib import Path def find_stylesheets() -> Iterable[str]: # pragma: no cover """Fetch all stylesheets used in the official Kedro documentation""" css_path = Path(__file__).resolve().parents[1] / "html" / "_static" / "css" return ( str(css_path / "copybutton.css...
bigcode/self-oss-instruct-sc2-concepts
def get_all_coins(exchanges): """ :param exchanges: [] of CryptoExchange List of exchanges :return: [] of str List of coins in all exchanges """ return list(set([ coin for exchange in exchanges for coin in exchange.build_wallets().keys() ]))
bigcode/self-oss-instruct-sc2-concepts
def must_replace_suffix(str, suffix, replacement): """ Replaces the given suffix in the string. If the string does not have the suffix, a runtime error will be raised. """ splits = str.rsplit(suffix, maxsplit=1) if len(splits) != 2 or splits[1]: raise RuntimeError(str + " does not contai...
bigcode/self-oss-instruct-sc2-concepts
import re def strip_whitespace(uni): """Strips all whitespace from a unicode string. Args: uni (unicode) Returns: unicode """ return re.sub(r"\s+", "", uni)
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def get_ports(line: str) -> Tuple[str, str]: """Returns 2 port labels strings from interconnect file.""" line = line.replace('"', "") line = line.replace("(", "") line_fields = line.split(",") port1 = line_fields[0] port2 = line_fields[3] return port1, port2
bigcode/self-oss-instruct-sc2-concepts
def get_run_info_nextseq500( instrument_model, application_version, tree ): """ Helper function to get some info about the sequencing runs. Args: tree: xml tree Returns: dict: basic statistics about run, like date, instrument, number of lanes, flowcell ID, read lengths, etc. """ ...
bigcode/self-oss-instruct-sc2-concepts
def is_external(label): """Determines whether a label corresponds to an external artifact.""" return label.workspace_root.startswith("external")
bigcode/self-oss-instruct-sc2-concepts
def unroll(piano_roll): """ Unrolls a piano roll into a list of notes. Args: piano_roll (list of lists of lists): the piano roll list """ temp = [] for song in piano_roll: for notes in song: temp += notes return temp
bigcode/self-oss-instruct-sc2-concepts
def checkRecord(s: str) -> bool: """ given a string s representing an attendance record for a student where each character signifies whether the student was absent, late, or present on that day. The record only contains the following three characters: 'A': Absent. 'L': Late. 'P': Present. The st...
bigcode/self-oss-instruct-sc2-concepts
def point_str(x,y=0,z=0): """ Returns a string repr of a point. Example: point_str(1,2,3) returns '(1.0,2.0,3.0)' Parameter x: the x coordinate Precondition: x is a number Parameter y: the y coordinate Precondition: y is a number Parameter z: the x coordinate Precondition: z...
bigcode/self-oss-instruct-sc2-concepts
def displayHits(hits): """ Handles the I/O of the song-searching functionality Parameters ---------- hits : list Holds json dictionaries with information of the songs that the search turned up Returns ------- integer Either -1 if no song was chosen or the index in hits with the appropriate song's...
bigcode/self-oss-instruct-sc2-concepts
def prime_sieve(n: int) -> list[int]: """ Sieve of Erotosthenes Function to return all the prime numbers up to a certain number https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes >>> prime_sieve(3) [2] >>> prime_sieve(50) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] ""...
bigcode/self-oss-instruct-sc2-concepts
def version_check(version): """Checks if OpenFlow version is compatible and returns the version if it is Parameters ---------- version: hex The OpenFlow version taken from the SDN switch 'hello' message Returns ------- The OpenFlow version if match, else 0 for unknown version ...
bigcode/self-oss-instruct-sc2-concepts
def is_outpatient(med): """Return true if the medication record belong to a valid outpatient order.""" return med.ordering_mode_name == 'Outpatient' and med.order_status_name == 'Sent'
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import Optional import re def decode_mention(mention: str) -> Tuple[Optional[str], Optional[int]]: """returns whether mention is a member mention or a channel mention (or neither) as well as the id of the mentioned object""" match = re.search(r"<(#|@)!?(\d+)>", mention) if matc...
bigcode/self-oss-instruct-sc2-concepts
def get_binary(values, threshold, target): """ Transforms continuous or multiclass values into binary values (0/1) Args: values (list): vector of the target values threshold (int or float): threshold used to assign a binary value 0 is assigned to 'bad' values...
bigcode/self-oss-instruct-sc2-concepts
def calc_gamma_FeO_silicate(silicate_comp): """ Returns a value for gammaFeO in the silicate. Parameterization is based on Holdzheid, where gammaFeO is taken as a constant value from 1.7-3, dependent only upon MgO content. Parameters ---------- silicate_comp: dict Dictionary of the composition of the silicate...
bigcode/self-oss-instruct-sc2-concepts
def flatten(l: list): """ Accepts a list containing one or more nested lists and returns a flattened copy. Parameters ---------- l: list A list containing one or more lists. Can contain zero lists but there's no point Returns ------- list A flattened version of the orig...
bigcode/self-oss-instruct-sc2-concepts
import pathlib def print_markdown(data, **kwargs): """Print listed data in GitHub-flavoured Markdown format so it can be copy-pasted into issues. Can either take a list of tuples or a dictionary, which will be converted to a list of tuples.""" def excl_value(value): # don't print value if it ...
bigcode/self-oss-instruct-sc2-concepts
def generate_fasta_dict(sec_record_list): """ Creates a dictionary containing FASTA formatted strings from a list of sequence record objects. This dictionary is keyed by the sequence ID. :param sec_record_list: List of Biopython sequence record objects. :return: Dictionary containing FASTA formatted strings. """...
bigcode/self-oss-instruct-sc2-concepts
def chop_at(s, sub, inclusive=False): """Truncate string ``s`` at the first occurrence of ``sub``. If ``inclusive`` is true, truncate just after ``sub`` rather than at it. >>> chop_at("plutocratic brats", "rat") 'plutoc' >>> chop_at("plutocratic brats", "rat", True) 'plutocrat' """ pos...
bigcode/self-oss-instruct-sc2-concepts
def format_percent(num): """ Format a percentage """ return int(round(num))
bigcode/self-oss-instruct-sc2-concepts
def _is_namedtuple(obj): """Returns `True` if `obj` is a `collections.namedtuple`.""" return isinstance(obj, tuple) and hasattr(obj, "_fields")
bigcode/self-oss-instruct-sc2-concepts
def _reachable(graph): """Return a dictionary with all reachable nodes from the graph nodes. Args: graph: dict: dictionary representing a graph. Keys are the nodes and values is a set containing the linked nodes. Returns: a new dictionary with the same keys, but whose values are al...
bigcode/self-oss-instruct-sc2-concepts
def add(n1, n2): """Return the sum of two numbers.""" return n1 + n2
bigcode/self-oss-instruct-sc2-concepts
def moyenne_ponderee(a : float, b : float, c : float, pa : float, pb : float, pc : float) -> float: """Hypothèse : pa + pb + pc != 0 Retourne la moyenne des trois nombres a, b, c, pondérés respectivement par pa (pondération pour a), pb et pc. """ return ((a * pa) + (b * pb) + (c...
bigcode/self-oss-instruct-sc2-concepts
def format_as_string(string: str): """ Formats a given string in a different color using ANSI escape sequences (see https://stackoverflow.com/a/287944/5299750) and adds double quotes :param string: to be printed """ ansi_start = '\033[32m' ansi_end = '\033[0m' return f"{ansi_start}\"{str...
bigcode/self-oss-instruct-sc2-concepts
def track_prop_dict_length(track_prop_dict): """Returns the number of tracks in a track properties dictionary. Raises an exception if the value lists in the input dictionary are not all of the same length. Returns zero if the track properties dict is empty.""" # A fancy way of checking if all value...
bigcode/self-oss-instruct-sc2-concepts
def count_lines(abspath): """Count how many lines in a pure text file. """ with open(abspath, "rb") as f: i = 0 for line in f: i += 1 pass return i
bigcode/self-oss-instruct-sc2-concepts
def _is_version_range(req): """Returns true if requirements specify a version range.""" assert len(req.specifier) > 0 specs = list(req.specifier) if len(specs) == 1: # "foo > 2.0" or "foo == 2.4.3" return specs[0].operator != '==' else: # "foo > 2.0, < 3.0" return Tr...
bigcode/self-oss-instruct-sc2-concepts
def latest_consent(user, org_id=None, include_suspended=False): """Lookup latest consent for user :param user: subject of query :param org_id: define to restrict to given org :param include_suspended: set true to stop looking back, even if the consent is marked suspended (aka withdrawn). By de...
bigcode/self-oss-instruct-sc2-concepts
def get_node_components_from_abstraction_graph(graph): """Extract the set of node ids from each node label in the input graph. Parameters ---------- graph : Networkx undirected graphs Abstract graph with set of node ids as labels. Returns ------- node_components : list[set(node ids...
bigcode/self-oss-instruct-sc2-concepts
def melt_cluster_rep_matrix(df, name="count"): """Helper function to melt a cluster rep matrix for saving as feather""" return df.T.reset_index().melt(id_vars=["cluster", "rep"], var_name="FBgn", value_name=name)
bigcode/self-oss-instruct-sc2-concepts
def wheel(pos): """b->g->r color wheel from 0 to 1020, neopixels use grb format""" if pos < 255: return [0 , pos , 255] elif pos < 510: pos -= 255 return [0 , 255, 255 - pos] elif pos < 765: pos -= 510 return [ pos, 255, 0] elif pos<=1020: pos -= ...
bigcode/self-oss-instruct-sc2-concepts
def _opacity_from_bin(bin, n_bins): """ Return opacity for bin.""" if n_bins <= 0: return 0.35 ratio = bin/float(n_bins) if ratio < 0.2: return 0.6 elif ratio < 0.3: return 0.85 elif ratio < 0.5: return 1.0 return 1.0
bigcode/self-oss-instruct-sc2-concepts
def fib(n, i=0, a=0, b=1): """Return the nth fibonacci number. >>> fib(6) 8 >>> [fib(n) for n in range(6)] [0, 1, 1, 2, 3, 5] >>> fib(-1) Traceback (most recent call last): ... ValueError: n must be >= 0 """ if not n >= 0: raise ValueError("n must be >= 0") ...
bigcode/self-oss-instruct-sc2-concepts
def purchase_intention(people_who_declared_interest, total_people): """Returns the purchase intention rate for a product. This can be used for cart-to-detail, buy-to-detail, and similar calculations. Args: people_who_declared_interest (int): Number of people who declared interest in a product. ...
bigcode/self-oss-instruct-sc2-concepts
def file_get_contents(path : str) -> bytes: """ Returns contents of file located at 'path' """ with open(path, 'rb') as f: return f.read()
bigcode/self-oss-instruct-sc2-concepts
import random def split_list_equal_sized_groups(lst: list, n: int, seed: int = 123) -> list: """This function splits a list in n approximately equal-sized subgroups Args: lst (list): input list that we want to split n (int): number of splits seed (int): random seed to use; defaults to ...
bigcode/self-oss-instruct-sc2-concepts
import base64 def encode(data, chunklen=6, linelen=78): """ Encode data with base64 and format it. Arguments: data: String to be encoded. chunklen: Number of bytes in a chunk, defaults to 6. linelen: Length of a line, defaults to 78 characters. Returns: The base64 enc...
bigcode/self-oss-instruct-sc2-concepts
def get_chart_url(country_code, interval, date1, date2): """Gets a url with the specified parameters""" chart_url = f'https://spotifycharts.com/regional/{country_code}/{interval}/{date1}--{date2}' return chart_url
bigcode/self-oss-instruct-sc2-concepts
def get_pdb_atom_info(line): """Split and read pdb-file line (QPREP-OUT). Extract and return: atomnumber, atomname, resname, resid) """ # UNIT: check if the correct numbers are extracted atomnum = int(line[6:11]) atmname = line[13:17].strip() resname = line[17:20].strip() resin...
bigcode/self-oss-instruct-sc2-concepts
def get_rot_mat(T): """ Takes a homogeneous transformation matrix and returns the corresponding rotation matrix and position vector :param T: 4 x 4 transformation matrix :return: rot_mat: 3 x 3 rotation matrix pos_vec: 3 x 1 position vector """ rot_mat = T[0:3, 0:3] ...
bigcode/self-oss-instruct-sc2-concepts
def get_ddfNames(opsimdb): """Given an opsim database object, return the DDF field names.""" propInfo = opsimdb.fetchPropInfo() DD_Ids = propInfo[1]['DD'] DD_names = [propInfo[0][x].split(':')[1] for x in DD_Ids] return DD_names
bigcode/self-oss-instruct-sc2-concepts
def append_correct_whitespace(token, pronoun): """ If the original pronoun was followed by whitespace, append whitespace to new pronoun. """ if token.text_with_ws != token.text: whitespace = token.text_with_ws[-1] pronoun = pronoun + whitespace return pronoun
bigcode/self-oss-instruct-sc2-concepts
def social_networks(context, user): """ Return user's social network connections """ association_facebook = user.social_auth.filter(provider='facebook').first() association_twitter = user.social_auth.filter(provider='twitter').first() association_googleplus = user.social_auth.filter(provider='go...
bigcode/self-oss-instruct-sc2-concepts
import re def preprocess_ents(label, text): """ Preprocess an entity Parameters ---------- label: str: The named entity label text: str: The name entity text Returns ------- tuple: returns a tuple of strings containing the label and text """ pattern = ':...
bigcode/self-oss-instruct-sc2-concepts
import math def computeStartsOfInterval(maxVal: int, intervalLength=1024, min_overlap_part=0.33): """ Divide the [0; maxVal] interval into a uniform distribution with at least min_overlap_part of overlapping :param maxVal: end of the base interval :param intervalLength: length of the new intervals ...
bigcode/self-oss-instruct-sc2-concepts
def checkPrefix(mainList, inputGTParams): """ Compares two input GTs to see if they have the same prefix. Returns the index in the internal list of GTs of the match or -1 in case of no match. """ if inputGTParams.find("_") == -1: raise Exception("Invalid GT name. It does not contain an _, it cannot ...
bigcode/self-oss-instruct-sc2-concepts
def currency(value): """ Returns a string currency representation of a float """ return '${:,.2f}'.format(value)
bigcode/self-oss-instruct-sc2-concepts
def tensor_to_complex_np(data): """ Converts a complex torch tensor to numpy array. Args: data (torch.Tensor): Input data to be converted to numpy. Returns: np.array: Complex numpy version of data. """ data = data.numpy() return data[..., 0] + 1j * data[..., 1]
bigcode/self-oss-instruct-sc2-concepts
def should_reduce_batch_size(exception: Exception) -> bool: """ Checks if `exception` relates to CUDA out-of-memory, CUDNN not supported, or CPU out-of-memory Args: exception (`Exception`): An exception """ _statements = [ "CUDA out of memory.", # CUDA OOM "cuDN...
bigcode/self-oss-instruct-sc2-concepts
import torch def is_tensor(data): """Checks if data is a torch tensor.""" return type(data) == torch.Tensor
bigcode/self-oss-instruct-sc2-concepts
import imp def load_module_file(module_name, file_path): """Load module given name and path.""" with open(file_path, 'r') as f: return imp.load_module(module_name, f, "%s.py" % module_name, (".py", "r", imp.PY_SOURCE))
bigcode/self-oss-instruct-sc2-concepts
import inspect def get_kwarg_names(func): """ Return a list of valid kwargs to function func """ sig = inspect.signature(func) kwonlyargs = [p.name for p in sig.parameters.values() if p.default is not p.empty] return kwonlyargs
bigcode/self-oss-instruct-sc2-concepts
def DoesDatabaseExist(client_vm, connection_string, database_name): """Returns whether or not the specifid database exists on the server. Args: client_vm: client vm which will run the query connection_string: database server connection string understood by psql database_name: name of database to check ...
bigcode/self-oss-instruct-sc2-concepts
def _synapse_error_msg(ex): """ Format a human readable error message """ if isinstance(ex, str): return ex return '\n' + ex.__class__.__name__ + ': ' + str(ex) + '\n\n'
bigcode/self-oss-instruct-sc2-concepts
def prices_from_returns(returns): """ Calculate the pseudo-prices given returns. These are not true prices because the initial prices are all set to 1, but it behaves as intended when passed to any PyPortfolioOpt method. :param returns: (daily) percentage returns of the assets :type returns: pd...
bigcode/self-oss-instruct-sc2-concepts
def do_complicated_mathematics() -> int: """Do complicated mathematics. Returns: int: The result """ return 1 + 1
bigcode/self-oss-instruct-sc2-concepts
def new_duplicate_dict(d): """ Create a duplicate of the given dictionary """ d1 = {} for p in d.keys(): d1[p] = d[p] return d1
bigcode/self-oss-instruct-sc2-concepts
def cleanup_url(url: str) -> str: """Cleans up the text to be a valid URL. Returns: str: The cleaned up URL. """ url = url.replace(" ", "-") if url.startswith("http://") or url.startswith("https://"): return url else: return f"https://{url}"
bigcode/self-oss-instruct-sc2-concepts
def results(person, result, rate): """ Checks if the current person is in the dict, if not adds them with their current rate if they are, adds the current rate to the current person :param person: the current person :param result: the output result :param rate: the current tax rate :return: ...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def hash_object(*objects, hasher=None): """Hash the given object(s) and return the hashlib hasher instance If no hasher argument is provided, then automatically created a hashlib.md5() """ if hasher is None: hasher = hashlib.md5() for obj in objects: if...
bigcode/self-oss-instruct-sc2-concepts
import math def shannon_entropy(p): """Computes the Shannon Entropy at a distribution in the simplex.""" s = 0. for i in range(len(p)): try: s += p[i] * math.log(p[i]) except ValueError: continue return -1.*s
bigcode/self-oss-instruct-sc2-concepts
import torch def Ax(A, x): """Returns the Matrix-vector product Ax. Arguments: A (function or torch.Tensor): Matrix-vector product function or explicit matrix. x (torch.Tensor): A vector. """ if callable(A): Ax = A(x) else: Ax = torch.mm(A, x) ...
bigcode/self-oss-instruct-sc2-concepts
def create_pad(size, pad_id): """ Create a padding list of a given size Args: size: nd list shape pad_id: padding index Returns: - padding list of the given size """ if len(size) == 1: return [pad_id for _ in range(size[0])] else: return [create_pad(...
bigcode/self-oss-instruct-sc2-concepts
def get_file_data(path): """ read data from a given file :param path: file path :return: file data """ data = "" try: _file = open(path, 'r') data = _file.read() _file.close() except EnvironmentError as e: print("File operation failed, Error: %s" % e) ...
bigcode/self-oss-instruct-sc2-concepts
def roi_center(roi): """Return center point of an ``roi``.""" def slice_center(s): return (s.start + s.stop) * 0.5 if isinstance(roi, slice): return slice_center(roi) return tuple(slice_center(s) for s in roi)
bigcode/self-oss-instruct-sc2-concepts
import textwrap def ssplit(str_, length=420): """ Splits a into multiple lines with a maximum length, without breaking words. :param str_: The string to split. :param length: Maximum line length. """ buf = list() for line in str_.split('\n'): buf.extend(textwrap.wrap(line.rstr...
bigcode/self-oss-instruct-sc2-concepts
import pickle def read_magnitude_catalogue(pkl_data_fname): """Function to read magnitude catalogue output by get_event_moment_magnitudes() into python. Arguments: Required: pkl_data_fname - The filename of the python dict containing the magnitudes information. This is an outp...
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def get_fine_regions(columns, min_samples=50): """ Select regions that have at least ``min_samples`` samples. Remaining regions will be coarsely aggregated up to country level. """ # Count number of samples in each subregion. counts = Counter() for location in co...
bigcode/self-oss-instruct-sc2-concepts
def check_consecutive(labels): """ Check that the input labels are consecutive and start at zero. """ diff = labels[1:] - labels[:-1] return (labels[0] == 0) and (diff == 1).all()
bigcode/self-oss-instruct-sc2-concepts
def merge_dicts(*args, **kwargs): """Outputs a merged dictionary from inputs. Overwrites data if there are conflicts from left to right. :param args: (dict), tuple of input dictionaries :param kwargs: dict, input kwargs to merge :return: dict, combined data. """ data = {} for input_dict in ...
bigcode/self-oss-instruct-sc2-concepts
import random def random_tour(num_of_cities): """ Returns a random valid tour """ tour = list(range(num_of_cities)) random.shuffle(tour) return tour
bigcode/self-oss-instruct-sc2-concepts
import six def clear_dict_empty_lists(to_clear_dict): """ Removes entries from a nested dictionary which are empty lists. param to_clear_dict dict: python dictionary which should be 'compressed' return new_dict dict: compressed python dict version of to_clear_dict Hints: recursive """ ne...
bigcode/self-oss-instruct-sc2-concepts
def per_hour_to_per_second(per_hour): """ Transform a per hour rate to a per second rate. :param per_hour: quantity per hour """ return per_hour / 3600
bigcode/self-oss-instruct-sc2-concepts
def decide_produced(desc): """Based on the provided description, determine the ActivityProducedBy.""" if 'Production' in desc: return desc.split('Production')[0].strip() return 'None'
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def preprocess(text): """ Converts any puctuation into tokens, creates a counter dictionary of the data, and trims the data dictionary of words with occurrances less than five Input: * text: a text file containing words Output: * returns a trimmed counter dictionary of tokeniz...
bigcode/self-oss-instruct-sc2-concepts
def shekel_gradient(point, p, matrix_test, C, b): """ Compute Shekel gradient at a given point with given arguments. Parameters ---------- point : 1-D array with shape (d, ) A point used to evaluate the gradient. p : integer Number of local minima. matrix_test : 3-D arra...
bigcode/self-oss-instruct-sc2-concepts