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 = """ 0 0 0 0 0 999 V3000 M V30 BEGIN CTAB M V30 COUNTS 9 9 0 0 0 M V30 BEGIN ATOM M V30 1 C 87.71 -95.64 0 0 M V30 2 C 87.71 -81.29 0 0 M V30 3 C 100.18 -74.09 0 0 M V30 4 C 100.18 -59.69 0 0 M V30 5 C 87.71 -52.49 0 0 M V30 6 C 75.24 -59.69 0 0 M V30 7 C 75.24 -74.09 0 0 M V30 8 C 87.71 -38.09 0 0 M V30 9 O 100.18 -30.89 0 0 M V30 END ATOM M V30 BEGIN BOND M V30 1 1 1 2 M V30 2 1 2 3 M V30 3 2 3 4 M V30 4 1 4 5 M V30 5 2 5 6 M V30 6 1 6 7 M V30 7 2 7 2 M V30 1 1 5 8 M V30 9 2 8 9 M V30 END BOND M V30 END CTAB M END $$$$ """ outpath = tmp_path / "input.sdf" with open(outpath, "w") as outh: outh.write(sdf_text) return outpath
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 github_page == "": return "" # split on github.com split_github_page = github_page.split("github.com") # take portion of URL after github.com and split on slashes github_url_elements = split_github_page[1].split("/") # rejoin by slash owner and repo name github_owner_and_repo = ("/").join(github_url_elements[1:3]) return github_owner_and_repo
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. db_query: The query that was sent to the API in its language. api_key: The key used for the request. error: The error message returned. start_record: The index of the first record requested. page_length: The page length requested. Returns: A dict containing the passed values and "-1" as index where necessary to be compliant with wrapper/output_format. """ out = dict() out["query"] = query out["dbQuery"] = db_query out["apiKey"] = api_key out["error"] = error out["result"] = { "total": "-1", "start": str(start_record), "pageLength": str(page_length), "recordsDisplayed": "0", } out["records"] = list() return out
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: divisible = False break if divisible: return number_i number_i += 1
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: flat.append(v) return flat
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. """ S_home, S_away = 0, 0 if home_score > away_score: S_home = 1 elif away_score > home_score: S_away = 1 else: S_home, S_away = .5, .5 return S_home, S_away
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. {"loss001a": ["actor/loss", "critic/loss"], ...} """ return {run: sorted(mapping[run]) for run in mapping}
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 Returns: The combined list, as described above """ additional_unique_elements_list_2 = [i for i in list_2 if i not in list_1] return list_1 + additional_unique_elements_list_2
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") return [t, x, y]
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 list of objects found """ return [obj for obj in objs if getattr(obj, attr) == value]
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 correctly formatted (#xxxxxxxxxxxx).") else: print(thxs) raise ValueError("thxs must be 12 digits long with '#' at the beginning.") return (int(thxs[1:3], 16), int(thxs[5:7], 16), int(thxs[9:11], 16))
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 seperated by a comma, and the brackets will be inserted as well. :param coll: The collection that needs to be printed. Can be a generator, but cannot be infinite. :param str lbracket: The bracket that goes on the left. :param str rbracket: The bracket that goes on the right. :returns: A context aware string representation of the pair. :rtype: str """ coll = list(coll) if len(coll) == 1: return str(coll[0]) return lbracket + ', '.join(coll) + rbracket
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 for i in range(0, adjmatrix.shape[0], 1): if adjmatrix[i][nodeid]: neighbors.append(i) num += 1 return neighbors, num
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 first. :param id: the id of the ucr report config :return: string class name """ return 'corehq.reports.DynamicReport{}'.format(id)
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 Returns ------- dict Flat dictionary with values of expected dtypes """ def __parse_str(mystery): if not isinstance(mystery, str): return mystery if mystery.lower() == 'true': return True if mystery.lower() == 'false': return False # try to convert to number try: mystery = float(mystery) if mystery % 1 == 0: mystery = int(mystery) return mystery except ValueError: return mystery if not ignore_keys: ignore_keys = list() else: if isinstance(ignore_keys, str): ignore_keys = [ignore_keys] elif not isinstance(ignore_keys, (list, tuple)): raise TypeError('ignore_keys should be a list of strings') clean_dict = dict() for key, val in raw_dict.items(): if key in ignore_keys: continue val = __parse_str(val) if isinstance(val, (tuple, list)): val = [__parse_str(item) for item in val] elif isinstance(val, dict): val = parse_dict(val, ignore_keys=ignore_keys) clean_dict[key] = val return clean_dict
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" + str(i + 1) + "_" for i in range(npcs)] + [ "residuo_", "maxflux_", ] return [i + j for j in ["g", "r"] for i in names_root]
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 concatenated output artifacts paths. """ action_index_to_output_files = {} for i, action in enumerate(actions): output_files = " ".join( sorted([artifacts[output_id] for output_id in action.output_ids])) action_index_to_output_files[i] = output_files return action_index_to_output_files
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*CGF/CGRA + epsl*KdR/CGRA*(1 + cg/KI)) return CEGF, CEGR
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 of spaces between each float """ if left: format = '%-*.*f%*s' else: format = '%*.*f%*s' istr = mesg for val in vals: istr += format % (nchar, ndec, val, nspaces, '') return istr
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[:amount]
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 right now, seems like a reasonable amount). This is so that if a sub gets 3 posts per day, we can adequately bring in everything, but if it has 800 posts a day (r/pics) then the value is adjusted appropriately so that it doesn't overwhelm the queue. """ target_queue_percentage = 0.01 queue_percentage = count_per_day / 1000 return target_queue_percentage / queue_percentage
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( "x 0.0 0.0 1.0 y 0.0 0.0 1.0 z 0.0 0.0 1.0", "z 0.0 0.0 1.0" ) return job
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), 'related_uid': get_uid(instance.related), } :rtype: str | None """ return instance.uid.hex if instance else None
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] content = tmp[1] return time, content
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 refs: p.mode = p.prevMode if not modeOnly: p.bindExpr = '' return refs
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: return "None"
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): pass elif isinstance(data, tuple): data = list(data) else: data = [data] return data
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 associates these variables to the corresponding edgeID. Parameters ---------- dict_values: dictionary it should be in the form {nodeID: value} where values is a measure that has been computed on the graph, for example G: networkx graph the graph that was used to compute or to assign values to nodes or edges node_attribute: string the attribute of the node to link to the edges GeoDataFrame Returns ------- ed_dict: dictionary a dictionary where each item consists of a edgeID (key) and centrality values (for example) or other attributes (values) """ view = dict_values.items() ed_list = list(view) ed_dict = {} for p in ed_list: ed_dict[G.nodes[p[0]][node_attribute]] = p[1] # attribute and measure return ed_dict
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_task(target(*args)) else: task = loop.run_in_executor(None, target, *args) return task
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('Input must be float type.') if b > a: return GCF(b, a) if a % b == 0: return b return GCF(b, a % b)
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. # Return A list of CLI elements that will be used by subprocess. """ # -------- # Basic Commands return [ "pandoc", "--lua-filter", lua_filter, input_file, ]
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: return collection # Iterate over the collection and collect groupings into results. groupings = [] index = 0 while index < len(collection): groupings.append(collection[index: index +length]) index += length return groupings
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 return match.group(1)
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, 9]), ... np.array([4, 1, 2, 3, 4, 5]), ... np.array([0, 5, 2, 3, 4, 5]), ... np.array([1, 1, 6, 3, 4, 5]), ... np.array([0, 1, 2, 7, 4, 5]) ... ] >>> memory = np.array([9, 9, 9, 9, 9, 9]) >>> gen_memory = memory.copy() >>> def arr_gen(arr_list, gen_memory): ... for arr in arr_list: ... gen_memory[:] = arr ... yield gen_memory >>> print('memory = %r' % (memory,)) >>> print('gen_memory = %r' % (gen_memory,)) >>> ufunc = np.maximum >>> res1 = iter_reduce_ufunc(ufunc, iter(arr_list), out=None) >>> res2 = iter_reduce_ufunc(ufunc, iter(arr_list), out=memory) >>> res3 = iter_reduce_ufunc(ufunc, arr_gen(arr_list, gen_memory), out=memory) >>> print('res1 = %r' % (res1,)) >>> print('res2 = %r' % (res2,)) >>> print('res3 = %r' % (res3,)) >>> print('memory = %r' % (memory,)) >>> print('gen_memory = %r' % (gen_memory,)) >>> assert np.all(res1 == res2) >>> assert np.all(res2 == res3) """ # Get first item in iterator try: initial = next(arr_iter) except StopIteration: return None # Populate the outvariable if specified otherwise make a copy of the first # item to be the output memory if out is not None: out[:] = initial else: out = initial.copy() # Iterate and reduce for arr in arr_iter: ufunc(out, arr, out=out) return out
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, unique_name, br_obj.full_analysis(analysis_set, output_directory, verbose = verbose, compile_pdf = verbose, quick_plots = quick_plots))
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': { 'range': [lower_bound, upper_bound] 'count': number of occurrences that fall into the range, 'total': total number of data points, }, 'error': ... }}} """ merged = {} for filename, results in results_by_file.iteritems(): if results: for check_name, values in results.iteritems(): if check_name not in merged: merged[check_name] = {filename: values} else: merged[check_name][filename] = values return merged
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 True else: return False
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 portion of ``min_coverage`` of the corpus. :param conn: Database connection for statistics. :param float min_coverage: The minimal coverage. :return: A dictionary from characters from graphic representations of lemmas to their frequency rank. """ if min_coverage < 0 or min_coverage > 1: raise ValueError('The minimum coverage must be between 0 (inclusive) and 1 (inclusive)') if min_coverage == 0: return dict() return {graphic_c: rank for graphic_c, rank in conn.cursor().execute( '''SELECT graphic, rank FROM statistics WHERE language = "jpn" AND form = "lemma:graphic:character" AND count >= ( SELECT MAX(count) FROM statistics WHERE language = "jpn" AND form = "lemma:graphic:character" AND cumulative_count >= ( SELECT MAX(cumulative_count) FROM statistics WHERE language = "jpn" AND form = "lemma:graphic:character") * ?)''', (min_coverage,))}
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 = float(u) s = float(s) c = float(c) if (s - u) == 0: return 0 if (c - s) == 0: return 0 if d <= u: b = 0.0 elif d > u and d <= s: b = (d - u)/(s - u) elif d > s and d < c: b = (c - d)/(c - s) else: b = 0.0 return b
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 classes gramaticais :return: Lista com as palavra/gestos alinhados ordenados conforme a sua ordem na frase original. """ alinhamento_ordenado = [] for t in elemento_frasico: for k, v in alinhamento.items(): if k == t[1]: alinhamento_ordenado.append(v) return alinhamento_ordenado
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: str -- the appropriate input password """ password = getpass.getpass(prompt) if password not in forbiddens: return password else: return ask_password(prompt, forbiddens)
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 = line.rstrip() if not line: continue first, last, _id = line.split(", ") if first_name == first and last_name == last: return _id return None
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 third dict which needs to contain the key 'sequence'. Returns ------- str : The query ID starting with 'Q '. Notes ----- Each 'hit' has one 'alignment', which comes with different lines. One of those lines is 'Q consensus'. Another line is called 'Q xxx' where xxx is the ID of the input query sequence. This function find this 'Q xxx' ID. We assume that there are only two line names starting with 'Q '. """ # find the right ID _id = [_id for _id in hit['alignment'].keys() if _id.startswith('Q') and _id != 'Q Consensus'][0] return _id
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=bare-except try: if pkt[ipformat['IPType']][ipformat['ICMP_rep']].type == \ ipformat['Type']: return True else: return False except: # pylint: disable=bare-except return False
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: piece = 'O' try: if board[move[:-1]][move] not in ('X', 'O'): board[move[:-1]][move] = piece return True, board else: return False, board except KeyError: return False, board
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 to covert the name of an OVA to the version :type to_version: Boolean """ if to_version: return name.rstrip('.ova') else: return '{}.ova'.format(name)
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 segment, presumably of similar size as that of the original blobs. Returns: Pruning ratios as a tuple of the original number of blobs, blobs after pruning to original, and blobs after pruning to the next region. """ ratios = None if num_blobs_next > 0 and num_blobs_orig > 0: # calculate pruned:original and pruned:adjacent blob ratios print("num_blobs_orig: {}, blobs after pruning: {}, num_blobs_next: {}" .format(num_blobs_orig, num_blobs_after_pruning, num_blobs_next)) ratios = (num_blobs_orig, num_blobs_after_pruning / num_blobs_orig, num_blobs_after_pruning / num_blobs_next) return ratios
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 = min(bbox1[0], bbox2[0]) y1 = max(bbox1[1], bbox2[1]) x0 = min(bbox1[2], bbox2[2]) x1 = max(bbox1[3], bbox2[3]) return [y0, y1, x0, x1]
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 field names and values are entries """ job_id, _results = client.query(query, timeout=timeout) complete, row_count = client.check_job(job_id) if complete: results = client.get_query_rows(job_id) print('Got %s records' %row_count) else: raise RuntimeError('Query not complete') return(results)
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": "Alliance Challenger", "alliance-chieftain": "Alliance Chieftain", "alliance-crusader": "Alliance Crusader", "anaconda": "Anaconda", "asp-explorer": "Asp Explorer", "asp-scout": "Asp Scout", "beluga-liner": "Beluga Liner", "cobra-mk-iii": "Cobra MkIII", "cobra-mk-iv": "Cobra MkIV", "diamondback-explorer": "Diamondback Explorer", "diamondback-scout": "Diamondback Scout", "dolphin": "Dolphin", "eagle": "Eagle", "federal-assault-ship": "Federal Assault Ship", "federal-corvette": "Federal Corvette", "federal-dropship": "Federal Dropship", "federal-gunship": "Federal Gunship", "fer-de-lance": "Fer-de-Lance", "hauler": "Hauler", "imperial-clipper": "Imperial Clipper", "imperial-courier": "Imperial Courier", "imperial-cutter": "Imperial Cutter", "imperial-eagle": "Imperial Eagle", "keelback": "Keelback", "krait-mk-ii": "Krait MkII", "krait-phantom": "Krait Phantom", "mamba": "Mamba", "orca": "Orca", "python": "Python", "sidewinder": "Sidewinder", "type-6": "Type-6 Transporter", "type-7": "Type-7 Transporter", "type-9": "Type-9 Heavy", "type-10": "Type-10 Defender", "viper-mk-iii": "Viper MkIII", "viper-mk-iv": "Viper MkIV", "vulture": "Vulture", } if internal_name in internal_names: return internal_names[internal_name] return None
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: print("Ransomware samples could not be read") return
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 <function func at 0x...> """ def decorator(func): setattr(object, name, func) return func return decorator
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 = "{}", outs = [ {} ], cmd = \"""{} \""", )""".format(name, "\n".join(outs), " && \\\n".join(cmds))
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*$)') textStartStripped = stripStartRegex.sub('', text) textStripped = stripEndRegex.sub('', textStartStripped) return textStripped
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(): if k == key_prev: tmp[key_after] = v else: tmp[k] = v return tmp
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