seed
stringlengths
1
14k
source
stringclasses
2 values
def LCross(S1,S2): """ S1 and S2 are two element tuples of two element tuples of x,y coordinates of the two lines: Routine to check if two line segments intersect returns 0 if they don't intersect, 1 if they intersect """ ((px1,py1),(px2,py2)) = S1 ((px3,py3),(px4,py4)) = S2 # First some utility f...
bigcode/self-oss-instruct-sc2-concepts
import csv def parse_csv(csv_file): """Parses an individual CSV file into a set of data points Args: csv_file (File): a csv file Returns: List[List[int,int,float]]: A list of data points. Each data points consist of ...
bigcode/self-oss-instruct-sc2-concepts
def set_whole_node_entry(entry_information): """Set whole node entry Args: entry_information (dict): a dictionary of entry information from white list file Returns: dict: a dictionary of entry information from white list file with whole node settings """ if "submit_attrs" in entry_...
bigcode/self-oss-instruct-sc2-concepts
import imp def ModuleAvailability(module_name): """ Checks if a module is installed/available on the current system. Args: module_name: [str] name of the module to check for availability. Returns: A boolean indicating whether the module is available. """ try: imp.fin...
bigcode/self-oss-instruct-sc2-concepts
def transform_test(true, pred): """Transform true and predicted raster data sets to flat arrays. Parameters ---------- true : array-like Testing data set raster as a 2D NumPy array. pred : array-like Predicted values as a 2D NumPy array. Returns ------- y_true : arr...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def hash_pass(password, salt): """Returns the hash of `password` with salt `salt`""" return hashlib.pbkdf2_hmac('sha512', password.encode(), salt, 100000)
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def is_false_schema(schema: Any) -> bool: """True if the value of `schema` is the always reject schema. The `false` schema forbids a given value. For writers this means the value is never produced, for readers it means the value is always rejected. >>> is_false_schema(parse_js...
bigcode/self-oss-instruct-sc2-concepts
def get_tfidf_score(tf_vocab, idf_vocab): """Calculate the tfidf score for an article :param tf_vocab: a dict that maps a word into its tf value :param idf_vocab: a dict that maps a word into its idf value :returns: a list of tuple, where the first element is the word, the second element i...
bigcode/self-oss-instruct-sc2-concepts
def format_output(header, content): """ Formatted the result header and content, separated by double newlines. """ if content is not None: if type(content) == str: content = [content] return "\n\n".join([header, *content]) else: return header
bigcode/self-oss-instruct-sc2-concepts
import codecs def _get_encoding(enc, read=False): """Check if encoding exists else return utf-8.""" try: codecs.lookup(enc) except LookupError: enc = 'utf-8' # If reading utf-8, lets just read with utf-8-sig # so we don't have to worry about an accidental BOM if read and enc....
bigcode/self-oss-instruct-sc2-concepts
def get_tensor_data(tensor_data_array, tensor_name): """Find the tensor data for this tensor by its name.""" for i in range(len(tensor_data_array.data_array)): if tensor_data_array.data_array[i].name == tensor_name: return tensor_data_array.data_array[i] return None
bigcode/self-oss-instruct-sc2-concepts
def is_identical_aggregation(aggr_x: dict, aggr_y: dict) -> bool: """ Checks whether two aggregated signals are identical Both signals are checked on and therefore *must* contain the following keys: - type - subject - handler :param aggr_x: Aggregation x :param aggr_y: Aggregation y ...
bigcode/self-oss-instruct-sc2-concepts
def collect_defines(file_name): """ Collect all XCB defines from file. """ defines = [] with open(file_name, "r") as f: for line in f.readlines(): line = line.strip() if not line.startswith("#define XCB"): continue defines.append(line) ...
bigcode/self-oss-instruct-sc2-concepts
def MMAX_POSITION_FROM_ID(ID): """ Extract the position from a MMAX ID """ return int(str(ID).split('_')[-1])
bigcode/self-oss-instruct-sc2-concepts
def unpad(img, pads): """ img: numpy array of the shape (height, width) pads: (x_min_pad, y_min_pad, x_max_pad, y_max_pad) @return padded image """ (x_min_pad, y_min_pad, x_max_pad, y_max_pad) = pads height, width = img.shape[:2] return img[y_min_pad:height - y_max_pad, x_min_pad:width ...
bigcode/self-oss-instruct-sc2-concepts
def token_in_list_ignore_case(token: str, list_check: list) -> bool: """Function that checks if the given token is in the list of tokens ignoring the case. Args: token: Token to be searched in the list. list_check: List of tokens within which to search. Returns: Boolean value: ...
bigcode/self-oss-instruct-sc2-concepts
def remove(base, string): """Remove a substring from a string""" return base.replace(string, '')
bigcode/self-oss-instruct-sc2-concepts
def sum_to_num(max_number): """ Returns the sum from 0 to max_number inclusive. >>> from gender_novels.testing import tests >>> x = tests.sum_to_num(3) >>> x 6 >>> x = tests.sum_to_num(100) >>> x 5050 """ sum_result = 0 for n in range(max_number + 1): sum_result...
bigcode/self-oss-instruct-sc2-concepts
def recombination(temperature): """ Calculates the case-B hydrogen recombination rate for a gas at a certain temperature. Parameters ---------- temperature (``float``): Isothermal temperature of the upper atmosphere in unit of Kelvin. Returns ------- alpha_rec (``float``): ...
bigcode/self-oss-instruct-sc2-concepts
def all_of(pred, iterable): """ Returns ``True`` if ``pred`` returns ``True`` for all the elements in the ``iterable`` range or if the range is empty, and ``False`` otherwise. >>> all_of(lambda x: x % 2 == 0, [2, 4, 6, 8]) True :param pred: a predicate function to check a value from th...
bigcode/self-oss-instruct-sc2-concepts
def distance(coord_a, coord_b): """ Calcuate the distance between 2 coordinates. Arguments: coord_a (array): coordinate of point a coord_b (array): coordinate of point b Return: dist (float) """ assert len(coord_a) == len(coord_b) dim = len(coord_a) sum_square_d...
bigcode/self-oss-instruct-sc2-concepts
import math def parallax( emission1: float, gndaz1: float, emission2: float, gndaz2: float ) -> float: """Returns the parallax angle between the two look vectors described by the emission angles and sub-spacecraft ground azimuth angles. Input angles are assumed to be radians, as is the return v...
bigcode/self-oss-instruct-sc2-concepts
def _time_string(minutes): """Time D-hh:mm:ss format.""" minutes = max(minutes, 0) seconds = int(round((minutes % 1) * 60)) hours, minutes = divmod(int(minutes), 60) return f'{hours:02}:{minutes:02}:{seconds:02}'
bigcode/self-oss-instruct-sc2-concepts
def ackermann(m: int, n: int) -> int: """Implement Ackermann function recursively. Raise: - TypeError for given non integers - ValueError for given negative integers """ if type(m) is not int or type(n) is not int: raise TypeError("m and/or n isn't integer") if m < 0 or n < 0: ...
bigcode/self-oss-instruct-sc2-concepts
def validate_unit(unit: str) -> str: """ Validates the unit of an object. :param unit: The unit of the object. :return: The validated unit. """ if not unit: raise ValueError("Unit must not be empty.") if len(unit) > 100: raise ValueError("Unit must not be longer than 100 cha...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable from typing import Set import click from typing import Union from typing import Optional def make_existing_cluster_id_option( existing_cluster_ids_func: Callable[[], Set[str]], ) -> Callable[[Callable[..., None]], Callable[..., None]]: """ Return a Click option for choosing an ...
bigcode/self-oss-instruct-sc2-concepts
def wcPy(f): """Count up lines in file 'f'.""" return sum(1 for l in f)
bigcode/self-oss-instruct-sc2-concepts
def pop(array, index=-1): """Remove element of array at `index` and return element. Args: array (list): List to pop from. index (int, optional): Index to remove element from. Defaults to ``-1``. Returns: mixed: Value at `index`. Warning: `array` is modified...
bigcode/self-oss-instruct-sc2-concepts
def get_tags(html_soup): """ Extracts keywords of the article from content Input : Content in BeautifulSoup format Output : List of keywords of the article """ tags = html_soup.findAll('a', attrs = {"class" : "tag"}) all_tags = [] for i in tags: all_tags.append(i.get_text())...
bigcode/self-oss-instruct-sc2-concepts
def bprop_sub(x, y, dz): """Backpropagator for primitive `sub`.""" return (dz, -dz)
bigcode/self-oss-instruct-sc2-concepts
def load_input(filename): """ Load input ciphertext """ with open(filename) as f: return [int(token) for token in f.readlines()[0].strip().split(",")]
bigcode/self-oss-instruct-sc2-concepts
def get_unique_name(new_name, name_list, addendum='_new'): """ Utility function to return a new unique name if name is in list. Parameters ---------- new_name : string name to be updated name_list: list list of existing names addendum: string addendum appended to new...
bigcode/self-oss-instruct-sc2-concepts
def twitter_id_from_timestamp(ts: float) -> int: """Get twitter id from timestamp Args: ts (float): time stamp in seconds Returns: int: twitter id representing the timestamp """ return (int(ts * 1000) - 1288834974657) << 22
bigcode/self-oss-instruct-sc2-concepts
def node_vertex_name(mesh_node, vertex_id): """ Returns the full name of the given node vertex :param mesh_node: str :param vertex_id: int :return: str """ return '{}.vtx[{}]'.format(mesh_node, vertex_id)
bigcode/self-oss-instruct-sc2-concepts
def AES_read_key(filepath): """Read in the key to use for encryption / decryption""" fh = open(filepath, 'r') # read and encode to bytes key = fh.read().encode("utf-8")[0:32] fh.close() return key
bigcode/self-oss-instruct-sc2-concepts
def get_user_input(question='Enter your transaction amount: '): """ Returns the user input Parameters ---------- question : str The question the user sees """ return float(input(question))
bigcode/self-oss-instruct-sc2-concepts
def is_int(arange): """ Check if a range is int Args: test_range ([int/float, int/float]): range to test Returns: .boolean """ if (isinstance(arange[0], int) and isinstance(arange[1], int)): return True return False
bigcode/self-oss-instruct-sc2-concepts
import re def GetExamplesTextFromDocOptText(DocOptText): """Get script usage example lines from a docopt doc string. The example text line start from a line containing `Examples:` keyword at the beginning of the line. Arguments: DocOptText (str): Doc string containing script usage examples l...
bigcode/self-oss-instruct-sc2-concepts
def two_sided_midpoint_PV(dist, s, out_dir, PVs_file): """ two-sided midpoint PV - Hohna et al. 2017 :param dist: simulated distributions :param s: current original statistic to compare :param out_dir: where to write results to :param PVs_file: the calculated two-sided midpoint p-values :ret...
bigcode/self-oss-instruct-sc2-concepts
def _repr_column_dict(dumper, data): """ Represent ColumnDict in yaml dump. This is the same as an ordinary mapping except that the keys are written in a fixed order that makes sense for astropy table columns. """ return dumper.represent_mapping(u'tag:yaml.org,2002:map', data)
bigcode/self-oss-instruct-sc2-concepts
def _dict_of_targetid(submitid, charid, journalid): """ Given a target of some type, return a dictionary indicating what the 'some type' is. The dictionary's key will be the appropriate column on the Report model. """ if submitid: return {'target_sub': submitid} elif charid: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict def _normalise_map(unformatted_map: List[List[str]]) -> Dict[str, str]: """Input format: [[value1,key1,key2],[value2,key4]] Output format: {key1:value1, key2: value1, key3:value2}""" normalised_map = {} for group in unformatted_map: value = grou...
bigcode/self-oss-instruct-sc2-concepts
def get_class_name(node): """ Simple wrapper to get a _class knob off a node so that you can use standard nuke nodes like group, NoOp etc, but give them their own "class". Args: node (nuke.Node): A node object we want to get a class from. Returns: str: The node class. """ ...
bigcode/self-oss-instruct-sc2-concepts
import torch def categorical_accuracy(y, y_pred): """Calculates categorical accuracy. # Arguments: y_pred: Prediction probabilities or logits of shape [batch_size, num_categories] y: Ground truth categories. Must have shape [batch_size,] """ return torch.eq(y_pred.argmax(dim=-1), y).s...
bigcode/self-oss-instruct-sc2-concepts
def remove_stop_words(input_str): """Removes stop words from query string""" remove_list = ['a', 'an', 'and', 'of', 'as', 'in', 'for', 'on', 'the', 'near', 'not', 'to', 'is'] word_list = input_str.split() cleaned_str = ' '.join([i for i in word_list if i.lower() not in remove_list]) return cleaned_s...
bigcode/self-oss-instruct-sc2-concepts
def turc(tmean, rs, rh, k=0.31): """Evaporation calculated according to [turc_1961]_. Parameters ---------- tmean: pandas.Series average day temperature [°C] rs: pandas.Series incoming solar radiation [MJ m-2 d-1] rh: pandas.Series mean daily relative humidity [%] k:...
bigcode/self-oss-instruct-sc2-concepts
import math def rms_error(seq1, seq2): """Returns the RMS error between two lists of values""" assert len(seq1) == len(seq2) return math.sqrt(sum((x - y) ** 2 for x, y in zip(seq1, seq2)) / len(seq1))
bigcode/self-oss-instruct-sc2-concepts
def get_sample_rate(header): """ get sample frequency from header """ sample_rate = int(header[0].strip().split()[2]) return sample_rate
bigcode/self-oss-instruct-sc2-concepts
def _any_trits(left: int, right: int) -> int: """ Adds two individual trits together and returns a single trit indicating whether the result is positive or negative. """ res = left + right return (res > 0) - (res < 0)
bigcode/self-oss-instruct-sc2-concepts
def fields_allocation(MINUTES=200, size=5): """ Allocate an empty fields value with "." everywhere """ return [ [["." for _ in range(size)] for _ in range(size)] for _ in range(MINUTES * 2 + 3) ]
bigcode/self-oss-instruct-sc2-concepts
def get_task_from_request_form(request): """ Parses a request from the API endpoint attempting to extract the JSON information and transform it on a python dict Returns ------- dict a dictionary obtained from the provided json Raises ------ ValueError If a required ...
bigcode/self-oss-instruct-sc2-concepts
def format_sentences_BERT(_row,weak_supervision=False): """ Given dataframe input row, formats input sentence for tokenization: appends context to each sentence (repeats target word if weak_supervision) and appends [CLS] and [SEP] tags. """ if not weak_supervision: return '[CLS] '+_row.lo...
bigcode/self-oss-instruct-sc2-concepts
import re def getFuncNames(funcNamesStr): """ Gets a list of function names from the string provided, where the function names are separated by whitespaces or commas. Arguments: funcNamesStr: String of function names. Returns: List of function names in the string. ...
bigcode/self-oss-instruct-sc2-concepts
def fix_encoding(training_data): """Fix utf-8 file encoding after word2phrase mangles it (happens sometimes). :param training_data: file containing text with encoding that needs fixing :return: filename of repaired text file """ out_fname = training_data.replace('.txt', '.utf-8.txt') with open(...
bigcode/self-oss-instruct-sc2-concepts
def insert (source_str, insert_str, pos): """ Inserts insert_str at source_str[pos], displacing the rest.""" if pos == 0: source_str = insert_str + source_str[pos:] else: source_str = source_str[:pos] + insert_str + source_str[pos:] return source_str
bigcode/self-oss-instruct-sc2-concepts
def get_alg_shortcode(alg_str): """ Get shortcode for the models, passed in as a list of strings """ if alg_str == "adahedged": return "ah" else: return alg_str
bigcode/self-oss-instruct-sc2-concepts
def _get_pdr_module_dict(ps_data, module_id, key_name=None): """ Returns the first occurrence of a module entry from PDR participant data for the specified module_id :param ps_data: A participant data dictionary (assumed to contain a 'modules' key/list of dict values) :param module_id: The name / ...
bigcode/self-oss-instruct-sc2-concepts
def num_params(model): """ Function that outputs the number of total and trainable paramters in the model. """ numTotalParams = sum([params.numel() for params in model.parameters()]) numTrainableParams = sum([params.numel() for params in model.parameters() if params.requires_grad]) return numTot...
bigcode/self-oss-instruct-sc2-concepts
def rowcol_to_cell(row, col, row_abs=False, col_abs=False): """Convert numeric row/col notation to an Excel cell reference string in A1 notation. """ d = col // 26 m = col % 26 chr1 = "" # Most significant character in AA1 if row_abs: row_abs = '$' else: row_abs = ''...
bigcode/self-oss-instruct-sc2-concepts
def autolabel(dropdown): """Automatically set Dropdown label on_click""" def callback(event): for label, _value in dropdown.menu: if event.item == _value: dropdown.label = label dropdown.on_click(callback) return callback
bigcode/self-oss-instruct-sc2-concepts
import re def caml_to_snake(word): """Convert a string written in CamlCase to a string written in snake_case. Args: word (str): Input string. Returns: str: Output string. """ return re.sub(r'(?<!^)(?=[A-Z])', '_', word).lower()
bigcode/self-oss-instruct-sc2-concepts
import itertools import random import socket def find_open_port(ip, port, n=50): """Find an open port near the specified port""" ports = itertools.chain((port + i for i in range(n)), (port + random.randint(-2 * n, 2 * n))) for port in ports: s = socket.socket(socket.AF...
bigcode/self-oss-instruct-sc2-concepts
import types def patch_method(obj): """ Patch method for given class or object instance. If a class is passed in, patches ALL instances of class. If an object is passed in, only patches the given instance. """ def decorator(method): if not isinstance(obj, object): raise Va...
bigcode/self-oss-instruct-sc2-concepts
def _nullable_list_symmetric_difference(list_1, list_2): """ Returns the symmetric difference of 2 nullable lists. Parameters ---------- list_1 : `None` or `list` of ``DiscordEntity`` First list. list_2 : `None` or `list` of ``DiscordEntity`` First list. Returns ...
bigcode/self-oss-instruct-sc2-concepts
import re def nmap_handle_special(tmp_file): """ This function returns the open ports from nmap scan output file :param tmp_file: the file to grep open ports from :return: a list of open ports """ for line in open(tmp_file): if "Ports" in line: line = line.split("Ports")[1]...
bigcode/self-oss-instruct-sc2-concepts
def pycode(msg: str): """Format to code block with python code highlighting""" return f'```py\n{msg}```'
bigcode/self-oss-instruct-sc2-concepts
def list_user_policies(iam_client, user): """ List IAM user policies """ return iam_client.list_user_policies(UserName=user)
bigcode/self-oss-instruct-sc2-concepts
def bit(value: int, byte: int, position: int) -> int: """Encode a bit value :param value: Value to encode :param byte: The byte to apply the value to :param position: The position in the byte to set the bit on """ return byte | (value << position)
bigcode/self-oss-instruct-sc2-concepts
def is_DER_sig(sig: bytes) -> bool: """Checks if the data is a DER encoded ECDSA signature https://bitcoin.stackexchange.com/questions/92680/what-are-the-der-signature-and-sec-format :param sig: Potential signature. :type sig: bytes :return: True if the passed in bytes are an ECDSA signature in ...
bigcode/self-oss-instruct-sc2-concepts
def make_safe_for_html(html): """Turn the text `html` into a real HTML string.""" html = html.replace("&", "&amp;") html = html.replace(" ", "&nbsp;") html = html.replace("<", "&lt;") html = html.replace("\n", "<br>") return html
bigcode/self-oss-instruct-sc2-concepts
def handle_command_line(argument_parser): """ Take command line arguments, check for issues, return the arguments. Args: `argument_parser` (`argparse.ArgumentParser`): The argument parser that is \ returned in `create_cmd_arguments()`. Returns: (`argparse.NameSpace`): c...
bigcode/self-oss-instruct-sc2-concepts
import csv def write_output_csv(output_csv_path, data, csv_type): """ Accepts a dictionary of rows and writes a new CSV Columns should be: ID, chromosome_name, start_position, end_position, strand, padj, log2FoldChange """ count = 1 # Open a second output file and write only unique rows w...
bigcode/self-oss-instruct-sc2-concepts
def add_edge(locations,edge): """ Add edge to list of locations, returning a list of edge-added locations """ if edge != None: return [tuple([i+j for i,j in zip(edge,l)]) for l in locations] return locations
bigcode/self-oss-instruct-sc2-concepts
def winning_player(players, payoffs): """ The index of a winning player from a pair of payoff values Parameters ---------- players : tuple A pair of player indexes payoffs : tuple A pair of payoffs for the two players Returns ------- integer The index of the...
bigcode/self-oss-instruct-sc2-concepts
def ClassicalRegister_to_c(self): """Syntax conversion for creating a classical register.""" return f'int {self.name}[{self.size}];'+"\n"+f'for (int i = 0; i < {self.size}; i++) {self.name}[i] = 0;'
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup from datetime import datetime def parse_html(html): """Parse FX html, return date and dict of {symbol -> rate}""" soup = BeautifulSoup(html, 'html.parser') # <h4>Date: <i class="date">2019-11-11</i></h4> i = soup('i', {'class': 'date'}) if not i: raise ValueE...
bigcode/self-oss-instruct-sc2-concepts
def document_config_types(agent_config_dict): """ Returns a single string containing all available config types, for Docs team to reference. """ return 'Available config types: \n\n' + '\n'.join(agent_config_dict.keys())
bigcode/self-oss-instruct-sc2-concepts
def calc_gc(sequence): """ Calculates GC percentage from DNA sequence Does not consider IUPAC ambiguity codes :param sequence: :return: float """ if len(sequence) == 0: raise ValueError("Sequence must have minimum length 1") gc = 0 for char in sequence: if char.upper(...
bigcode/self-oss-instruct-sc2-concepts
def line_preformatter(line: str) -> str: """Preformats a line to be better readable by `ast.literal_eval()` Args: line (str): Input String from SQL File Returns: str: Formatted string with special replacements """ # <!-- Clear comments --> #line = line[:line.find('--')] # <...
bigcode/self-oss-instruct-sc2-concepts
def hex_switchEndian(s): """ Switches the endianness of a hex string (in pairs of hex chars) """ pairList = [s[i:i+2].encode() for i in range(0, len(s), 2)] return b''.join(pairList[::-1]).decode()
bigcode/self-oss-instruct-sc2-concepts
def _AndroidAbiToCpuArch(android_abi): """Return the Chromium CPU architecture name for a given Android ABI.""" _ARCH_MAP = { 'armeabi': 'arm', 'armeabi-v7a': 'arm', 'arm64-v8a': 'arm64', 'x86_64': 'x64', } return _ARCH_MAP.get(android_abi, android_abi)
bigcode/self-oss-instruct-sc2-concepts
def wait_for_task(task): """ wait for a vCenter task to finish """ task_done = False while not task_done: if task.info.state == 'running': pass if task.info.state == 'success': return task.info.result if task.info.state == 'error': print ("there ...
bigcode/self-oss-instruct-sc2-concepts
import itertools def groupby(itr, key_fn=None): """ An wrapper function around itertools.groupby to sort each results. :param itr: Iterable object, a list/tuple/genrator, etc. :param key_fn: Key function to sort `itr`. >>> import operator >>> itr = [("a", 1), ("b", -1), ("c", 1)] >>> res...
bigcode/self-oss-instruct-sc2-concepts
def cropping_center(x, crop_shape, batch=False): """Crop an input image at the centre. Args: x: input array crop_shape: dimensions of cropped array Returns: x: cropped array """ orig_shape = x.shape if not batch: h0 = int((orig_shape[0] - crop_shape[0])...
bigcode/self-oss-instruct-sc2-concepts
from typing import List import inspect def _get_function_params(function) -> List[str]: """ Returns the list of variables names of a function :param function: The function to inspect :rtype: List[str] """ parameters = inspect.signature(function).parameters bound_arguments = [ name...
bigcode/self-oss-instruct-sc2-concepts
def ith_bit(x: int, i: int) -> int: """ Return the i-th bit of the input parameter. LSB has index 0, MSB has the greatest index (31 for a word). :param x: A number. :param i: The bit index. :return: The ith-bit of x. """ assert i >= 0 # Do not support negative indexes, ATM return (...
bigcode/self-oss-instruct-sc2-concepts
def base_name(var): """Extracts value passed to name= when creating a variable""" return var.name.split('/')[-1].split(':')[0]
bigcode/self-oss-instruct-sc2-concepts
def _split_value_units(raw_str): """Take a string with a numerical value and units, and separate the two. Args: raw_str (str): the string to parse, with numerical value and (optionally) units. Returns: A tuple (value, units), where value is a string and units is either ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def get_media_insert(media, event): """ Gets all insertion data for a single media object Parameters ---------- media: dict Dictionary object of a media object event: str Event name of query the media was retrieved from Returns ------- ...
bigcode/self-oss-instruct-sc2-concepts
def lotkavolterra(y, t=0, a=1, b=1, c=1, d=1): """Lotka-Volterra predator prey model """ prey, pred = y dydt = [a * prey - b * pred * prey, c * pred * prey - d * pred] return dydt
bigcode/self-oss-instruct-sc2-concepts
def extract_from_dict(data, path): """ Navigate `data`, a multidimensional array (list or dictionary), and returns the object at `path`. """ value = data try: for key in path: value = value[key] return value except (KeyError, IndexError): return ''
bigcode/self-oss-instruct-sc2-concepts
import requests def get_current_version(election_id: str, state_code: str) -> str: """Checks the base website to get the current data version number for later data download""" current_version_url = f"https://results.enr.clarityelections.com//{state_code}/{election_id}/current_ver.txt" r = requests.g...
bigcode/self-oss-instruct-sc2-concepts
import torch def get_constraint(w, reg_type=1, beta=0.7): """ Input: - w (1D torch tensor): weights - reg_type (integer): id for the type of regularization - beta (float): beta for regularization corresponding to reg_type=2 Output: - Values of the regularization constraint (reg_value)...
bigcode/self-oss-instruct-sc2-concepts
import time def random_time_range(start, end, file_format, prop): """Get a time at a proportion of a range of two formatted times. start and end should be strings specifying times formated in the given format (strftime-style), giving an interval [start, end]. prop specifies how a proportion of the in...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def update_date_of_sale(date_input): """ Update date format from DD/MM/YYYY to YYYY-MM-DD """ current_format = datetime.strptime(date_input, "%d/%m/%Y") new_format = current_format.strftime("%Y-%m-%d") return new_format
bigcode/self-oss-instruct-sc2-concepts
import time def decode_tag(tag, time_format): """ Return prefix and time represented by playlist tag. Args: tag ::: (str) playlist tag to decode time_format ::: (str) format specifier for `time.strftime` see http://strftime.org/ Returns: prefix ::: (str) un...
bigcode/self-oss-instruct-sc2-concepts
def inclusion_one_param_from_template(arg): """Expected inclusion_one_param_from_template __doc__""" return {"result": "inclusion_one_param_from_template - Expected result: %s" % arg}
bigcode/self-oss-instruct-sc2-concepts
import yaml def load_config(config_path): """ Loads a YAML config file and returns data as a nested dictionary. """ with open(config_path, 'r') as f: config = yaml.safe_load(f) return config
bigcode/self-oss-instruct-sc2-concepts
def merge(items1, items2): """Merge given lists of items, each assumed to already be in sorted order, and return a new list containing all items in sorted order. Running time: O(n) Passes over each element once Memory usage: O(n) Makes a new list for all the elements """ ind_1, ind_2 = 0, 0 ...
bigcode/self-oss-instruct-sc2-concepts
def compose1(f, g): """"Return a function h, such that h(x) = f(g(x)).""" def h(x): return f(g(x)) return h
bigcode/self-oss-instruct-sc2-concepts