seed
stringlengths
1
14k
source
stringclasses
2 values
def line_split_to_str_list(line): """E.g: 1 2 3 -> [1, 2, 3] Useful to convert numbers into a python list.""" return "[" + ", ".join(line.split()) + "]"
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def single_duplicate_bond_index_v3000_sdf(tmp_path: Path) -> Path: """Write a single molecule to a v3000 sdf with a duplicate bond index. Args: tmp_path: pytest fixture for writing files to a temp directory Returns: Path to the sdf """ sdf_text = """ ...
bigcode/self-oss-instruct-sc2-concepts
def extract_github_owner_and_repo(github_page): """ Extract only owner and repo name from GitHub page https://www.github.com/psf/requests -> psf/requests Args: github_page - a reference, e.g. a URL, to a GitHub repo Returns: str: owner and repo joined by a '/' """ if githu...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def invalid_output( query: dict, db_query: Union[str, dict], api_key: str, error: str, start_record: int, page_length: int) -> dict: """Create and return the output for a failed request. Args: query: The query in format as defined in wrapper/input_format.py. ...
bigcode/self-oss-instruct-sc2-concepts
def time_mirror(clip): """ Returns a clip that plays the current clip backwards. The clip must have its ``duration`` attribute set. The same effect is applied to the clip's audio and mask if any. """ return clip.time_transform(lambda t: clip.duration - t - 1, keep_duration=True)
bigcode/self-oss-instruct-sc2-concepts
def get_smallest_divisible_number_brute_force(max_factor): """ Get the smallest divisible number by all [1..max_factor] numbers by brute force. """ number_i = max_factor while True: divisible = True for factor_i in range(1, max_factor+1): if number_i % factor_i > 0: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any from typing import List def lst(*a: Any) -> List[Any]: """Returns arguments *a as a flat list, any list arguments are flattened. Example: lst(1, [2, 3]) returns [1, 2, 3]. """ flat = [] for v in a: if isinstance(v, list): flat.extend(v) else: ...
bigcode/self-oss-instruct-sc2-concepts
def parse_stam(organization_data): """ Used to parse stamnummer of organization. """ return str(organization_data["stamNr"])
bigcode/self-oss-instruct-sc2-concepts
def construct_type(code): """Construct type in response.""" # return 'https://bcrs.gov.bc.ca/.well_known/schemas/problem#{}'.format(code) return code
bigcode/self-oss-instruct-sc2-concepts
def silverS(home_score, away_score): """Calculate S for each team (Source: https://www.ergosum.co/nate-silvers-nba-elo-algorithm/). Args: home_score - score of home team. away_score - score of away team. Returns: 0: - S for the home team. 1: - S for the away team. ""...
bigcode/self-oss-instruct-sc2-concepts
def _get_run_tag_info(mapping): """Returns a map of run names to a list of tag names. Args: mapping: a nested map `d` such that `d[run][tag]` is a time series produced by DataProvider's `list_*` methods. Returns: A map from run strings to a list of tag strings. E.g. {...
bigcode/self-oss-instruct-sc2-concepts
def trrotate_to_standard(trin, newchan = ("E", "N", "Z")): """Rotate traces to standard orientation""" return trin.rotate_to_standard(newchan)
bigcode/self-oss-instruct-sc2-concepts
def score(boards, number, index): """Return the final score of the board that contains index.""" first = index - index % 25 return int(number) * sum(int(boards[i]) for i in range(first, first + 25))
bigcode/self-oss-instruct-sc2-concepts
def combine_two_lists_no_duplicate(list_1, list_2): """ Method to combine two lists, drop one copy of the elements present in both and return a list comprised of the elements present in either list - but with only one copy of each. Args: list_1: First list list_2: Second list Return...
bigcode/self-oss-instruct-sc2-concepts
def match1(p, text): """Return true if first character of text matches pattern character p.""" if not text: return False return p == '.' or p == text[0]
bigcode/self-oss-instruct-sc2-concepts
import random def shuffle(lst): """ Shuffle a list """ random.shuffle(lst) return lst
bigcode/self-oss-instruct-sc2-concepts
import math def bit_length(i: int) -> int: """Returns the minimal amount of bits needed to represent unsigned integer `i`.""" return math.ceil(math.log(i + 1, 2))
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def convert_volume(value: Union[float, str]) -> float: """Convert volume to float.""" if value == "--": return -80.0 return float(value)
bigcode/self-oss-instruct-sc2-concepts
def _ag_checksum(data): """ Compute a telegram checksum. """ sum = 0 for c in data: sum ^= c return sum
bigcode/self-oss-instruct-sc2-concepts
import turtle def create_turtle(x, y): """[summary] Create the turtle pen with specific attributes [description] Set speed and pen color Direction is set default due east Pen is returned in list with x and y coordinates """ t = turtle.Pen() t.speed(8) t.pencolor("white") r...
bigcode/self-oss-instruct-sc2-concepts
import random import string def rndstr(length): """Generate random string of given length which contains digits and lowercase ASCII characters""" return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(length))
bigcode/self-oss-instruct-sc2-concepts
def bb_union(*bbs): """Returns a bounding box containing the given bboxes""" return [min(*x) for x in zip(*[b[0] for b in bbs])],[max(*x) for x in zip(*[b[1] for b in bbs])]
bigcode/self-oss-instruct-sc2-concepts
def search_list_of_objs(objs, attr, value): """Searches a list of objects and retuns those with an attribute that meets an equality criteria Args: objs (list): The input list attr (str): The attribute to match value (any): The value to be matched Returns: list[any]: The lis...
bigcode/self-oss-instruct-sc2-concepts
def tw_to_rgb(thxs): """ Convert a 12-digit hex color to RGB. Parameters ---------- thxs : str A 12-digit hex color string. Returns ------- tuple[int] An RGB tuple. """ if len(thxs) != 13: if len(thxs) == 12: raise ValueError("thxs is not cor...
bigcode/self-oss-instruct-sc2-concepts
def make_pair(coll, lbracket='<', rbracket='>'): """ A context aware function for making a string representation of elements of relationships. It takes into account the length of the element. If there is just one element, the brackets are left of, but when there are more, all the elements will be sepera...
bigcode/self-oss-instruct-sc2-concepts
def _get2DArea(box): """Get area of a 2D box""" return (box['right']-box['left']) * (box['bottom']-box['top'])
bigcode/self-oss-instruct-sc2-concepts
from typing import List def to_base_digits(value: int, base: int) -> List[int]: """Returns value in base 'base' from base 10 as a list of digits""" ret = [] n = value while n > base: n, digit = divmod(n, base) ret.append(digit) ret.append(n) return ret[::-1]
bigcode/self-oss-instruct-sc2-concepts
def get_neighbors(nodeid, adjmatrix): """returns all the direct neighbors of nodeid in the graph Args: nodeid: index of the datapoint adjmatrix: adjmatrix with true=edge, false=noedge Returns: list of neighbors and the number of neighbors """ neighbors = [] num = 0 ...
bigcode/self-oss-instruct-sc2-concepts
def get_ucr_class_name(id): """ This returns the module and class name for a ucr from its id as used in report permissions. It takes an id and returns the string that needed for `user.can_view_report(string)`. The class name comes from corehq.reports._make_report_class, if something breaks, look there f...
bigcode/self-oss-instruct-sc2-concepts
def scope_minimal_nr_tokens(df_in, min_nr_tokens=1): """ Remove destinations with fewer tokens than the set minimum (default: at least 1). """ return df_in.loc[lambda df: df["nr_tokens"] >= min_nr_tokens]
bigcode/self-oss-instruct-sc2-concepts
def eval_en(x, mol): """ Evaluate the energy of an atom. """ mol.set_positions(x) return [mol.get_potential_energy()]
bigcode/self-oss-instruct-sc2-concepts
def default_before_hook(*args, **kwargs): """The default before hook, will act like it's not even there """ return args, kwargs
bigcode/self-oss-instruct-sc2-concepts
def parse_dict(raw_dict, ignore_keys=[]): """ Parses the values in the dictionary as booleans, ints, and floats as appropriate Parameters ---------- raw_dict : dict Flat dictionary whose values are mainly strings ignore_keys : list, optional Keys in the dictionary to remove ...
bigcode/self-oss-instruct-sc2-concepts
def get_feature_names(npcs=3): """ Create the list of feature names depending on the number of principal components. Parameters ---------- npcs : int number of principal components to use Returns ------- list name of the features. """ names_root = ["coeff" + st...
bigcode/self-oss-instruct-sc2-concepts
def _map_action_index_to_output_files(actions, artifacts): """Constructs a map from action index to output files. Args: actions: a list of actions from the action graph container artifacts: a map {artifact_id: artifact path} Returns: A map from action index (in action graph container) to a string of...
bigcode/self-oss-instruct-sc2-concepts
def adsorption(CGF, CGRA, CET, cg, epsl, KdF, KdR, KI): """ Adsorption equilibrium of enzyme between facile and recalcitrant glucan, and accounting for inhibition by glucose (and other sugars if present) """ CEGF = CET/(1 + KdF/KdR*CGRA/CGF + epsl*KdF/CGF*(1 + cg/KI)) CEGR = CET/(1 + KdR/KdF*CG...
bigcode/self-oss-instruct-sc2-concepts
def container_logs(client, resource_group_name, name, container_name=None): """Tail a container instance log. """ if container_name is None: container_name = name log = client.container_logs.list(resource_group_name, container_name, name) return log.content
bigcode/self-oss-instruct-sc2-concepts
def float_list_string(vals, nchar=7, ndec=3, nspaces=2, mesg='', left=False): """return a string to display the floats: vals : the list of float values nchar : [7] number of characters to display per float ndec : [3] number of decimal places to print to nspaces : [2] number o...
bigcode/self-oss-instruct-sc2-concepts
def tiles_from(state_pkt): """ Given a Tile State packet, return the tile devices that are valid. This works by taking into account ``tile_devices_count`` and ``start_index`` on the packet. """ amount = state_pkt.tile_devices_count - state_pkt.start_index return state_pkt.tile_devices[:amou...
bigcode/self-oss-instruct-sc2-concepts
def balance_queue_modifier(count_per_day: float) -> float: """ Create a modifier to use when setting filter values. Because our queue is only ever 1k posts long (reddit limitation), then we never want any given sub to take up any more than 1/100th of the queue (seeing as how we have ~73 partners ri...
bigcode/self-oss-instruct-sc2-concepts
def seq_mult_scalar(a, s): """Takes a list of numbers a and a scalar s. For the input a=[a0, a1, a2,.., an] the function returns [s * a0, s * a1, s * a2, ..., s * an]""" return [s * i for i in a]
bigcode/self-oss-instruct-sc2-concepts
def fix_z_dir(job): """ Rather than fixing all directions only fix the z-direction during an NPT simulation Args: job (LAMMPS): Lammps job object Returns: LAMMPS: Return updated job object """ job.input.control["fix___ensemble"] = job.input.control["fix___ensemble"].replace( ...
bigcode/self-oss-instruct-sc2-concepts
def get_uid(instance): """ 获取实例的 uid (hex). get hex uid from instance. Examples:: data = { 'uid': instance.uid.hex if instance else None, 'related_uid': instance.related.uid.hex if instance.related else None, } data = { 'uid': get_uid(instance), ...
bigcode/self-oss-instruct-sc2-concepts
def idx_tuple_in_df(tuple_x, df): """Find the first row index of tuple_x in df.""" res=None for i,v in enumerate(df.values): if tuple_x == tuple(v): res = i break else: res=None return res
bigcode/self-oss-instruct-sc2-concepts
def account_main_purse_uref(CLIENT, account_key: bytes) -> str: """Returns an on-chain account's main purse unforgeable reference. """ return CLIENT.queries.get_account_main_purse_uref(account_key)
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _make_pod_command() -> List[str]: """Generate pod command. Returns: List[str]: pod command. """ return ["./init_icscf.sh", "&"]
bigcode/self-oss-instruct-sc2-concepts
def time_content_log_split(log_line): """ Splits a portal.log line into the Time Elapsed and Content sections :param log_line: A line from the portal.log file :return: Values for time elapsed and content of line """ tmp = log_line.replace('[', '') tmp = tmp.split('] ') time = tmp[0] ...
bigcode/self-oss-instruct-sc2-concepts
def get_number_rows(settings, star_height): """Determine the number of rows of stars that fit on the screen.""" avaiable_space_y = (settings.screen_height - star_height) number_rows = int(avaiable_space_y / (2 * star_height)) return number_rows
bigcode/self-oss-instruct-sc2-concepts
def unbindReferences(par, modeOnly=False): """ Erase bind strings or change modes for all bindReferences of a parameter :param par: the bindMaster parameter :param modeOnly: if True, just change the references modes to prevMode :return: the references that were changed """ refs = par.bindReferences for p in re...
bigcode/self-oss-instruct-sc2-concepts
def redshiftFromScale(scale): """ Converts a scale factor to redshift. :param scale: scale factor :type scale: float or ndarray :return: redshift :rtype: float or ndarray """ return 1. / scale - 1.
bigcode/self-oss-instruct-sc2-concepts
def normalize_url(url: str) -> str: """ Remove leading and trailing slashes from a URL :param url: URL :return: URL with no leading and trailing slashes :private: """ if url.startswith('/'): url = url[1:] if url.endswith('/'): url = url[:-1] return url
bigcode/self-oss-instruct-sc2-concepts
def reliability_calc(RACC, ACC): """ Calculate Reliability. :param RACC: random accuracy :type RACC: float :param ACC: accuracy :type ACC: float :return: reliability as float """ try: result = (ACC - RACC) / (1 - RACC) return result except Exception: retu...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import Any def to_list(data: Union[tuple, list, Any]): """ If input is tuple, it is converted to list. If it's list, it is returned untouched. Otherwise returns a single-element list of the data. :return: list-ified data """ if isinstance(data, list): ...
bigcode/self-oss-instruct-sc2-concepts
def dual_id_dict(dict_values, G, node_attribute): """ It can be used when one deals with a dual graph and wants to link analyses conducted on this representation to the primal graph. For instance, it takes the dictionary containing the betweennes-centrality values of the nodes in the dual graph, and as...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable import asyncio def add_async_job(target: Callable, *args): """Add a callable to the event loop.""" loop = asyncio.get_event_loop() if asyncio.iscoroutine(target): task = loop.create_task(target) elif asyncio.iscoroutinefunction(target): task = loop.create_t...
bigcode/self-oss-instruct-sc2-concepts
def GCF(a, b): """ Finds Greatest Common Factor of two given numbers :param a: arbitrary first number :type a: int :param b: arbitrary second number :type b: int :return: greatest common factor :rtype: int """ if type(a) is not int or type(b) is not int: raise TypeError('...
bigcode/self-oss-instruct-sc2-concepts
def construct_pandoc_command( input_file=None, lua_filter=None, ): """ Construct the Pandoc command. # Parameters input_file:pathlib.Path - The file that we want to apply the lua filter too. lua_filter:pathlib.Path - The path to the lua filter to use for the word counts. ...
bigcode/self-oss-instruct-sc2-concepts
import re import requests def get_resource_tables(resource_url): """ Returns a list of all the HTML tables for the resource documented at resource_url """ pattern = re.compile(r'(?ims)(\<table\>.*?\</table\>)') response = requests.get(resource_url) return pattern.findall(response.text)
bigcode/self-oss-instruct-sc2-concepts
import re def split_blurb(lines): """ Split blurb on horizontal rules.""" blurbs = [""] for line in lines.split('\n')[:-1]: if re.match(r'\*{3,}',line): blurbs.append("") else: blurbs[-1] += line + '\n' return blurbs
bigcode/self-oss-instruct-sc2-concepts
def splitConsecutive(collection, length): """ Split the elements of the list @collection into consecutive disjoint lists of length @length. If @length is greater than the no. of elements in the collection, the collection is returned as is. """ # Insufficient collection size for grouping if len(collection) < length...
bigcode/self-oss-instruct-sc2-concepts
import csv def csv_to_fasta(csv_path, delimiter=","): """Convert a csv-file of the format: <sequence> <name> to a FASTA file.""" result = "" with csv_path.open() as csv_file: rd = csv.reader(csv_file, delimiter=delimiter) for row in rd: result += '> {}\n{}\n'.format(row[1], row[0]) return result
bigcode/self-oss-instruct-sc2-concepts
def _create_titled_group(root, key, title): """Helper to create a titled group in h5py""" out = root.create_group(key) out.attrs['TITLE'] = title return out
bigcode/self-oss-instruct-sc2-concepts
import re def run_and_parse_first_match(run_lambda, command, regex): """ Runs command using run_lambda, returns the first regex match if it exists """ rc, out, _ = run_lambda(command) if rc != 0: return None match = re.search(regex, out) if match is None: return None re...
bigcode/self-oss-instruct-sc2-concepts
def fetch_courses(soups): """Fetches each course inside a given page.""" courses = [] for soup in soups: course = soup.find_all('div', class_='item-frame') courses.append(course) return courses
bigcode/self-oss-instruct-sc2-concepts
def iter_reduce_ufunc(ufunc, arr_iter, out=None): """ constant memory iteration and reduction applys ufunc from left to right over the input arrays Example: >>> # ENABLE_DOCTEST >>> from vtool_ibeis.other import * # NOQA >>> arr_list = [ ... np.array([0, 1, 2, 3, 8...
bigcode/self-oss-instruct-sc2-concepts
def _full_analysis_mp_alias(br_obj, analysis_set, output_directory, unique_name, verbose, quick_plots): """ Alias for instance method that allows the method to be called in a multiprocessing pool. Needed as multiprocessing does not otherwise work on object instance methods. """ return (br_obj, u...
bigcode/self-oss-instruct-sc2-concepts
def GatherResultsFromMultipleFiles(results_by_file): """Gather multiple results to organize them by check name and file name. Args: results_by_file: A dict of check results indexed by file name. Returns: A dict of check results in the form of: {`check_name`: {`file_name`: { 'warning': { ...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def _username_hash(username): """Returns bytes, a cryptographically safe one-way hash of the username. This way, if someone breaks the Fernet encryption, they still don't know the username. Args: username: unicode """ return hashlib.sha256(username.encode('utf-8')).digest()
bigcode/self-oss-instruct-sc2-concepts
def show_input(data): # 이거 각 setting으로 옮겨주기 """ 입력값이 올바른지 확인 :param data: 어떤 데이터든 가능 :return: 맞으면 True / 틀리면 False (type: boolean) """ print(data) confirm = input("입력을 재대로 하셨나요? Y/N: ") print("===========================================") if confirm.lower() == 'y': return Tr...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def get_sha_hash(input_string): """ Method returns the sha hash digest for a given string. Args: input_string (str): the input string for which sha has to be computed """ return hashlib.md5(input_string).digest()
bigcode/self-oss-instruct-sc2-concepts
def generate_graphic_character_vocabulary(conn, min_coverage): """Generate a vocabulary of characters from graphic representations of lemmas with the specified minimal corpus coverage. This is the smallest vocabulary of the most frequent characters so that these characters together cover at least a por...
bigcode/self-oss-instruct-sc2-concepts
def blendTriangular(d, u=0.1, s=0.4, c=0.9): """ Triangular blending funciton, taken from eq. 3.5 c must be greater than s s must be greater than u u is the beginning point of the triangle c is the endpoint of the triangle s is the peak of the triangle """ d = float(d) u = f...
bigcode/self-oss-instruct-sc2-concepts
def ordenar_alinhamento(elemento_frasico, alinhamento): """ Ordena os pares alinhados conforme as frases originais. :param elemento_frásico: lista de tuplos com as informações (palavra/gesto, lema, classe gramatical) do elemento frásico :param alinhamento: dicionário com as palavras/gestos alinhados e as suas class...
bigcode/self-oss-instruct-sc2-concepts
import getpass def ask_password(prompt="Password : ", forbiddens=[]): """Prompt the user for a password without echoing Keyword Arguments: prompt {str} -- the question message (default: {"Password : "}) forbiddens {list} -- the list of bad passwords (default: {[]}) Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def get_id(first_name, last_name): """ :param first_name: The first_name to search for. :param last_name: The last_name to search for. :return: The id number for the given first/last name, otherwise None. """ with open("database.txt", "r") as file: for line in file: line = li...
bigcode/self-oss-instruct-sc2-concepts
def check_file(filename): """Returns whether or not a file is considered a valid image""" ext = filename.split(".")[-1].lower() return ext == "jpg" or ext == "png" or ext == "jpeg"
bigcode/self-oss-instruct-sc2-concepts
def get_q_id(hit): """ Returns the query ID for a hit. Parameters ---------- A hit parsed from an HHsearch output file, i.e. dict with at least the key 'alignment' which is a dict by itself and comes at least with the key 'Q xxx' where xxx is some identifier. The value for this 'Q xxx' key is a...
bigcode/self-oss-instruct-sc2-concepts
def split_version(version_string): """Parse a version string like 2.7 into a tuple.""" return tuple(map(int, version_string.split(".")))
bigcode/self-oss-instruct-sc2-concepts
def is_icmp_reply(pkt, ipformat): """Return True if pkt is echo reply, else return False. If exception occurs return False. :param pkt: Packet. :param ipformat: Dictionary of names to distinguish IPv4 and IPv6. :type pkt: dict :type ipformat: dict :rtype: bool """ # pylint: disable=...
bigcode/self-oss-instruct-sc2-concepts
def validate_move(move, turn, board): """ Determine if the next move is valid for the current player :param move: :param turn: :param board: :return: boolean flag for if the move is valid as well as the current gamestate dictionary """ if turn == 1: piece = 'X' else: ...
bigcode/self-oss-instruct-sc2-concepts
def convert_name(name, to_version=False): """This function centralizes converting between the name of the OVA, and the version of software it contains. OneFS OVAs follow the naming convention of <VERSION>.ova :param name: The thing to covert :type name: String :param to_version: Set to True t...
bigcode/self-oss-instruct-sc2-concepts
def meas_pruning_ratio(num_blobs_orig, num_blobs_after_pruning, num_blobs_next): """Measure blob pruning ratio. Args: num_blobs_orig: Number of original blobs, before pruning. num_blobs_after_pruning: Number of blobs after pruning. num_blobs_next: Number of a blobs in an adjacent se...
bigcode/self-oss-instruct-sc2-concepts
def count_str(S): """Takes a pd Series with at least the indices 'alt' and 'repeatunit', both strings. Return the number of occurances of repeatunit in alt""" if S['alt'] is None: return 0 count = S['alt'].count(S['repeatunit']) return count
bigcode/self-oss-instruct-sc2-concepts
def abs2(src, target): """ compute the square absolute value of two number. :param src: first value :param target: second value :return: square absolute value """ return abs(src - target) ** 2
bigcode/self-oss-instruct-sc2-concepts
def union(bbox1, bbox2): """Create the union of the two bboxes. Parameters ---------- bbox1 Coordinates of first bounding box bbox2 Coordinates of second bounding box Returns ------- [y0, y1, x0, x1] Coordinates of union of input bounding boxes """ y0 =...
bigcode/self-oss-instruct-sc2-concepts
def run_bq_query(client, query, timeout): """ Returns the results of a BigQuery query Args: client: BigQuery-Python bigquery client query: String query timeout: Query timeout time in seconds Returns: List of dicts, one per record; dict keys are table fi...
bigcode/self-oss-instruct-sc2-concepts
def create_headers(bearer_token): """Create headers to make API call Args: bearer_token: Bearer token Returns: Header for API call """ headers = {"Authorization": f"Bearer {bearer_token}"} return headers
bigcode/self-oss-instruct-sc2-concepts
def get_ship_name(internal_name): """ Get the display name of a ship from its internal API name :param internal_name: the internal name of the ship :return: the display name of the ship, or None if not found """ internal_names = { "adder": "Adder", "alliance-challenger": "Allianc...
bigcode/self-oss-instruct-sc2-concepts
def user_input(passcode: str) -> str: """Get the passcode from the user.""" code = input(f"Type the numerical value of the passcode `{passcode}`: ") return code
bigcode/self-oss-instruct-sc2-concepts
import glob def getRansomwareFiles(path): """ Return all the ransomware files (sorted) from a given path """ try: all_file_names = [i for i in glob.glob(str(path) + '/*_labeled.*')] all_file_names = sorted(all_file_names) return all_file_names except: pri...
bigcode/self-oss-instruct-sc2-concepts
def to_dynamic_cwd_tuple(x): """Convert to a canonical cwd_width tuple.""" unit = "c" if isinstance(x, str): if x[-1] == "%": x = x[:-1] unit = "%" else: unit = "c" return (float(x), unit) else: return (float(x[0]), x[1])
bigcode/self-oss-instruct-sc2-concepts
import typing def attach(object: typing.Any, name: str) -> typing.Callable: """Return a decorator doing ``setattr(object, name)`` with its argument. >>> spam = type('Spam', (object,), {})() >>> @attach(spam, 'eggs') ... def func(): ... pass >>> spam.eggs # doctest: +ELLIPSIS <funct...
bigcode/self-oss-instruct-sc2-concepts
import email def process(data): """Extract required data from the mail""" mail = email.message_from_string(data[1]) return { 'date': mail['Date'], 'to': mail['To'], 'from': mail['From'], 'message': mail.get_payload() }
bigcode/self-oss-instruct-sc2-concepts
def test_in(value, seq): """Check if value is in seq. Copied from Jinja 2.10 https://github.com/pallets/jinja/pull/665 .. versionadded:: 2.10 """ return value in seq
bigcode/self-oss-instruct-sc2-concepts
def make_copy_files_rule(repository_ctx, name, srcs, outs): """Returns a rule to copy a set of files.""" # Copy files. cmds = ['cp -f "{}" "$(location {})"'.format(src, out) for (src, out) in zip(srcs, outs)] outs = [' "{}",'.format(out) for out in outs] return """genrule( name = "{}", ...
bigcode/self-oss-instruct-sc2-concepts
def json_serializer(obj): """ A JSON serializer that serializes dates and times """ if hasattr(obj, 'isoformat'): return obj.isoformat()
bigcode/self-oss-instruct-sc2-concepts
import re def strip(text): """ python's str.strip() method implemented using regex Args: text (str): text to strip of white space Returns: textStripped (str): text stripped of white space """ stripStartRegex = re.compile(r'(^\s*)') stripEndRegex = re.compile(r'(\s*$)') tex...
bigcode/self-oss-instruct-sc2-concepts
import collections def replace_key_in_order(odict, key_prev, key_after): """Replace `key_prev` of `OrderedDict` `odict` with `key_after`, while leaving its value and the rest of the dictionary intact and in the same order. """ tmp = collections.OrderedDict() for k, v in odict.items(): ...
bigcode/self-oss-instruct-sc2-concepts
def _which(repository_ctx, cmd, default = None): """A wrapper around repository_ctx.which() to provide a fallback value.""" result = repository_ctx.which(cmd) return default if result == None else str(result)
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable def composed(*decorators: Callable) -> Callable: """ Build a decorator by composing a list of decorator """ def inner(f: Callable) -> Callable: for decorator in reversed(decorators): f = decorator(f) return f return inner
bigcode/self-oss-instruct-sc2-concepts