seed
stringlengths
1
14k
source
stringclasses
2 values
def csv2json(csvdata, header=True): #----------------------------------------<<< """Convert CSV data to JSON (i.e., list of dictionaries). csvdata = string containing a CSV file e.g., open('filename.csv').read() header = whether the data contains a header row (if not, output fields ...
bigcode/self-oss-instruct-sc2-concepts
def range_check(low, high): """\ Verifies that that given range has a low lower than the high. >>> range_check(10, 11) (10.0, 11.0) >>> range_check(6.4, 30) (6.4, 30.0) >>> try: ... range_check(7, 2) ... except ValueError as e: ... print(e) ...
bigcode/self-oss-instruct-sc2-concepts
import pytz def utc_to_local(user, utc_dt): """ Turn a date into a date matching use timezone. It's useful when you need to display a date. """ local_tz = pytz.timezone(user["timezone"]) local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz) return local_tz.normalize(local_dt)
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def add_day_month(df): """Creates columns for the Day, Day int value, and the Month Args: df (pandas.DataFrame): The original pandas dataframe Returns: df (pandas.DataFrame): The pandas dataframe with the DAY, DAY_NUM, and MONTH columns """ df['DAY'...
bigcode/self-oss-instruct-sc2-concepts
def newalpha(img, alpha): """ Multiplication of image alpha channel and alpha :param img: PIL.Image :param alpha: float :return: PIL.Image """ out = img.copy() a = img.getchannel('A') a = a.point(lambda i: i * alpha) out.putalpha(a) return out
bigcode/self-oss-instruct-sc2-concepts
from typing import List import random def load_paragraphs_from_files(file_name_list: List[str], shuffled: bool=True): """ This function loads paragraphs from multiple files. A paragraph is just a string. It can, but does not need to contain multiple sentences. The function takes a list of file nam...
bigcode/self-oss-instruct-sc2-concepts
def start_new_game(player1, player2): """ Creates and returns a new game configuration. """ board = [['-']*3 for _ in range(3)] game = { 'player1': player1, 'player2': player2, 'board': board, 'next_turn': player1, 'winner': None } return game
bigcode/self-oss-instruct-sc2-concepts
def key_for_value(dictionary, value): """finds the key for a given value in a dict.""" return list(dictionary.keys())[list(dictionary.values()).index(value)]
bigcode/self-oss-instruct-sc2-concepts
import re def natural_sort(lst): """Sort a list in natural order.""" def key(s): return [int(t) if t.isdigit() else t.lower() for t in re.split(r'(\d+)', str(s))] return sorted(lst, key=key)
bigcode/self-oss-instruct-sc2-concepts
def split_semicolon(text): """Split lines by semicolon Useful to manage path in windows or email names >>> split_semicolon('Jean;Jane; John') 'Jean\\nJane\\nJohn' """ return text.replace("; ", "\n").replace(";", "\n")
bigcode/self-oss-instruct-sc2-concepts
import re def is_canonical(version): """Check if a version string is in canonical format of PEP 440.""" # Source: https://www.python.org/dev/peps/pep-0440 pattern = ( r'^([1-9][0-9]*!)?(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))' r'*((a|b|rc)(0|[1-9][0-9]*))?(\.post(0|[1-9][0-9]*))' r'?(\.d...
bigcode/self-oss-instruct-sc2-concepts
def dasherize(text): """Replace underscores with hyphens.""" return text.replace('_', '-')
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Tuple def read_data() -> List[Tuple[str, int]]: """ Read list of people and how much did they pay :return: List[name, how much money did he / she gave] """ print('Enter names and amounts of money in format of "Jack: 1984"' 'If man didn\'t pay an...
bigcode/self-oss-instruct-sc2-concepts
import typing def atoi(text: str) -> typing.Union[int, str]: """returns numeric representation of text if possible else original text Parameters ---------- text: str text whose numeric representation is needed Returns ------- typing.Union[int, str] the integer representat...
bigcode/self-oss-instruct-sc2-concepts
import yaml import collections def ParseMappingAsOrderedDict(enable=True, loader=yaml.Loader, dumper=yaml.Dumper): """Treat OrderedDict as the default mapping instance. While we load a yaml file to a object, modify the object, and dump to a yaml file,...
bigcode/self-oss-instruct-sc2-concepts
def lerp(x, x0, x1, y0, y1): """ Linearly interpolate between points (x0, y0) and (x1, y1) to get the value of y at x. :param x: :param x0: :param x1: :param y0: :param y1: :return: """ t = (x - x0) / (x1 - x0) return (1 - t) * y0 + t * y1
bigcode/self-oss-instruct-sc2-concepts
def container_to_string(cont): """Convert a container to a command line string. Elements of the container are joined with a space between them, suitable for a command line parameter. If the container `cont` is only a sequence, like a string and not a container, it is returned unmodified. Para...
bigcode/self-oss-instruct-sc2-concepts
def verifyRasterNum(alg, parameters, context, rasters, mini, maxi=None): """Verify that we have at least n rasters in multipleInput""" num = len(alg.parameterAsLayerList(parameters, rasters, context)) if num < mini: return False, 'You need to set at least {} input rasters for this algorithm!'.format...
bigcode/self-oss-instruct-sc2-concepts
import pathlib def grab_files_from_dir(input_path, file_types=("*.jpg", "*.png", "*.tif")): """Grab file paths specified by file extensions. Args: input_path (str or pathlib.Path): Path to the directory where files need to be searched. file_types (str or tuple(str)): ...
bigcode/self-oss-instruct-sc2-concepts
import json def loadjson(filepath, field=None): """load a json file Parameters ---------- filepath : str The file path string. field : None, optional The string of field that want to be loaded. """ with open(filepath, 'r', encoding='utf-8') as f: if field is None:...
bigcode/self-oss-instruct-sc2-concepts
def list_datasets(print_list=True): """Print available datasets in the cptac.pancan module. Parameters: print_list (bool, optional): Whether to print the list. Default is True. Otherwise, it's returned as a string. """ datasets = [ "PancanBrca", "PancanCcrcc", "PancanCoad",...
bigcode/self-oss-instruct-sc2-concepts
def initial_check(filename): """ Check the first 4 bytes of a file for the 'magic number' and return the file endianness. If the 'magic number' is not found, the file is probably not a PSU-WOPWOP file and an error is raised. """ endianness_flag = 'little' # read first four bytes to check f...
bigcode/self-oss-instruct-sc2-concepts
def strip_base_dir(filename, base_dir): """Strip base directory from filename if it starts there. >>> strip_base_dir('/path/to/base/relpath/to/file', ... '/path/to/base/') 'relpath/to/file' >>> strip_base_dir('/path/to/somewhere/else/relpath/to/file', ... '/path/t...
bigcode/self-oss-instruct-sc2-concepts
import base64 def btoa(a): """Jinja filter to mimic JavaScript's ``btoa`` function.""" return base64.b64encode(a.encode()).decode()
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import Callable from typing import Dict from typing import Any def runner(args: Tuple[Callable, Dict[Any, Any]]) -> Any: """Runner function for process pool Args: args: A pair where the first element is the function to run and the second element is a d...
bigcode/self-oss-instruct-sc2-concepts
def format_key_list(keys_str): """ Format the key list :param keys_str: a string containing the keys separated by spaces :return: a string containing the keys ordered and separated by a coma and a space """ key_list = keys_str.split(" ") key_list.sort() return ", ".join(key_list)
bigcode/self-oss-instruct-sc2-concepts
def HealthCheckName(deployment): """Returns the name of the health check. A consistent name is required to define references and dependencies. Assumes that only one health check will be used for the entire deployment. Args: deployment: the name of this deployment. Returns: The name of the health ch...
bigcode/self-oss-instruct-sc2-concepts
import math def jd_to_weekday(jd): """Return weekday of Julian Day Return: int - weekday [1..7] where 1 is Ahad/Sunday """ return int(math.floor(jd + 1.5) % 7) + 1
bigcode/self-oss-instruct-sc2-concepts
def _branch_error_analyzer(output): """Checks if there is an error in `output` for branch creation. """ if len(output["error"]) > 0: l = output["error"][0] return "Switched to a new branch" not in l else: return False
bigcode/self-oss-instruct-sc2-concepts
def _parse_book_links(dom): """ Parse links to the details about publications from page with book list. Args: dom (obj): HTMLElement container of the page with book list. Returns: list: List of strings / absolute links to book details. """ links = [] picker = lambda x: x.pa...
bigcode/self-oss-instruct-sc2-concepts
import socket import logging def GetHostName(fully_qualified=False): """Return hostname of current machine, with domain if |fully_qualified|.""" hostname = socket.gethostname() try: hostname = socket.gethostbyaddr(hostname)[0] except (socket.gaierror, socket.herror) as e: logging.warning('please check...
bigcode/self-oss-instruct-sc2-concepts
def get_armature_modifier_rig_object(mesh_object): """ This function gets the armature associated with a mesh via its armature modifier. :param object mesh_object: A object of type mesh. :return object: A object of type armature. """ for modifier in mesh_object.modifiers: if modifier.ty...
bigcode/self-oss-instruct-sc2-concepts
import decimal def _decimal(value): """Return env var cast as Decimal.""" return decimal.Decimal(value)
bigcode/self-oss-instruct-sc2-concepts
import jinja2 def read_template(template): """ Returns a jinja template Parameters --------- template: str template file that is to be stored as variable. Returns ------- output_template: jinja template object output template that can be 'jinja.render' -ed. """ ...
bigcode/self-oss-instruct-sc2-concepts
def is_tie_bar(a_character: str) -> bool: """ Whether a character is used to tie two characters in the international phonetic alphabet together. The tie bar is usually used to indicate an affricate, or double-articulation. """ return a_character in ["͜", "͡"]
bigcode/self-oss-instruct-sc2-concepts
def max_key(dic): """ Based on https://stackoverflow.com/questions/42044090/return-the-maximum-value-from-a-dictionary Returns the key of the max value in a dictionairy """ return [k for k, v in dic.items() if v == max(dic.values())][0]
bigcode/self-oss-instruct-sc2-concepts
def strToSet(string): """ Convert a string into a set """ ens = set() for char in string: ens.add(char) return ens
bigcode/self-oss-instruct-sc2-concepts
def read64str(f): """Read 8 bytes from a file and return as an ASCII string. """ return f.read(8).decode("latin1")
bigcode/self-oss-instruct-sc2-concepts
from warnings import warn def add_attrs(remember_added_attrs=True, if_attr_exists="raise", **attrs): """Make a function that will add attributes to an obj. Originally meant to be used as a decorator of a function, to inject >>> from on.util import add_attrs >>> @add_attrs(bar='bituate', hello='world')...
bigcode/self-oss-instruct-sc2-concepts
import math def ToVVU(AxorRh): """ Convert to van Vleck Units (vvu = m3/3.77 10-35) @param AxorRh: Axial or Rhombic component @type AxorRh : float """ return AxorRh*(1./((12*math.pi))*10000)
bigcode/self-oss-instruct-sc2-concepts
def parseTR(trCode): """요청 TR 코드 파싱 :param trCode: TR 코드 :type trCode: str :return: TR코드 내역을 반환 :: parseTR("t0425") # 주식체결/미체결 """ ht = { "t0424" : "주식잔고", "t0425" : "주식체결/미체결", "t8407" : "멀티현재가조회", "t8412" : "주식챠트(N분)", ...
bigcode/self-oss-instruct-sc2-concepts
def pd_train_eval_split(df, eval_split=0.0, seed=None, reset_index=False): """Splits pandas dataframe into train/eval sets. Uses pandas DataFrame.sample to create the split. Args: df: Dataframe of examples to be split. eval_split: Float in range (0, 1), fraction of dataset to split out as eval set...
bigcode/self-oss-instruct-sc2-concepts
def find_bounds(f, y): """ Find approximate bounds for binomial search. """ x = 1 while((f(x) < y) and (x<1000483646) ): x = x * 2 lo = -100 if (x ==1): lo = -100 else: lo = x/2 if(x > 1000): x = min(x,2047483646) return lo, x
bigcode/self-oss-instruct-sc2-concepts
def get_seq(query_filepath): """ Get a sequence from a single-entry FASTA file. """ f = open(query_filepath,'r') lines = f.readlines() lines = [row.strip() for row in lines] # restituisce una copia della stringa con i caratteri iniziali e finali rimossi per le righe in fila lines = [row.repl...
bigcode/self-oss-instruct-sc2-concepts
def remap_clocks(ports, clock_map): """ Remaps clock dependencies of all ports and returns a new port map. Does not remap clocks for "P1" and "P2" ports. """ new_ports = { "input": set(), "clock": set(), "output": set(), } for key in ["input", "clock", "output"]: ...
bigcode/self-oss-instruct-sc2-concepts
def get_string_names(elems, names, label): """ Transform the list of values into a string to write elems is a dictionary with the values names is the selected keys we want for the output label is the model label """ # Start to write the output string ss = "" for name in names: ...
bigcode/self-oss-instruct-sc2-concepts
import _pickle def unpickle(fname): """Load pickled object from `fname`""" with open(fname) as f: return _pickle.loads(f.read())
bigcode/self-oss-instruct-sc2-concepts
def check_inv_exists(v, phi): """ Given a vertex id u and a set of partial isomorphisms phi. Returns True if an inverse transformation exists for v """ for _phi in phi: if _phi[1] == v: return True return False
bigcode/self-oss-instruct-sc2-concepts
import requests def post_file(input_filepath, input_format, output_format): """Posts a file to the REST API and converts between the given formats.""" with open(input_filepath) as input_file: input_text = input_file.read() url = 'http://localhost:5000/convert/{}/{}'.format( input_f...
bigcode/self-oss-instruct-sc2-concepts
def filter_by_speaker_id(queryset, speaker_id): """Filter a Quip-based queryset by Quote's Speaker's id.""" queryset = queryset.filter(quotes__speaker_id=speaker_id) return queryset
bigcode/self-oss-instruct-sc2-concepts
def convert_flat_stitch_id_to_pubchem_cid(stitch_flat_id: str) -> str: """Convert a flattened STITCH identifier (no stereochemistry) to PubChem compound identifier.""" return str(abs(int(stitch_flat_id[3:])) - 100000000)
bigcode/self-oss-instruct-sc2-concepts
def load_loglikelihood_from_hdf5_group(group): """ Loads a loglikelihood from the given hdf5 group. group: the hdf5 file group from which to load the Loglikelihood returns: Loglikelihood object of the correct type """ try: class_name = group.attrs['class'] cls = eval(cl...
bigcode/self-oss-instruct-sc2-concepts
def int_to_bitstring(n: int, desired_len=None) -> str: """Converts an integer into a bitstring (unicode representation) of desired length. MSB leftmost, LSB rightmost""" bitstring = bin(n)[2:] if desired_len: current_len = len(bitstring) assert current_len <= desired_len, 'Desired length to...
bigcode/self-oss-instruct-sc2-concepts
def q_liq_top(rho_top_liq, L_septum, L_top): """ Calculates the specific flow rate of the liquid for 1 m of drain septum Parameters ---------- rho_top_liq : float The destiny of liquid at top of column, [kg/m**3] L_top : float The flow rate of liquid at top of column, [kg/s] ...
bigcode/self-oss-instruct-sc2-concepts
def make_dict(in_text): """ Create a counter of the string """ my_dict = dict() for c in in_text: if c in [' ', '\n']: continue if c not in my_dict.keys(): my_dict[c] = 1 else: my_dict[c] += 1 return my_dict
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def to_string(byte_array: Union[bytes, bytearray]) -> str: """ convert a byte array into string :param byte_array: a latin1 encoded byte array :return: a decoded string """ string = [] for byte in byte_array: string.append(chr(byte)) return "".join(str...
bigcode/self-oss-instruct-sc2-concepts
def get_user_input(prompt: str) -> str: """ Get user answer given prompt Args: prompt (str): String with to confirm action by user Returns: str: "y" or "n" strings """ response = input(prompt) assert response in ['y', 'n'], 'Invalid input entered by user' return response
bigcode/self-oss-instruct-sc2-concepts
def combine_dicts(dict1, dict2): """ Combine two dicts into one, respecting common keys If dict1 and dict2 both have key a, then x[a] and y[a] must both be dictionaries to recursively merge. Args: dictionary1 : dict dictionary2 : dict Returns: output : dict """ outpu...
bigcode/self-oss-instruct-sc2-concepts
def examine_categoricals(df, columns=None): """ Returns (to driver memory) a list of tuples consisting of every unique value for each column in `columns` or for every categorical column in the source data if no columns are specified """ default_columns = [ "SeniorCitizen", "Par...
bigcode/self-oss-instruct-sc2-concepts
def represent(instance: object, *args, **kwargs) -> str: """ Return an appropriate representation string for the instance. >>> class Cat(object): ... def __init__(self, name, *, age=0): ... self.name, self.age = name, age ... def __repr__(self): ... return represent(self...
bigcode/self-oss-instruct-sc2-concepts
def numberp(thing): """ NUMBERP thing NUMBER? thing outputs TRUE if the input is a number, FALSE otherwise. """ return type(thing) is int or type(thing) is float
bigcode/self-oss-instruct-sc2-concepts
def get_ordered_values_from_table_by_key(table, reverse=False): """ Get value list where the value orders are determined by their keys. Args: table: a table of data reverse: value list in a reversed order Returns: - an ordered list of values """ keys = [_ for _ in table...
bigcode/self-oss-instruct-sc2-concepts
def get_backends_url(config): """Return the URL for a backend.""" hub = config.get('hub', None) group = config.get('group', None) project = config.get('project', None) if hub and group and project: return '/Network/{}/Groups/{}/Projects/{}/devices/v/1'.format(hub, group, ...
bigcode/self-oss-instruct-sc2-concepts
def depth_first_search(grid, start, target): """ Search a 2d grid for a given target starting at start. Args: grid: the input grid as a List[List] start: the start grid in format (x,y) zero index target: the target value to find in the grid Returns: Coordinate of the tar...
bigcode/self-oss-instruct-sc2-concepts
def _exam_score(review): """Returns an HTML-formatted exam score, if applicable.""" if review.type_ == "Evaluation": return u"" return u"<p>Scored %s on written exam." % review.exam_score
bigcode/self-oss-instruct-sc2-concepts
def is_unweighted(matrix): """Quick function to determine if a Matrix is likely an unweighted adjacency matrix""" return matrix[matrix.nonzero()].min() == 1 and matrix.max() == 1
bigcode/self-oss-instruct-sc2-concepts
def to_iso_8601_format(dt): """ Convert the supplied datetime instance to the ISO 8601 format as per API specs. :param dt: The datetime instance to convert. :return: Supplied datetime as timestamp in ISO 8601 format. """ if not dt: return if isinstance(dt, str): return dt ...
bigcode/self-oss-instruct-sc2-concepts
def getNamedNode(node, nodename): """ Return first named subnode of the supplied node """ subnodes = node.getElementsByTagName(nodename) if len(subnodes) > 0: return subnodes[0] return None
bigcode/self-oss-instruct-sc2-concepts
def get_lname(request): """ Returns the name of the label which has been changed :param request: incomming request :return: label name from request (String) """ return request.json['label']['name']
bigcode/self-oss-instruct-sc2-concepts
def indent(code, level): """ indent code to the given level """ return code.replace("\n", "\n" + (" "*level))
bigcode/self-oss-instruct-sc2-concepts
def keys(dictionary: dict) -> tuple: """Return a tuple of keys in a dictionary.""" return tuple(dictionary.keys())
bigcode/self-oss-instruct-sc2-concepts
def is_benign(ba, bs_terms): """Check if criterias for Benign are fullfilled The following are descriptions of Benign clasification from ACMG paper: Benign (i) 1 Stand-alone (BA1) OR (ii) ≥2 Strong (BS1–BS4) Args: ba(bool): Stand Alone term for evidence of benign impact bs...
bigcode/self-oss-instruct-sc2-concepts
import zlib def undeflate(data): """Decompresses data for Content-Encoding: deflate. (the zlib compression is used.) """ decompressobj = zlib.decompressobj(-zlib.MAX_WBITS) return decompressobj.decompress(data)+decompressobj.flush()
bigcode/self-oss-instruct-sc2-concepts
def output_modal(func, output: set): """Updates output with the result of func, a modal which returns a set. Cheap way to monitor the modal result of a bpy.Operator.""" def wrap(self, context, event): result = func(self, context, event) output.update(result) return result return...
bigcode/self-oss-instruct-sc2-concepts
import re def find_ipv6_with_subnet(string): """ Find and return IPv6 address with subnet inside a string. This function will only return an ipv6 address with a subnet :param string: (str) The string to search for ipv6 with subnet (i.e. "Successfully added Subnet 2001:420:30a:200::a10/127") ...
bigcode/self-oss-instruct-sc2-concepts
def parse_url(url: str) -> str: """ Makes sure the URL starts with 'http://' """ # Replace HTTPS with HTTP (if exists) url = url.replace("https://", "http://") if url.startswith("http://"): return url return f"http://{url}"
bigcode/self-oss-instruct-sc2-concepts
def extract(str_value, start_='{', stop_='}'): """Extract a string between two symbols, e.g., parentheses.""" extraction = str_value[str_value.index(start_)+1:str_value.index(stop_)] return extraction
bigcode/self-oss-instruct-sc2-concepts
import time def get_agg_log(db, sessionID, start='', end=''): """ Retrieve all Collection entries in a given time frame. :param db: The database object. :param sessionID: Current user's session ID. :param start: (Optional) The start of the time frame. :param end: (Optional) The end of the time...
bigcode/self-oss-instruct-sc2-concepts
def graph_to_triples(digraph, sent): """ Convert a single graph to triples """ return ["{}\t{}\t{}".format(" ".join(sent[u[0]: u[1]]), " ".join(digraph[u][v]["label"]), " ".join(sent[v[0]: v[1]])) for (u, v) in digraph.edges()]
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def weekday(date): """ Generate day of the week based on date (as string or as datetime object)""" if isinstance(date, str): date = datetime.strptime(date, "%m-%d-%Y") # change the format if necessary # "%Y-%m-%d" return date.strftime("%A")
bigcode/self-oss-instruct-sc2-concepts
def _is_macos(repository_ctx): """Determines if the host is running MacOS. Args: repository_ctx: A `repository_ctx` instance. Returns: A `bool` indicating whether the host is running MacOS. """ os_name = repository_ctx.os.name.lower() return os_name.startswith("mac os")
bigcode/self-oss-instruct-sc2-concepts
def run_episode(env, policy, gamma = 1.0, render = False): """ Runs an episode and return the total reward """ obs = env.reset() total_reward = 0 step_idx = 0 while True: if render: env.render() obs, reward, done, _ = env.step(int(policy[obs])) total_reward += (ga...
bigcode/self-oss-instruct-sc2-concepts
def get_wred_profiles(host_ans): """ Get all the WRED/ECN profiles of a SONiC switch Args: host_ans: Ansible host instance of the device Returns: WRED/ECN profiles (dictionary) or None. Example format is given below: { u'AZURE_LOSSLESS': { u...
bigcode/self-oss-instruct-sc2-concepts
def c_array_buf(ctype, buf): """Create ctypes array from a Python buffer.""" return (ctype * len(buf)).from_buffer(buf)
bigcode/self-oss-instruct-sc2-concepts
import requests def requestCourseEnroll(sess, subject, cournum): """ Get a request instance from http://www.adm.uwaterloo.ca/cgi-bin/cgiwrap/infocour/salook.pl after requesting the class enrollment data Parameters: sess: int or str subject: str cournum: int or str Ret...
bigcode/self-oss-instruct-sc2-concepts
def get_header_list(sheet): """ Get a list of header row cell values. :param sheet: :return: Returns a list of values from the first row in the sheet. """ return [c.value for c in sheet.row(0)]
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence def combine_dicts(dict_ls: Sequence[dict], strict=True, dict_class=dict): """Merges entries from one or more dicts into a single dict (shallow copy). Args: dict_ls (Sequence[dict]): sequence of dictionaries to combine. strict (bool): whether to throw an exception i...
bigcode/self-oss-instruct-sc2-concepts
def cast_keep_none(obj, dest_type: type): """ Cast ``obj`` to ``dest_type``. If ``obj`` is ``None``, returns ``None``. :param obj: object to be casted :param dest_type: target type to cast `obj` :return: casted `obj` """ if obj is None: return None if issubclass(dest_type,...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def file_hash(file_path): """Returns the SHA-1 hash of |file_path| contents.""" chunk_size = 51200 # Read in 50 KB chunks. digest = hashlib.sha1() with open(file_path, 'rb') as file_handle: chunk = file_handle.read(chunk_size) while chunk: digest.update(chun...
bigcode/self-oss-instruct-sc2-concepts
def isAlphanum(c): """return true if the character is a letter, digit, underscore, dollar sign, or non-ASCII character. """ return ((c >= 'a' and c <= 'z') or (c >= '0' and c <= '9') or (c >= 'A' and c <= 'Z') or c == '_' or c == '$' or c == '\\' or (c is not None and ord(c) > 126));
bigcode/self-oss-instruct-sc2-concepts
def _group_ccs_with_issuetracker(ccs_payload, ccs_issuetracker): """Group ccs from ggrc system and issuetracker. Args: - ccs_system: CCs on Issue Tracker Payload - ccs_tracker: CCs from Issue Tracker Returns: list of grouped ccs from ggrc and issuetracker. """ ccs_system = set(cc.strip() for c...
bigcode/self-oss-instruct-sc2-concepts
def is_prime(num): """Returns True if the number is prime else False.""" if num == 0 or num == 1: return False for x in range(2, num): if num % x == 0: return False else: return True
bigcode/self-oss-instruct-sc2-concepts
def is_clone(g): """ Return True if the generator `g` is a clone of another generator, otherwise return False. """ return g.parent is not None
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def createPositionLookup(frags, pos=1): """Create dictionary where key is subsetted fragment coords (no start or no stop), value is the list of full fragments that share the coordinates in the key. Only entries where >1 full fragments share the same coordinate are retain...
bigcode/self-oss-instruct-sc2-concepts
def is_memcpy(cluster): """ True if `cluster` emulates a memcpy and the target object is a mapped Array, False otherwise. """ return (len(cluster.exprs) == 1 and cluster.exprs[0].lhs.function.is_Array and cluster.exprs[0].lhs.function._mem_mapped and cluster.exprs...
bigcode/self-oss-instruct-sc2-concepts
import logging def info_blocref(app, doctree, fromdocname, class_name, entry_name, class_node, class_node_list): """ Log information with :epkg:`Sphinx`. @param app application (Sphinx) @param doctree document tree @param fromdocname ...
bigcode/self-oss-instruct-sc2-concepts
def contains_only(seq, aset): """ Check whether sequence seq contains ONLY items in aset. """ for c in seq: if c not in aset: return False return True
bigcode/self-oss-instruct-sc2-concepts
def compile_function(name, code, globs): """ Given a *code* string, compile it with globals *globs* and return the function named *name*. """ co = compile(code, "<string>", "exec") ns = {} eval(co, globs, ns) return ns[name]
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable from typing import Tuple def retry_fn(fn: Callable, allowable_exceptions: Tuple, retry_count: int=5): """ Call fn, retrying if exception type in allowable_exceptions is raised up to retry_count times """ for i in range(0, retry_count): try: return fn() ...
bigcode/self-oss-instruct-sc2-concepts
def last(x): """ Returns the last element of a series. Params: x (pd.Series) Returns: scalar of x.dtype """ return x.iloc[-1]
bigcode/self-oss-instruct-sc2-concepts