seed
stringlengths
1
14k
source
stringclasses
2 values
def get_indexes(lst, sub_lst, compare_function=None): """Return the indexes of a sub list in a list. :param lst: the list to search in :param sub_lst: the list to match :param compare_function: the comparaison function used :type lst: list :type sub_lst: list :type compare_function: function, takes 2 list as argument :return: the list of indexes of sub_lst in lst. :rtype: list of int """ indexes = [] ln = len(sub_lst) for i in range(len(lst)): if compare_function: if compare_function(lst[i:i + ln], sub_lst): indexes.append(i) else: if lst[i:i + ln] == sub_lst: indexes.append(i) return indexes
bigcode/self-oss-instruct-sc2-concepts
def _join_modules(module1, module2): """Concatenate 2 module components. Args: module1: First module to join. module2: Second module to join. Returns: Given two modules aaa.bbb and ccc.ddd, returns a joined module aaa.bbb.ccc.ddd. """ if not module1: return module2 if not module2: return module1 return '%s.%s' % (module1, module2)
bigcode/self-oss-instruct-sc2-concepts
def from_723(u: bytes) -> int: """Convert from ISO 9660 7.2.3 format to uint16_t Return the little-endian part always, to handle non-specs-compliant images. """ return u[0] | (u[1] << 8)
bigcode/self-oss-instruct-sc2-concepts
import base64 def decode_textfield_base64(content): """ Decodes the contents for CIF textfield from Base64. :param content: a string with contents :return: decoded string """ return base64.standard_b64decode(content)
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def default_key(obj: object, key: str, default: Any = None) -> Any: """Get value by attribute in object or by key in dict. If property exists returns value otherwise returns `default` value. If object not exist or object don't have property returns `default`. Args: obj (object, list, tuple, dict): dictionary key (str, int): key of property default (object): Object that returned if key not found Returns: value by given key or default """ if obj and isinstance(obj, dict): return obj[key] if key in obj else default elif obj and isinstance(obj, object): return getattr(obj, key, default) else: return default
bigcode/self-oss-instruct-sc2-concepts
def _get_lua_base_module_parts(base_path, base_module): """ Get a base module from either provided data, or from the base path of the package Args: base_path: The package path base_module: None, or a string representing the absence/presence of a base module override Returns: Returns a list of parts of a base module based on base_path/base_module. If base_module is None, a default one is created based on package name. """ # If base module is unset, prepare a default. if base_module == None: return ["fbcode"] + base_path.split("/") # If base module is empty, return the empty list. elif not base_module: return [] # Otherwise, split it on the module separater. else: return base_module.split(".")
bigcode/self-oss-instruct-sc2-concepts
def broken_bond_keys(tra): """ keys for bonds that are broken in the transformation """ _, _, brk_bnd_keys = tra return brk_bnd_keys
bigcode/self-oss-instruct-sc2-concepts
def named_field(key, regex, vim=False): """ Creates a named regex group that can be referend via a backref. If key is None the backref is referenced by number. References: https://docs.python.org/2/library/re.html#regular-expression-syntax """ if key is None: # return regex return r'(%s)' % (regex,) if vim: return r'\(%s\)' % (regex) else: return r'(?P<%s>%s)' % (key, regex)
bigcode/self-oss-instruct-sc2-concepts
import torch def _set_finite_diff_coeffs(ndim, dx, device, dtype): """Calculates coefficients for finite difference derivatives. Currently only supports 4th order accurate derivatives. Args: ndim: Int specifying number of dimensions (1, 2, or 3) dx: Float Tensor containing cell spacing in each dimension device: PyTorch device to create coefficient Tensors on dtype: PyTorch datatype to use Returns: Float Tensors containing the coefficients for 1st and 2nd derivatives. fd1: Contains 2 coefficients for each dimension fd2: Contains 1 coefficient for the central element, followed by 2 coefficients for each dimension """ fd1 = torch.zeros(ndim, 2, device=device, dtype=dtype) fd2 = torch.zeros(ndim * 2 + 1, device=device, dtype=dtype) dx = dx.to(device).to(dtype) for dim in range(ndim): fd1[dim] = ( torch.tensor([8 / 12, -1 / 12], device=device, dtype=dtype) / dx[dim] ) fd2[0] += -5 / 2 / dx[dim] ** 2 fd2[1 + dim * 2 : 1 + (dim + 1) * 2] = ( torch.tensor([4 / 3, -1 / 12], device=device, dtype=dtype) / dx[dim] ** 2 ) return fd1, fd2
bigcode/self-oss-instruct-sc2-concepts
def build_regex(pattern, pattern_name=None, **kwargs): """ Return regex string as a named capture group. See: https://tonysyu.github.io/readable-regular-expressions-in-python.html """ pattern = pattern.format(**kwargs) if pattern_name is not None: return r'(?P<{name}>{pattern})'.format(name=pattern_name, pattern=pattern) return pattern
bigcode/self-oss-instruct-sc2-concepts
def number_of_patients(dataset, feature_files, label_files): """ Calculates number of unique patients in the list of given filenames. :param dataset: string. Dataset train/val/test. :param feature_files: list of strings. List of filenames with patient names containing features. :param label_files: list of strings. List of filenames with patient names containing labels. :return: int. Number of unique patients. """ if len(feature_files) != len(label_files): raise AssertionError(dataset, 'files have different length.') print('Number of', dataset, 'files:', len(feature_files)) patients = [] for file in feature_files: patient = file[:4] if patient not in patients: patients.append(patient) print(dataset, 'patients:', patients) num_patients = len(patients) print('Num', dataset, 'patients:', num_patients) return num_patients
bigcode/self-oss-instruct-sc2-concepts
def invert_dict(dic, sort=True, keymap={}, valmap={}): """Inverts a dictionary of the form key1 : [val1, val2] key2 : [val1] to a dictionary of the form val1 : [key1, key2] val2 : [key2] Parameters ----------- dic : dict Returns ----------- dict """ dic_inv = {} for k, v_list in dic.items(): k = keymap.get(k, k) for v in v_list: v = valmap.get(v, v) if v in dic_inv: dic_inv[v].append(k) else: dic_inv[v] = [k] if sort: for k in dic_inv.keys(): dic_inv[k].sort() return dic_inv
bigcode/self-oss-instruct-sc2-concepts
def byte_ord(b): """ Return the integer representation of the byte string. This supports Python 3 byte arrays as well as standard strings. """ try: return ord(b) except TypeError: return b
bigcode/self-oss-instruct-sc2-concepts
import re def parse_time(time_string) -> int: """ Parse a time stamp in seconds (default) or milliseconds (with "ms" unit) The "s" unit is optional and implied if left out. Args: time_string(str): timestamp, e.g., "0.23s", "5.234" (implied s), "1234 ms" must be a number followed by "s", "ms" or nothing. Returns: int: time represented by time_string in milliseconds """ time_pattern = re.compile( r""" \s* # ignore leading spaces ([0-9.]+) # Numerical part \s* # optional spaces ( (s|ms) # optional units: s (seconds) or ms (milliseconds) \s* # ignore trailing spaces )? """, re.VERBOSE, ) match = time_pattern.fullmatch(time_string) if match: units = match[3] if units == "ms": return int(match[1]) else: return int(1000 * float(match[1])) else: raise ValueError( f'cannot convert "{time_string}" to a time in seconds or milliseconds' )
bigcode/self-oss-instruct-sc2-concepts
def confidence_intervals_overlap(old_score, old_ci, new_score, new_ci): """Returns true if the confidence intervals of the old and new scores overlap, false otherwise. """ if old_score < new_score: old_score += old_ci new_score -= new_ci return old_score >= new_score else: old_score -= old_ci new_score += new_ci return old_score <= new_score
bigcode/self-oss-instruct-sc2-concepts
def data2str(data): """ Convert some data to a string. An empty or None value is returned unchanged (helpful for testing), e.g.: '57 75 6e 64 65 72 62 61 72 49 52' -> 'WunderbarIR' '' -> '' """ if not data: return data text = ''.join([chr(int(v, 16)) for v in data.split()]) return text
bigcode/self-oss-instruct-sc2-concepts
import re def get_task_args_and_kwargs(file_path): """Get the args and kwargs for the task.""" text = '' with open(file_path, 'r') as f: for line in f: text += line.strip() + ' ' reg = re.search('Task was called with args: (\(.*?\)) ' 'kwargs: ({.*?})', text) if reg: return reg.group(1), reg.group(2) # Can't parse arguments b/c they're not in the email. return None, None
bigcode/self-oss-instruct-sc2-concepts
import yaml def gen_lookup(file): """ Generating the lookup table between api-endpoints and elasticsearch instances from the configuration of the lod-api. lookup table is of the form: {"/api/endpoint": "http://elasticsearchhost:port/index/doctype", "/resource": "http://elasticsearchhost:9200/resource/data", "/works": …, } returns: dict. """ es_lookup = dict() # read complete api configuration with open(file, 'r') as instream: config = yaml.safe_load(instream) # generate lookup for source indices for source, instance in config["source_indices"].items(): key = "/source/{}".format(source) # remove trailing slash from index-URL es_lookup[key] = instance.rstrip("/") # generate remaining index lookups es_address = "http://{h}:{p}".format(h=config["es_host"], p=config["es_port"]) for ctx in config["indices"]: doctype = config["indices"][ctx].get("type") index = config["indices"][ctx].get("index") es_lookup["/" + index] = "{h}/{i}/{t}".format( h=es_address, i=index, t=doctype) return es_lookup
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def default_tile_extras_provider(hyb: int, ch: int, z: int) -> Any: """ Returns None for extras for any given hyb/ch/z. """ return None
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def copa_preformat_fn(ex: Dict[str, Any]) -> Dict[str, Any]: """format for COPA tasks. Args: ex: Dictionary with one sample Returns: ex: Formatted dictionary """ premise, question = ex['premise'].decode(), ex['question'].decode() input_prompt = f'{premise} What was the {question} of this?' choices = { ex['choice1'].decode(): -ex['label'] + 1, ex['choice2'].decode(): ex['label'] } return {'input': input_prompt, 'target_scores': choices}
bigcode/self-oss-instruct-sc2-concepts
def bfs(G, s, f): """ Breadth-first search :param G: The graph object :param s: The start node :param f: The goal node :return: The explored set """ explored, frontier = [], [s] while frontier: v = frontier.pop(0) if v == f: pass else: explored.append(v) frontier.extend([w for w in G[v] if w not in explored]) return explored
bigcode/self-oss-instruct-sc2-concepts
import copy def norm_rda_deficit(norm_rda_arr): """ Returns a modified list of nutrient dicts in which value represents a fraction of how much a given nutrient has been satisfied. A value of 0 represents full satisfaction, and 1 represents no satisfaction. """ r_nut = copy.deepcopy(norm_rda_arr) for ni, _ in enumerate(r_nut): r_nut[ni]['value'] = 1 - r_nut[ni]['value'] return r_nut
bigcode/self-oss-instruct-sc2-concepts
def add_dicts(*args): """ Combine dicts. If there are duplicate keys, raise an error. """ new = {} for arg in args: for key in arg: if key in new: raise ValueError("Duplicate key: %r" % key) new[key] = arg[key] return new
bigcode/self-oss-instruct-sc2-concepts
import re def get_confirm_lines(code): """ Takes the block of code submitted to RESOLVE and returns a list of the lines that start with Confirm or ensures, keeping the semicolons attached at the end, and removing all spaces (starting, ending, or in between) @param code: All code submitted to RESOLVE verifier @return: List of confirm/ensures statements, missing the confirm/ensures but with their semicolons, all spaces removed """ # Regex explanation: [^;]* is any amount of characters that isn't a semicolon, so what this is saying is find # all Confirm [characters that aren't ;]; OR ensures [characters that aren't ;]; # The parentheses tell regex what to actually return out, so the Confirm/ensures are chopped off but they did have # to be present for it to match lines = [] for match in re.findall("Confirm ([^;]*;)|ensures ([^;]*;)", code): for group in match: if group: # This check gets rid of the empty matches made by having 2 group statements # Get rid of all spaces lines.append(re.sub(" ", "", group)) return lines
bigcode/self-oss-instruct-sc2-concepts
def rotate_90(grid): """ Rotate a given grid by 90 degrees. Args: grid: Grid to rotate. Returns: Grid after being rotated by 90 degrees. """ new_grid = [] for col, _ in enumerate(grid): new_row = [] # Go through the rows, # and form new rows depending on the flower's column. for row in grid: new_row.append(row[col]) new_grid.append(new_row) return new_grid[::-1]
bigcode/self-oss-instruct-sc2-concepts
def get_single_key_value_pair(d): """ Returns the key and value of a one element dictionary, checking that it actually has only one element Parameters ---------- d : dict Returns ------- tuple """ assert isinstance(d, dict), f'{d}' assert len(d) == 1, f'{d}' return list(d.keys())[0], list(d.values())[0]
bigcode/self-oss-instruct-sc2-concepts
def donner_carte(nombre:int, joueur:dict, paquet:list) -> bool: """Donne une carte Args: nombre (int): nombre de cartes à donner joueur (dict): profil du joueur paquet (list): paquet de jeu Returns: bool: True si pas d'erreurs """ for _ in range(nombre): joueur['jeu'].append(paquet.pop(0)) return True
bigcode/self-oss-instruct-sc2-concepts
def command(cmd, *parameters): """ Helper function. Prints the gprMax #<cmd>: <parameters>. None is ignored in the output. Args: cmd (str): the gprMax cmd string to be printed *parameters: one or more strings as arguments, any None values are ignored Returns: s (str): the printed string """ # remove Nones filtered = filter(lambda x: x is not None, parameters) # convert to str filtered_str = map(str, filtered) # convert to list filtered_list = list(filtered_str) try: s = '#{}: {}'.format(cmd, " ".join(filtered_list)) except TypeError as e: # append info about cmd and parameters to the exception: if not e.args: e.args = ('', ) additional_info = "Creating cmd = #{} with parameters {} -> {} failed".format(cmd, parameters, filtered_list) e.args = e.args + (additional_info,) raise e # and now we can print it: print(s) return s
bigcode/self-oss-instruct-sc2-concepts
import inspect import types def find_classes_subclassing(mods, baseclass): """ Given a module or a list of modules, inspect and find all classes which are a subclass of the given baseclass, inside those modules """ # collect all modules found in given modules if not isinstance(mods, list): mods = [mods] innner_mods = inspect.getmembers(mods, lambda obj: isinstance(obj, types.ModuleType)) mods.extend(innner_mods) classes = [] for m in mods: name_klasses = inspect.getmembers(m, lambda obj: isinstance(obj, type) and issubclass(obj, baseclass)) if name_klasses: for name, klass in name_klasses: del name classes.append(klass) return classes
bigcode/self-oss-instruct-sc2-concepts
def bdev_get_iostat(client, name=None): """Get I/O statistics for block devices. Args: name: bdev name to query (optional; if omitted, query all bdevs) Returns: I/O statistics for the requested block devices. """ params = {} if name: params['name'] = name return client.call('bdev_get_iostat', params)
bigcode/self-oss-instruct-sc2-concepts
def simplify_whitespace(name): """Strip spaces and remove duplicate spaces within names""" if name: return ' '.join(name.split()) return name
bigcode/self-oss-instruct-sc2-concepts
import toml def data_from_toml_lines(lines): """ Return a mapping of data from an iterable of TOML text ``lines``. For example:: >>> lines = ['[advisory]', 'id = "RUST1"', '', '[versions]', 'patch = [">= 1"]'] >>> data_from_toml_lines(lines) {'advisory': {'id': 'RUST1'}, 'versions': {'patch': ['>= 1']}} """ return toml.loads("\n".join(lines))
bigcode/self-oss-instruct-sc2-concepts
def unames_are_equivalent(uname_actual: str, uname_expected: str) -> bool: """Determine if uname values are equivalent for this tool's purposes.""" # Support `mac-arm64` through Rosetta until `mac-arm64` binaries are ready # Expected and actual unames will not literally match on M1 Macs because # they pretend to be Intel Macs for the purpose of environment setup. But # that's intentional and doesn't require any user action. if "Darwin" in uname_expected and "arm64" in uname_expected: uname_expected = uname_expected.replace("arm64", "x86_64") return uname_actual == uname_expected
bigcode/self-oss-instruct-sc2-concepts
def part_1b_under_equilb_design_ensemble_run_limit(job): """Check that the equilbrium design ensemble run is under it's run limit.""" try: if ( job.doc.equilb_design_ensemble_number >= job.doc.equilb_design_ensemble_max_number ): job.doc.equilb_design_ensemble_max_number_under_limit = False return job.doc.equilb_design_ensemble_max_number_under_limit else: return True except: return False
bigcode/self-oss-instruct-sc2-concepts
def get_column(grid, column_index): """Return the column from the grid at column_index as a list.""" return [row[column_index] for row in grid]
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple import requests def create_sq_project(sq_server: str, auth: Tuple, proj_id: str) -> str: """Creates a SonarQube project for the current project""" url = f"{sq_server}/api/projects/create" name = f"project-{proj_id}" args = {"name": name, "project": name, "visibility": "public"} requests.post(url=url, data=args, auth=auth) return name
bigcode/self-oss-instruct-sc2-concepts
def fit(approach, train_dict): """ Given a train data (features and labels), fit a dummy classifier. Since we can actually not fit a model, it returns the probability of complaint. Parameters ---------- approach: dictionary Approach configuration coming from the experiment yaml train_dict: dictionary Dictionary containing the train features DataFrame and the train labels DataFrame. Return ------ Class Model fitted using the train data. """ model = approach['hyperparameters']['perc_complaint'] return model
bigcode/self-oss-instruct-sc2-concepts
def count_words(my_string): """ This function counts words :param my_string: str - A string of words or characters :return: int - length of words """ if not isinstance(my_string, str): raise TypeError("only accepts strings") special_characters = ['-', '+', '\n'] for character in special_characters: my_string = my_string.replace(character, " ") words = my_string.split() return len(words)
bigcode/self-oss-instruct-sc2-concepts
import re def toSentenceCase(text): """ Converts the given text to sentence case. Args: text (string): Text to convert to sentence case. Returns: (string): Sentence case version of given text. """ return re.sub(r"(?<=\w)([A-Z])", r" \1", text).title()
bigcode/self-oss-instruct-sc2-concepts
import re def readLinking(goldStdFile): """ Reads a file containing Entity Linking output according to the KBP 2013 format. Each line in the systeming output file consists of 2 or 3 fields: mention_id KB_ID (optional confidence, default is 1.0) Each line in the gold standard file may contain 2 or more than 3 fields, but we ignore all but the first 2 fields: mention_id KB_ID Do NOT change IDs in any way (i.e., do not Uppercase all IDs) Returns a pair of dictionaries: linking: KB_ID -> set of query_IDs el2kbid: query_ID -> list of pairs of KB_ID (or NIL ID) and confidence, highest confidence first """ linking = dict() el2kbid = dict() for line in open(goldStdFile): d = re.split("\s+", line.strip()) if len(d)<2: continue mention = d[0] kb_id = d[1] if(len(d)==3): # a system linking conf = d[2] else: conf = 1.0 if mention in el2kbid.keys(): # more than one link for this mention; put the earliest highest confidence link in front, and add additional links to back of list links = el2kbid[mention] # list of (kb_id,conf) tuples bestlink, bestconf = links[0] if conf > bestconf: links.insert(0, (kb_id, conf)) else: links.append((kb_id, conf)) else: el2kbid[mention] = [(kb_id, conf)] if kb_id in linking.keys(): linking[kb_id].add(mention) else: linking[kb_id] = set([mention]) return (linking, el2kbid)
bigcode/self-oss-instruct-sc2-concepts
def _compute_nfp_uniform(l, u, cum_counts, sizes): """Computes the expected number of false positives caused by using u to approximate set sizes in the interval [l, u], assuming uniform distribution of set sizes within the interval. Args: l: the lower bound on set sizes. u: the upper bound on set sizes. cum_counts: the complete cummulative distribution of set sizes. sizes: the complete domain of set sizes. Return (float): the expected number of false positives. """ if l > u: raise ValueError("l must be less or equal to u") if l == 0: n = cum_counts[u] else: n = cum_counts[u]-cum_counts[l-1] return n * float(sizes[u] - sizes[l]) / float(2*sizes[u])
bigcode/self-oss-instruct-sc2-concepts
def class_counts(rows): """Counts the number of each type of example in a dataset.""" counts = {} # a dictionary of label -> count. for row in rows: # in our dataset format, the label is always the last column label = row[-1] if label not in counts: counts[label] = 0 counts[label] += 1 return counts
bigcode/self-oss-instruct-sc2-concepts
def is_pandigital(n: int) -> bool: """Determine if n is pandigital.""" lst = set(sorted([int(i) for i in str(n)])) return len(lst) == 10
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def traverse_dict(d: Dict, key_path: str) -> Any: """ Traverse nested dictionaries to find the element pointed-to by key_path. Key path components are separated by a ':' e.g. "root:child:a" """ if type(d) is not dict: raise TypeError(f"unable to traverse into non-dict value with key path: {key_path}") # Extract one path component at a time components = key_path.split(":", maxsplit=1) if components is None or len(components) == 0: raise KeyError(f"invalid config key path: {key_path}") key = components[0] remaining_key_path = components[1] if len(components) > 1 else None val: Any = d.get(key, None) if val is not None: if remaining_key_path is not None: return traverse_dict(val, remaining_key_path) return val else: raise KeyError(f"value not found for key: {key}")
bigcode/self-oss-instruct-sc2-concepts
def is_prime(n): """ Decide whether a number is prime or not. """ if n < 2: return False if n == 2: return True if n % 2 == 0: return False i = 3 maxi = n**0.5 + 1 while i <= maxi: if n % i == 0: return False i += 2 return True
bigcode/self-oss-instruct-sc2-concepts
def fluid_needed(molarity : float, mw : float , mass : float) -> float: """How much liquid do you need for a solution of a specific molarity?""" return mass/mw/molarity
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_backups_in_path(folder, file_type): """Return a collection of all backups of a specified type in a path. Use the rglob utility function to recursively search a directory for all backup files of the type `file_type`. Pass an empty string to not spe :param folder: The path to search :param file_type: The type of files to search for :returns: Collection of backups :rtype: PosixPath (as defined in pathlib) """ return Path(folder).rglob("*." + file_type + '*.backup')
bigcode/self-oss-instruct-sc2-concepts
def format_xi_stats(users_as_nodes, exp, xi_mean, xi_std, tot): """Formats the curvature estimates for logging. Args: users_as_nodes: Bool indicating which interaction graph was generated. If True (False), a user-user (item-item) interaction graph was generated. exp: Boolean indicating if the interaction graph distances are on an exponential scale. xi_mean: Float containng the mean of the curvatures of the sampled triangles. xi_std: Float containng the standard deviation of the curvatures of the sampled triangles. tot: Int containing the total number of legal sampled triangles. Returns: String storing the input information in a readable format. """ stats = 'User-user stats:' if users_as_nodes else 'Item-item stats:' if exp: stats += ' (using exp)' stats += '\n' stats += '{:.3f} +/- {:.3f} \n'.format(xi_mean, xi_std) stats += 'out of {} samples.'.format(tot) return stats
bigcode/self-oss-instruct-sc2-concepts
def greatest_common_divisor(a: int, b: int) -> int: """ Euclid's Lemma : d divides a and b, if and only if d divides a-b and b Euclid's Algorithm >>> greatest_common_divisor(7,5) 1 Note : In number theory, two integers a and b are said to be relatively prime, mutually prime, or co-prime if the only positive integer (factor) that divides both of them is 1 i.e., gcd(a,b) = 1. >>> greatest_common_divisor(121, 11) 11 """ if a < b: a, b = b, a while a % b != 0: a, b = b, a % b return b
bigcode/self-oss-instruct-sc2-concepts
def _build_xpath_expr(attrs) -> str: """ Build an xpath expression to simulate bs4's ability to pass in kwargs to search for attributes when using the lxml parser. Parameters ---------- attrs : dict A dict of HTML attributes. These are NOT checked for validity. Returns ------- expr : unicode An XPath expression that checks for the given HTML attributes. """ # give class attribute as class_ because class is a python keyword if "class_" in attrs: attrs["class"] = attrs.pop("class_") s = " and ".join(f"@{k}={repr(v)}" for k, v in attrs.items()) return f"[{s}]"
bigcode/self-oss-instruct-sc2-concepts
def insert_symbol(symbol: str, fbid: str, dict: dict): """ Modifies the dictionary in place by inserting the symbol as the key and the fbid as the value. If the symbol is already present in the dictionary the fbid is added to the unique set of FlyBase IDs in the value :param symbol:str - A single symbol to insert into the dictionary. :param fbid:str - A single FlyBase ID. :param dict:dict - The dictionary reference to modify. :return: None """ if symbol and symbol not in dict: # If we haven't seen this symbol before initialize the set. dict[symbol] = {fbid} elif symbol: # We have seen this symbol before so we add it to the set. dict[symbol].add(fbid) return None
bigcode/self-oss-instruct-sc2-concepts
import ntpath def path_leaf(path): """ guaranteed filename from path; works on Win / OSX / *nix """ head, tail = ntpath.split(path) return tail or ntpath.basename(head)
bigcode/self-oss-instruct-sc2-concepts
import re def win_path_to_unix(path, root_prefix=""): """Convert a path or ;-separated string of paths into a unix representation Does not add cygdrive. If you need that, set root_prefix to "/cygdrive" """ path_re = '(?<![:/^a-zA-Z])([a-zA-Z]:[\/\\\\]+(?:[^:*?"<>|]+[\/\\\\]+)*[^:*?"<>|;\/\\\\]+?(?![a-zA-Z]:))' # noqa def _translation(found_path): found = found_path.group(1).replace("\\", "/").replace(":", "").replace("//", "/") return root_prefix + "/" + found path = re.sub(path_re, _translation, path).replace(";/", ":/") return path
bigcode/self-oss-instruct-sc2-concepts
def entry_to_bytes(arch, entry: dict) -> bytes: """ Pack a U-Boot command table *entry* (struct cmd_tbl_s), as defined by the following dictionary keys and return it's representation in bytes. +---------------+---------------+----------------------------------------------+ | Key | Value Type | Description | +===============+===============+==============================================+ | name | int | Pointer to command name string | +---------------+---------------+----------------------------------------------+ | maxargs | int | Maximum number of arguments the command takes| +---------------+---------------+----------------------------------------------+ | cmd_rep | int | Depending upon the U-Boot version, either a | | | | flag or function pointer used for command | | | | autorepeat behavior | +---------------+---------------+----------------------------------------------+ | cmd | int | Function pointer for ``do_<command>`` | +---------------+---------------+----------------------------------------------+ | usage | int | Pointer to short usage text string | +---------------+---------------+----------------------------------------------+ | longhelp | int | Pointer to longer command description and | | | | help text. Only present if U-Boot was built | | | | with ``CONFIG_SYS_LONGHELP`` | +---------------+---------------+----------------------------------------------+ | autocomplete | int | Function pointer to autocomplete handler. | | | | Only present if U-Boot was built with | | | | ``CONFIG_AUTOCOMPLETE``. | +---------------+---------------+----------------------------------------------+ The **arch** parameter is required in order to pack the pointer values according to the target's endianness. """ ret = bytearray() ret += arch.int_to_bytes(entry['name']) ret += arch.int_to_bytes(entry['maxargs']) ret += arch.int_to_bytes(entry['cmd_rep']) ret += arch.int_to_bytes(entry['cmd']) ret += arch.int_to_bytes(entry['usage']) if 'longhelp' in entry: ret += arch.int_to_bytes(entry['longhelp']) if 'complete' in entry: ret += arch.int_to_bytes(entry['complete']) return bytes(ret)
bigcode/self-oss-instruct-sc2-concepts
import requests import json def api_call(page, username, password): """ This function makes an API call to the leitos ocupaca API within DataSUS Arguments: page: a string or integer with the number of the page to request username: a string with the username login information for the API password: a string with the password login information for the API Output: json_data: a dictionary containing the information for the requested page """ # Make API request for given page r = requests.get("https://elastic-leitos.saude.gov.br/leito_ocupacao/_search?from={}".format(str(page)), auth = (username, password)) # Turn data into json json_data = json.loads(r.text) # Return dictionary return json_data
bigcode/self-oss-instruct-sc2-concepts
def ref(i): """ref returns a string with a reference to object number `i`""" return b'%d 0 R' % i
bigcode/self-oss-instruct-sc2-concepts
def structure_metadata(structure): """ Generates metadata based on a structure """ comp = structure.composition elsyms = sorted(set([e.symbol for e in comp.elements])) meta = { "nsites": structure.num_sites, "elements": elsyms, "nelements": len(elsyms), "composition": comp.as_dict(), "composition_reduced": comp.reduced_composition.as_dict(), "formula_pretty": comp.reduced_formula, "formula_anonymous": comp.anonymized_formula, "chemsys": "-".join(elsyms), "volume": structure.volume, "density": structure.density, } return meta
bigcode/self-oss-instruct-sc2-concepts
def swap(L, i, j): """Swaps elements i and j in list L.""" tmp = L[i] L[i] = L[j] L[j] = tmp return L
bigcode/self-oss-instruct-sc2-concepts
def parse_gav(gav, defaults=(None, None, None)): """Parses the given GAV as a tuple. gav the GAV to parse. It must be a string with two colons separating the GAV parts. defaults a triple of default coordinates to return if a part from the input is missing Returns: a triple with the parsed GAV """ parts = gav.split(':') if len(parts) != 3: raise ValueError(f"Not a valid GAV pattern: {gav}") for index, value in enumerate(parts): if len(value) == 0: parts[index] = defaults[index] return tuple(parts)
bigcode/self-oss-instruct-sc2-concepts
def _get_indices(term, chunk): """Get indices where term appears in chunk Parameters ---------- term : str The token to look for in the `chunk` chunk : [str] A chunk of text in which to look for instances of `term` Returns ------- [int] Indices in `chunk` where `term` was found Examples -------- >>> term = 'a' >>> chunk = ['a', 'a', 'b', 'b', 'a'] >>> _get_indices(term, chunk) [0, 1, 5] """ return [i for i, token in enumerate(chunk) if token == term]
bigcode/self-oss-instruct-sc2-concepts
import unicodedata def meta_tostring(metadata): """Convert the metadata dictionary to text header""" lines = [] lines.append('# {}\n'.format(metadata.get('title', ''))) for k, v in metadata.items(): if k != 'title': lines.append(f'{k}: {v}') return unicodedata.normalize('NFC', '\n'.join(lines) + '\n')
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def get_cameras_and_objects(config: dict[str, Any]) -> set[tuple[str, str]]: """Get cameras and tracking object tuples.""" camera_objects = set() for cam_name, cam_config in config["cameras"].items(): for obj in cam_config["objects"]["track"]: camera_objects.add((cam_name, obj)) return camera_objects
bigcode/self-oss-instruct-sc2-concepts
def dt_to_camli_iso(dt): """ Convert a datetime to iso datetime compatible with camlistore. """ return dt.isoformat() + 'Z'
bigcode/self-oss-instruct-sc2-concepts
def floatOrNone(v, default=0.0, exctype=Exception): """Returns the float value of the given value, or default (which is normally 0.0) on error. Catches exceptions of the given exctype (Exception by default)""" try: return float(v) except exctype: return default
bigcode/self-oss-instruct-sc2-concepts
import torch def get_mrr(indices, targets): #Mean Receiprocal Rank --> Average of rank of next item in the session. """ Calculates the MRR score for the given predictions and targets Args: indices (Bxk): torch.LongTensor. top-k indices predicted by the model. targets (B): torch.LongTensor. actual target indices. Returns: mrr (float): the mrr score """ tmp = targets.view(-1, 1) targets = tmp.expand_as(indices) hits = (targets == indices).nonzero() ranks = hits[:, -1] + 1 ranks = ranks.float() rranks = torch.reciprocal(ranks) mrr = torch.sum(rranks).data / targets.size(0) return mrr
bigcode/self-oss-instruct-sc2-concepts
def get_valid_results(df_res): """Splits up results into valid and invalid results. Based on properties computed in data.py.""" # Select valid results (one pair of resized ellipses) cond_valid = df_res['inside'] & df_res['resized'] & (df_res['num_annot']==2) df_res_valid = df_res.loc[cond_valid] # Everything else is excluded/invalid df_res_invalid = df_res.loc[~cond_valid] return df_res_valid, df_res_invalid
bigcode/self-oss-instruct-sc2-concepts
import inspect from typing import Dict from typing import Any def _build_bool_option(parameter: inspect.Parameter) -> Dict[str, Any]: """Provide the argparse options for a boolean option.""" params = {"action": "store_false" if parameter.default is True else "store_true"} return params
bigcode/self-oss-instruct-sc2-concepts
def _get_default_image_id(module): """ Return the image_id if the image_id was specified through "source_details" or None. """ if "source_details" in module.params and module.params["source_details"]: source_details = module.params["source_details"] source_type = source_details.get("source_type") if not source_type: if "source_type" not in source_details: module.fail_json( msg="source_type required and must be one of: 'bootVolume', 'image'" ) if source_type == "image": return source_details["image_id"] return None
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_test_path_services(filename, data_type): """ Gets the path of the filename for a given data type Args: filename (str): Name of file, not path data_type (str): Data type, CRDS, GC, ICOS etc Returns: pathlib.Path: Absolute path to object """ data_path = Path(__file__).resolve().parent.parent.parent.joinpath(f"data/proc_test_data/{data_type}/{filename}") return data_path
bigcode/self-oss-instruct-sc2-concepts
import pkg_resources def readfile(filename: str) -> str: """Read a file that is contained in the openclean_notebook package. This is a helper method to read Javascript files and HTML templates that are part of the openclean_notebook package. Returns a string containing the file contents. Parameters ---------- filename: string Relative path to the file that is being read. Returns ------- string """ return pkg_resources.resource_string(__name__, filename).decode('utf-8')
bigcode/self-oss-instruct-sc2-concepts
import string def add_numbering(ax, i=0, loc=(0.8, 0.8), label='', style='APS', numbering='abc', **kwargs): """ Add numbering (a,b,c,...) to axis. Parameters ---------- ax : matplotlib.pyplot.axis object i : int The axis index, e.g., i=1 -> (a) loc : tuple or list Position of label, relative to axis [x, y] where 0 <= x,y <= 1 (values outside this limit are allowed but may result in labels outside axis) label : string Override with custom label style : string If 'APS' or 'Nature' will use preset styles Otherwise if string matches format r'{i}' will use that as template string Otherwise style overwrites the label numbering : string Which type of numbering 'abc' -> a, b, c 'ABC' -> A, B, C '123' -> 1, 2, 3 'roman' -> i, ii, iii 'ROMAN' -> I, II, III **kwargs : string keyword arguments e.g. {'color', 'red'} Returns ------- ax : matplotlib.pyplot.axis object """ if not label: if i<0 or i>25: raise ValueError("i must be between 0 and 25 \ (support for i>25 will come in future version)") roman_nums = ['i', 'ii', 'iii', 'iv', 'v', 'vi', 'vii', 'viii', 'ix', 'x',\ 'xi', 'xii', 'xiii', 'xiv', 'xv', 'xvi', 'xvii', 'xviii', \ 'xix', 'xx', 'xxi', 'xxii', 'xxiii', 'xxiv', 'xxv', 'xxvi'] # different formats: if numbering == 'abc': # a, b, c label = string.ascii_lowercase[i] elif numbering == 'ABC': # A, B, C label = string.ascii_uppercase[i] elif numbering == '123': # 1, 2, 3 label = i elif numbering == 'roman': # i, ii, iii, ... label = r'${}$'.format(roman_nums[i]) elif numbering == 'ROMAN': # I, II, III, ... label = r'{}'.format(roman_nums[i].upper()) else: raise ValueError("numbering option not a recognized value") if style == 'APS': label = r'({})'.format(label) elif style == 'Nature': label = r'\textbf{{{i}}}'.format(i=label) else: label = style.format(i=label) ax.text(loc[0], loc[1], label, transform=ax.transAxes, **kwargs) return ax
bigcode/self-oss-instruct-sc2-concepts
import re def normalize_tag_name(name): """ Normalize an EC2 resource tag to be compatible with shell environment variables. Basically it means the the following regex must be followed: [a-Z][a-Z0-9_]*. This function is not meant to handle all possible corner cases so try not to be stupid with tag naming. :param name: the tag name :return: a normalized version of the tag name """ result = name if name[0].isdigit(): result = "_" + name result = re.sub('[^0-9a-zA-Z_]+', '_', result) return result.upper()
bigcode/self-oss-instruct-sc2-concepts
def cmd_name(python_name): """Convert module name (with ``_``) to command name (with ``-``).""" return python_name.replace('_', '-')
bigcode/self-oss-instruct-sc2-concepts
def hash_string(s, is_short_hash=False): """Fowler–Noll–Vo hash function""" if not is_short_hash: h = 14695981039346656037 for c in s: h = ((h ^ ord(c)) * 1099511628211) & 0xFFFFFFFFFFFFFFFF if h == 0: h = 1 # Special case for our application (0 is reserved internally) return h else: h = 2166136261 for c in s: h = ((h ^ ord(c)) * 16777619) & 0xFFFFFFFF if h == 0: h = 1 # Special case for our application (0 is reserved internally) return h
bigcode/self-oss-instruct-sc2-concepts
import csv def create_mapping(path, src, dest, key_type=None) -> dict: """ Create a dictionary between two attributes. """ if key_type is None: key_type = int with open(path, 'r') as f: reader = csv.DictReader(f) raw_data = [r for r in reader] mapping = {key_type(row[src]): row[dest] for row in raw_data} return mapping
bigcode/self-oss-instruct-sc2-concepts
def set_axis(mode_pl): """Sets Active Axes for View Orientation. Note: Sets indices for axes from taper vectors Axis order: Rotate Axis, Move Axis, Height Axis Args: mode_pl: Taper Axis Selector variable as input Returns: 3 Integer Indicies. """ order = { "RX-MY": (0, 1, 2), "RX-MZ": (0, 2, 1), "RY-MX": (1, 0, 2), "RY-MZ": (1, 2, 0), "RZ-MX": (2, 0, 1), "RZ-MY": (2, 1, 0), } return order[mode_pl]
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_pickle(pickle_path): """Utility function for loading .pkl pickle files. Arguments --------- pickle_path : str Path to pickle file. Returns ------- out : object Python object loaded from pickle. """ with open(pickle_path, "rb") as f: out = pickle.load(f) return out
bigcode/self-oss-instruct-sc2-concepts
def update_params(params, **kwargs): """ Updates a dictionary with the given keyword arguments Parameters ---------- params : dict Parameter dictionary **kwargs : kwargs New arguments to add/update in the parameter dictionary Returns ------- params : dict Updated parameter dictionary """ for kwarg in kwargs: if kwargs.get(kwarg, None)!=None: params[kwarg]=kwargs[kwarg] return params
bigcode/self-oss-instruct-sc2-concepts
def docker_push_age(filename): """Check when the Docker image was last pushed to Docker Hub.""" try: with open(filename, "r") as handle: return float(handle.read().strip()) except FileNotFoundError: return 0
bigcode/self-oss-instruct-sc2-concepts
def is_triangle(triangle: int): """any tn in triangle sequence is t = ½n(n+1): Solving with quadratic formula reveals n is only an integer if (1+8t) ** 0.5 is an integer and odd""" if int((1+8*triangle)**0.5) == (1+8*triangle)**0.5 and ((1+8*triangle)**0.5)%2 == 1: return True return False
bigcode/self-oss-instruct-sc2-concepts
import re def make_write_file_block(content:str, outname:str, directory:str='/usr/local/etc/ehos/'): """ makes a yaml write_file content block Args: content: what to enter as content into the block outname: the filename the yaml points to directory: the directory the yaml points to Returns write_file block for a yaml file (str) Raises: None """ block = """- content: | {content} path: {filepath} owner: root:root permissions: '0644' """ # pad the write_file_block with 8 whitespaces to ensure yaml integrity content = re.sub("\n", "\n ", " "+content) block = re.sub('{filepath}', "{}/{}".format(directory, outname), block) block = re.sub('{content}', "{}".format(content), block) return block
bigcode/self-oss-instruct-sc2-concepts
def flatten_dict(a_dict, parent_keys=None, current_parent_key=None): """Given a dict as input, return a version of the dict where the keys are no longer nested, and instead flattened. EG: >>> flatten_dict({"a": {"b": 1}}) {"a.b": 1} NB: The kwargs are only for internal use of the function and should not be used by the caller. """ if parent_keys is None: parent_keys = [] for key, value in a_dict.items(): if current_parent_key: key = "%s.%s" % (current_parent_key, key) if isinstance(value, dict): flatten_dict(value, parent_keys=parent_keys, current_parent_key=key) else: parent_keys.append((key, value)) return dict(parent_keys)
bigcode/self-oss-instruct-sc2-concepts
def filter(record): """ Filter for testing. """ return record if record["str"] != "abcdef" else None
bigcode/self-oss-instruct-sc2-concepts
def sort(source_list, ignore_case=False, reverse=False): """ :param list source_list: The list to sort :param bool ignore_case: Optional. Specify true to ignore case (Default False) :param bool reverse: Optional. Specify True to sort the list in descending order (Default False) :return: The sorted list :rtype: list >>> sort( ['Bad','bored','abe','After']) ['After', 'Bad', 'abe', 'bored'] >>> sort( ['Bad','bored','abe','After'], ignore_case=True) ['abe', 'After', 'Bad', 'bored'] """ sorted_list = source_list.copy() if ignore_case: sorted_list.sort(key=lambda s: s.casefold(), reverse=reverse) else: sorted_list.sort(reverse=reverse) return sorted_list
bigcode/self-oss-instruct-sc2-concepts
def get_scene(videoname): """ActEV scene extractor from videoname.""" s = videoname.split("_S_")[-1] s = s.split("_")[0] return s[:4]
bigcode/self-oss-instruct-sc2-concepts
def VtuFieldComponents(vtu, fieldName): """ Return the number of components in a field """ return vtu.ugrid.GetPointData().GetArray(fieldName).GetNumberOfComponents()
bigcode/self-oss-instruct-sc2-concepts
def get_note_title(note): """get the note title""" if 'title' in note: return note['title'] return ''
bigcode/self-oss-instruct-sc2-concepts
def merge(source, target): """Merge a source dictionary into a target dictionary :param source: source dictionary :param target: target dictionary :return: source merged into target """ for key, value in source.items(): if isinstance(value, dict): # get node or create one if key in target and not target[key]: target[key] = {} node = target.setdefault(key, {}) merge(value, node) else: if key in target: target_value = target[key] if isinstance(target_value, list) and isinstance(value, list): target_value.extend(value) target[key] = target_value else: target[key] = value return target
bigcode/self-oss-instruct-sc2-concepts
def get_type_and_tile(erow): """ Trivial function to return the OBSTYPE and the TILEID from an exposure table row Args: erow, Table.Row or dict. Must contain 'OBSTYPE' and 'TILEID' as keywords. Returns: tuple (str, str), corresponding to the OBSTYPE and TILEID values of the input erow. """ return str(erow['OBSTYPE']).lower(), erow['TILEID']
bigcode/self-oss-instruct-sc2-concepts
def inject(variables=None, elements=None): """ Used with elements that accept function callbacks. :param variables: Variables that will be injected to the function arguments by name. :param elements: Elements that will be injected to the function arguments by name. """ def wrapper(fn): fn.inject = { 'variables': variables or [], 'elements': elements or [] } return fn return wrapper
bigcode/self-oss-instruct-sc2-concepts
def increment(number): """Increases a give number by 1.""" return number + 1
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Tuple def three_variables_large_mean_differences() -> List[Tuple[Tuple[float, float, float], float]]: """Each entry represents three random variables. The format is: ( (mean1, mean2, mean3), covariance_scale ) and covariance scale controls how big the covariance between any two variables can be. Note: this data set is created in such way that differences between means are always much larger than any covariances. This makes the approximation very accurate. """ return [ ((1.0, 10.0, 20.0), 0.1), ((2.0, 9.0, 25.1), 1.0), ((0.1, 3.0, 5.0), 0.1), ]
bigcode/self-oss-instruct-sc2-concepts
def pivot_genres(df): """Create a one-hot encoded matrix for genres. Arguments: df -- a dataFrame containing at least the columns 'movieId' and 'genre' Output: a matrix containing '0' or '1' in each cell. 1: the movie has the genre 0: the movie does not have the genre """ return df.pivot_table(index = 'business_id', columns = 'categorie', aggfunc = 'size', fill_value=0)
bigcode/self-oss-instruct-sc2-concepts
def check_error(http): """ Checks for http errors (400 series) and returns True if an error exists. Parameters ---------- http : addinfourl whose fp is a socket._fileobject Returns ------- has_error : bool """ err = http.code if 400<= err < 500: print("HTTP error {}. Make sure your PV exists.".format(err)) return True return False
bigcode/self-oss-instruct-sc2-concepts
def bproj(M, P): """Project batched marices using P^T M P Args: M (torch.tensor): batched matrices size (..., N, M) P (torch.tensor): Porjectors size (..., N, M) Returns: torch.tensor: Projected matrices """ return P.transpose(1, 2) @ M @ P
bigcode/self-oss-instruct-sc2-concepts
def is_sequence(nums): """Return True if a set of numbers is sequential i.e. 8, 11, 14, 17.""" nums = sorted(list(nums)) if len(nums) < 3: return False while nums: first_difference = nums[1] - nums[0] second_difference = nums[2] - nums[1] if first_difference != second_difference: return False if len(nums) < 4: break nums.pop(0) return True
bigcode/self-oss-instruct-sc2-concepts
def PickUpTextBetween(text,startstr,endstr): """ Pick up lines between lines having "stratstr" and "endstr" strings :param str text: text data :param str startstr: start string :param str endstr: end string :return: text list :rtype: lst """ rtext=""; start=False for ss in text: s=ss.strip(); s.replace('\n','') if start: if endstr != "": if s.find(endstr) >=0: start=False else: if s.strip() == "": start=False if not start: continue if not start: if startstr != "": if s.find(startstr) >=0: start=True else: if s.strip() == "": start=True if start: continue if start: rtext=rtext+ss+"\n" return rtext
bigcode/self-oss-instruct-sc2-concepts
from typing import Set from pathlib import Path import yaml def _ci_patterns() -> Set[str]: """ Return the CI patterns given in the CI config file. """ repository_root = Path(__file__).parent.parent ci_file = repository_root / '.github' / 'workflows' / 'ci.yml' github_workflow_config = yaml.safe_load(ci_file.read_text()) matrix = github_workflow_config['jobs']['build']['strategy']['matrix'] ci_pattern_list = matrix['ci_pattern'] ci_patterns = set(ci_pattern_list) assert len(ci_pattern_list) == len(ci_patterns) return ci_patterns
bigcode/self-oss-instruct-sc2-concepts
def get_center(bounds): """ Returns given element center coords:: from magneto.utils import get_center element = self.magneto(text='Foo') (x, y) = get_center(element.info['bounds']) :param dict bounds: Element position coordinates (top, right, bottom, left) :return: x and y coordinates of element center """ x = bounds['right'] - ((bounds['right'] - bounds['left']) / 2) y = bounds['bottom'] - ((bounds['bottom'] - bounds['top']) / 2) return x, y
bigcode/self-oss-instruct-sc2-concepts
def check_kwargs(input_kwargs, allowed_kwargs, raise_error=True): """Tests if the input `**kwargs` are allowed. Parameters ---------- input_kwargs : `dict`, `list` Dictionary or list with the input values. allowed_kwargs : `list` List with the allowed keys. raise_error : `bool` Raises error if ``True``. If ``False``, it will raise the error listing the not allowed keys. """ not_allowed = [i for i in input_kwargs if i not in allowed_kwargs] if raise_error: if len(not_allowed) > 0: allowed_kwargs.sort() raise TypeError("function got an unexpected keyword argument {}\n" "Available kwargs are: {}".format(not_allowed, allowed_kwargs)) else: return not_allowed
bigcode/self-oss-instruct-sc2-concepts