seed
stringlengths
1
14k
source
stringclasses
2 values
def trim_block(multiline_str): """Remove empty lines and leading whitespace""" result = "" for line in multiline_str.split("\n"): line = line.lstrip() if line != '': result += "%s\n" % line return result.rstrip()
bigcode/self-oss-instruct-sc2-concepts
def intersect_trees(tree1, tree2): """Shrink two trees to contain only overlapping taxa. Parameters ---------- tree1 : skbio.TreeNode first tree to intersect tree2 : skbio.TreeNode second tree to intersect Returns ------- tuple of two TreeNodes resulting trees containing only overlapping taxa """ taxa1 = [tip.name for tip in tree1.tips()] taxa2 = [tip.name for tip in tree2.tips()] n1, n2 = len(taxa1), len(taxa2) taxa1, taxa2 = set(taxa1), set(taxa2) if n1 != len(taxa1) or n2 != len(taxa2): raise ValueError('Either tree has duplicated taxa.') taxa_lap = taxa1.intersection(taxa2) if len(taxa_lap) == 0: raise KeyError('Trees have no overlapping taxa.') tree1_lap = tree1.shear(taxa_lap) tree2_lap = tree2.shear(taxa_lap) return (tree1_lap, tree2_lap)
bigcode/self-oss-instruct-sc2-concepts
def filter_none(kwargs): """ Remove all `None` values froma given dict. SQLAlchemy does not like to have values that are None passed to it. :param kwargs: Dict to filter :return: Dict without any 'None' values """ n_kwargs = {} for k, v in kwargs.items(): if v: n_kwargs[k] = v return n_kwargs
bigcode/self-oss-instruct-sc2-concepts
def _quote(text): """Enclose the string with quotation characters""" return '\'{0}\''.format(text)
bigcode/self-oss-instruct-sc2-concepts
def filter_by_year(df, filter_cat="conc_yy", year=1990): """Filter df by year, either with conception year ('conc_yy') or birth year ('dob_yy') """ df = ( df[df[filter_cat] == year] .groupby( [ "conc_yy", "conc_month", "dob_yy", "birth_month", "conc_mm", "dob_mm", ], as_index=False, ) .sum() ) if filter_cat == "conc_yy": df = df.sort_values(by=["conc_mm"]).reset_index(drop=True) return df else: df = df.sort_values(by=["dob_mm"]).reset_index(drop=True) return df
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import shutil def get_config(repo_path: Path, filename: str) -> Path: """Get a config file, copied from the test directory into repo_path. :param repo_path: path to the repo into which to copy the config file. :param filename: name of the file from the test directory. :return: the path to the copied config file. """ config_src = Path(__file__).parent / filename config_file = repo_path / config_src.name shutil.copy(config_src, config_file) return config_file
bigcode/self-oss-instruct-sc2-concepts
def create_tag_cloud_html(tag_cloud_name, tags, level_weights): """Create HTML code for the tag cloud. ``tag_cloud_name`` is the CSS style name used for the generated tag cloud. It should be the same value as passed to ``create_tag_cloud_css``. ``tags`` and ``level_weights`` are the return values of ``create_tag_cloud_data``. """ result = '<div id="' + tag_cloud_name + '">' result += ' '.join(['<a href="{1}" class="{2}">{0}</a>'.format(name, url, tag_cloud_name + str(level_index)) for _, name, level_weight, level_index, url in tags]) result += '</div>' return result
bigcode/self-oss-instruct-sc2-concepts
def get_tables_from_mapping(source_table, dest_fields, source_dest_map): """ Obtain a petl tables from a source petl table and some mappings source_table: petl table dest_fields: list source_dest_map: dict Returns dest_table: petl table """ source_fields = list(source_table.header()) # Build up trns_table and spl_table from the source_table dest_table = source_table.addrownumbers() # Add the new fields one at a time. There might be a better # way to do this. for field in dest_fields: if field in source_dest_map: dest_table = dest_table.addfield(field, source_dest_map[field]) else: dest_table = dest_table.addfield(field, '') # Cut out the original columns from the source_table to obtain # the destination tables, trns_table and spl_table dest_table = dest_table.cutout(*source_fields) dest_table = dest_table.cutout('row') return dest_table
bigcode/self-oss-instruct-sc2-concepts
def second(xs): """Grab the second item from a list-like thing.""" return xs[1]
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable import re def remove_link_ids() -> Callable[[str], str]: """Create function to remove link ids from rendered hyperlinks.""" def _remove_link_ids(render: str) -> str: """Remove link ids from rendered hyperlinks.""" re_link_ids = re.compile(r"id=[\d\.\-]*?;") subsituted_render = re_link_ids.sub("id=0;", render) return subsituted_render return _remove_link_ids
bigcode/self-oss-instruct-sc2-concepts
def fails_if_called(test, msg="This function must not be called.", arguments=True): """ Return a new function (accepting any arguments) that will call test.fail(msg) if it is called. :keyword bool arguments: If set to ``False``, then we will not accept any arguments. This can avoid masking when we would expect a TypeError to be raised by calling an instance method against a class. """ if not arguments: return lambda: test.fail(msg) return lambda *_args, **__kwargs: test.fail(msg)
bigcode/self-oss-instruct-sc2-concepts
def qualifiedClassName(obj): """ Utility method for returning the fully qualified class name of an instance. Objects must be instances of "new classes." """ return obj.__module__ + "." + type(obj).__name__
bigcode/self-oss-instruct-sc2-concepts
import torch def pairwise_distance(node_feature): """ Compute the l2 distance between any two features in a group of features :param node_feature: a group of feature vectors organized as batch_size x channels x number_of_nodes """ batch_size = node_feature.shape[0] node_feature = node_feature.squeeze() if batch_size == 1: node_feature = node_feature.unsqueeze(0) # print(node_feature.shape) assert (len(node_feature.shape) == 3) node_feature_t = node_feature.permute(0, 2, 1) node_feature_inner = -2 * torch.bmm(node_feature_t, node_feature) node_feature_square = node_feature**2 node_feature_square = node_feature_square.sum(dim=1, keepdim=True) node_feature_square_t = node_feature_square.permute(0, 2, 1) res = node_feature_square + node_feature_square_t + node_feature_inner return res
bigcode/self-oss-instruct-sc2-concepts
def is_six_band(frequency: int) -> bool: """determines if a channel frequency is in the 6.0-7.125 GHz ISM band""" if frequency > 5900 and frequency < 7125: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def setify(i): """ Iterable to set. """ return set(i)
bigcode/self-oss-instruct-sc2-concepts
from typing import Set def compute_number_of_edge_types( tied_fwd_bkwd_edge_types: Set[int], num_fwd_edge_types: int, add_self_loop_edges: bool ) -> int: """Computes the number of edge types after adding backward edges and possibly self loops.""" return 2 * num_fwd_edge_types - len(tied_fwd_bkwd_edge_types) + int(add_self_loop_edges)
bigcode/self-oss-instruct-sc2-concepts
import re def uppercase_lowercase(a_string): """Assumes a_string is a string returns a boolean, True is a_string contains one upper case letter followed by lower case letters else False """ regex = "[A-Z][a-z]+" results = re.search(regex, a_string) return bool(results)
bigcode/self-oss-instruct-sc2-concepts
def _get_mean_dist(data: list): """ Calculates the average euclidian distance matrix from prior training c-means. ----------------------------------------------------------------------------------- !!! For statistical evaluation !!! ----------------------------------------------------------------------------------- Parameters: ----------------------------------------------------------------------------------- data: List (ndarray, int) Result from fcm_train(). Returns: ----------------------------------------------------------------------------------- mean_dist: 2d array, (S, N) Average final Euclidian distance matrix. """ mean_dist = data[0][3] / len(data) # Starting with the distance matrix of the 1st image for i in range(1, len(data)): mean_dist += data[i][3] / len(data) # Adding the distance matrices from all other images return mean_dist
bigcode/self-oss-instruct-sc2-concepts
def gray_augment(is_training=True, **kwargs): """Applies random grayscale augmentation.""" if is_training: prob = kwargs['prob'] if 'prob' in kwargs else 0.2 return [('gray', {'prob': prob})] return []
bigcode/self-oss-instruct-sc2-concepts
def winsorize_at_explicit_input(x, lower_bound, upper_bound): """ Winsorizes the array x at the lower_bound and upper_bound. :param x: a numpy array-like object :param lower_bound: a scalar for the lower bound :param upper_bound: a scalar for the upper bound :return: the winsorized array """ ret = x ret[x < lower_bound] = lower_bound ret[x > upper_bound] = upper_bound return ret
bigcode/self-oss-instruct-sc2-concepts
def _parse_str_to_dict(x): """Convert "k1:v1,k2:v2" string to dict Args: x (str): Input string Returns: dict: Dictionary {"k1": "v1", "k2": "v2"} """ d = {} for p in x.split(","): if ":" in p: k, v = p.split(":") d[k] = v return d
bigcode/self-oss-instruct-sc2-concepts
def subject_tag_get_all(client, subject_id, session=None): """Get a list of tags for a specific subject.""" return client.subject_tag_get_all(subject_id=subject_id)
bigcode/self-oss-instruct-sc2-concepts
def _extract_fields_from_row(row, element): """Pluck data from the provided row and element.""" row_data = [] fields = row.find_all(element) for raw_field in fields: field = raw_field.text.strip() row_data.append(field) return row_data
bigcode/self-oss-instruct-sc2-concepts
def normalize_brightness_dict(brightness_dict): """Usually the distribution of the character brightness for a given font is not as diverse as we would like it to be. This results in a pretty poor result during the image to ASCII art conversion (if used as-is). Because of this it's much better to normalize the brightness distribution. Normalization widens the distribution ranges to 8-bit 0-255 range. Args: brightness_dict (dict): A map of characters to brightness. Returns: dict: normalized map of characters to brightness. """ b_min, b_max = 255, 0 for brightness in brightness_dict.values(): b_min = min(b_min, brightness) b_max = max(b_max, brightness) def widen(b): """Using the min and max bounds to widen the char brightness""" return int(round( ( (b - b_min) / (b_max - b_min) ) * 255 )) return {char: widen(brightness) for char, brightness in brightness_dict.items()}
bigcode/self-oss-instruct-sc2-concepts
def all_smaller(nums1: set, nums2: set) -> bool: """Return whether every number in nums1 is less than every number in num2. You may ASSUME that: - nums1 is non-empty - nums2 is non-empty - nums1 and nums2 contain only integers and/or floats >>> all_smaller({2}, {3}) True >>> all_smaller({3}, {2}) False >>> all_smaller({2, 3}, {2, 3}) False >>> all_smaller({1, 2, 3}, {4, 5, 6}) True >>> all_smaller({-100, -101}, {-1, 0}) True >>> all_smaller({0.11}, {0.1}) False >>> all_smaller({-0.01}, {-0.009}) True Hint: use the min and max functions. """ assert len(nums1) != 0 assert len(nums2) != 0 return max(nums1) < min(nums2)
bigcode/self-oss-instruct-sc2-concepts
def treasury_bill_price(discount_yield, days_to_maturity): """Computes price ot treasury bill""" return 100 * (1 - days_to_maturity / 360 * discount_yield)
bigcode/self-oss-instruct-sc2-concepts
import torch def _get_test_data(with_boundary=True, identical=True): """ Produces test data in the format [Batch size x W x H], where batch size is 2, W=3 and H=3. In the first batch the pixel at 3,2 is a boundary pixel and in the second pixel at 1,2 :param with_boundary: bool if true there is a boundary pixel like described :param identical: bool if true pred and trues are the same :return: """ device = torch.device('cpu') # 0 = Background; 1 = Text # 0, 0, 0 ; 0, (1), 0 # 0, 1, 0 ; 0, 0, 0 # 0, 1, 0 ; 1, 1, 1 # batch size 2; 3x3; () --> masked label_trues = torch.tensor([[[0, 0], [0, 1], [0, 0]], [[0, 0], [1, 0], [0, 0]], [[0, 1], [1, 1], [0, 1]]], device=device) # 0, 0, 0 ; 0, [0], 0 # 0, 1, 0 ; 0, 0, 0 # 0, [0], 0 ; 1, 1, 1 label_preds = torch.tensor([[[0, 0], [0, 1], [0, 0]], [[0, 0], [1, 0], [0, 0]], [[0, 1], [1, 1], [0, 1]]], device=device) if not identical: label_preds[0, 1, 1] = 0 label_preds[2, 1, 0] = 0 num_classes = len(label_trues.unique()) mask = torch.tensor([[[False, False], [False, True], [False, False]], [[False, False], [False, False], [False, False]], [[False, False], [False, False], [False, False]]], device=device) if not with_boundary: mask[:] = False return label_preds, label_trues, num_classes, mask
bigcode/self-oss-instruct-sc2-concepts
def _analyse_gdal_output(output): """ Analyse the output from gpt to find if it executes successfully. Parameters ---------- output : str Ouptut from gpt. Returns ------- flag : boolean False if "Error" is found and True if not. """ # return false if "Error" is found. if 'error' in output.lower(): return False # return true if "100%" is found. elif '100 - done' in output.lower(): return True # otherwise return false. else: return False
bigcode/self-oss-instruct-sc2-concepts
def normalized_current_date(datetime_col, min_date, max_date): """ Temporal feature indicating the position of the date of a record in the entire time period under consideration, normalized to be between 0 and 1. Args: datetime_col: Datetime column. min_date: minimum value of date. max_date: maximum value of date. Returns: float: the position of the current date in the min_date:max_date range """ date = datetime_col.dt.date current_date = (date - min_date).apply(lambda x: x.days) if max_date != min_date: current_date = current_date / (max_date - min_date).days elif max_date == min_date: current_date = 0 return current_date
bigcode/self-oss-instruct-sc2-concepts
def _is_permutation_winning(my, result, count): """判断是否匹配(排列方式) my: 排列数1 result: 排列数2 count: 匹配的位数 e.g.: my = [9,9,8,5,6,3,8] result = [2,0,3,5,6,4,9] count = 2 return is True """ s, e = 0, count #逐个切片 while e <= len(result): if my[s:e] == result[s:e]: return True s += 1 e += 1 return False
bigcode/self-oss-instruct-sc2-concepts
import string import random def random_string_generator(size=10, chars=string.ascii_uppercase + string.digits): """ Generate a random string of `size` consisting of `chars` """ return ''.join(random.choice(chars) for _ in range(size))
bigcode/self-oss-instruct-sc2-concepts
import torch def sequence_mask(lengths, maxlen, dtype=None): """ Exact same behavior as tf.sequence_mask. Thanks to Dimitris Papatheodorou (https://discuss.pytorch.org/t/pytorch-equivalent-for-tf-sequence-mask/ 39036). """ if maxlen is None: maxlen = lengths.max() mask = ~(torch.ones((len(lengths), maxlen)).cumsum(dim=1).t() > lengths). \ t() mask.type(dtype or torch.bool) return mask
bigcode/self-oss-instruct-sc2-concepts
def ensure_list_or_tuple(obj): """ Takes some object and wraps it in a list - i.e. [obj] - unless the object is already a list or a tuple instance. In that case, simply returns 'obj' Args: obj: Any object Returns: [obj] if obj is not a list or tuple, else obj """ return [obj] if not isinstance(obj, (list, tuple)) else obj
bigcode/self-oss-instruct-sc2-concepts
import requests def get_agents(url, agents_tag, headers): """Get the agents.""" req = requests.get(url + "/agents/", headers=headers) if req.status_code != 200: raise ValueError("Unable to get the token") return [a for a in req.json()["results"] if agents_tag in a["parameters"]["tags"]]
bigcode/self-oss-instruct-sc2-concepts
def section(name): """ Returns regex matching the specified section. Case is ignored in name. """ return r'(?<=\n)={2,} *' + fr'(?i:{name})' + r' *={2,}'
bigcode/self-oss-instruct-sc2-concepts
import time import re def to_kubernetes_name(name, prefix=""): """ Returns a valid and unique kubernetes name based on prefix and name, replacing characters in name as necessary see https://kubernetes.io/docs/concepts/overview/working-with-objects/names/ """ unique_id = str(time.time()).replace(".", "-") safe_name = re.sub("[^0-9a-zA-Z\\-]+", "-", name) return f"{prefix}{safe_name}-{unique_id}"[:63]
bigcode/self-oss-instruct-sc2-concepts
def target_state(target_dict): """Converting properties to target states Args: target_dict: dictionary containing target names as keys and target objects as values Returns: dictionary mapping target name to its state """ if {} == target_dict: return None result = {} for key, value in target_dict.iteritems(): if not value.repaired: result[key] = "cut" elif value.targetable: result[key] = "targetable" else: result[key] = "untargetable" return result
bigcode/self-oss-instruct-sc2-concepts
def F_calc(TP, FP, FN, beta): """ Calculate F-score. :param TP: true positive :type TP: int :param FP: false positive :type FP: int :param FN: false negative :type FN: int :param beta: beta coefficient :type beta: float :return: F-score as float """ try: result = ((1 + (beta)**2) * TP) / \ ((1 + (beta)**2) * TP + FP + (beta**2) * FN) return result except (ZeroDivisionError, TypeError): return "None"
bigcode/self-oss-instruct-sc2-concepts
def title_case(sentence): """ Capitalize the first letter of every word. Parameters ---------------- sentence: string The sentence to be put into title case. Returns ---------------- capitalized: string The input string in title case. """ if sentence == sentence.upper(): capitalized = ' '.join([x[0].upper()+x[1:].lower() for x in sentence.strip().split()]) else: capitalized = ' '.join([x[0].upper()+x[1:] for x in sentence.strip().split()]) return capitalized
bigcode/self-oss-instruct-sc2-concepts
def testme(si): """Revert a string, filtering out the vowel characters""" so = ''.join([c for c in reversed(si) if c.lower() not in 'aeiouy']) return so, len(so)
bigcode/self-oss-instruct-sc2-concepts
import hashlib def get_md5(file: str) -> str: """ Get the md5code of file. :param file: The path of file. :return: The md5code of file """ m = hashlib.md5() with open(file, 'rb') as f: for line in f: m.update(line) md5code = m.hexdigest() return md5code
bigcode/self-oss-instruct-sc2-concepts
def mergeDicts(dict1, dict2): """Merge two dictionaries.""" res = {**dict1, **dict2} return res
bigcode/self-oss-instruct-sc2-concepts
def dict_keys_lower(d): """list of dictionary keys in lower case""" return list(map(str.lower, d.keys()))
bigcode/self-oss-instruct-sc2-concepts
def expand(x, y, cals, shown, length, width): """ Expand empty position with no bombs surrounded :param x: horizontal position :param y: vertical position :param cals: matrix of numbers :param shown: list of positions shown :param length: length of the board :param width: width of the board :return: modified list of positions shown """ for m in (x - 1, x, x + 1): for n in (y - 1, y, y + 1): if 0 <= m < length and 0 <= n < width: if (m != x or n != y) and (m, n) not in shown: shown.append((m, n)) if cals[m][n] == 0: expand(m, n, cals, shown, length, width) return shown
bigcode/self-oss-instruct-sc2-concepts
def get_batch_token_embeddings(layer_hidden_states, attention_mask, rm_special_tokens=False): """ remove padding and special tokens Args: layer_hidden_states: (N, L, D) attention_mask: (N, L) with 1 indicate valid bits, 0 pad bits rm_special_tokens: bool, whether to remove special tokens, this is different for different model_type 1) a RoBERTa sequence has the following format: <s> X </s> return: list(np.ndarray), each ndarray is (L_sentence, D), where L_sentence <= L """ valid_lengths = attention_mask.sum(1).long().tolist() # (N, ) layer_hidden_states = layer_hidden_states.cpu().numpy() embeddings = [e[1:vl-1] if rm_special_tokens else e[:vl] for e, vl in zip(layer_hidden_states, valid_lengths)] return embeddings
bigcode/self-oss-instruct-sc2-concepts
import copy def get_social_config(env): """ Arguments: env: Arena-Blowblow-Sparse-2T2P-Discrete Returns: [[0,1],[2,3]] """ xTxP = env.split("-")[-2] T = int(xTxP.split("T")[0]) P = int(xTxP.split("T")[1].split("P")[0]) policy_i = 0 all_list = [] for t in range(T): t_list = [] for p in range(P): t_list += [copy.deepcopy(policy_i)] policy_i += 1 all_list += [copy.deepcopy(t_list)] return all_list
bigcode/self-oss-instruct-sc2-concepts
def delete_at(my_list=[], idx=0): """ deletes an element from a list at a given index """ l_len = len(my_list) if idx >= l_len or idx < 0: return (my_list) del my_list[idx] return (my_list)
bigcode/self-oss-instruct-sc2-concepts
import random def _get_pin(length=5): """ Return a numeric PIN with length digits """ return random.sample(range(10**(length-1), 10**length), 1)[0]
bigcode/self-oss-instruct-sc2-concepts
def swap_byte_order(arr_in): """Swap the byte order of a numpy array to the native one. Parameters ---------- arr_in : `~numpy.ndarray` Input array. Returns ------- arr_out : `~numpy.ndarray` Array with native byte order. """ if arr_in.dtype.byteorder not in ("=", "|"): return arr_in.byteswap().newbyteorder() return arr_in
bigcode/self-oss-instruct-sc2-concepts
def determineTranslation(translation,reference_orientation): """ Convert a translation in the world reference frame to a translation in the steroid reference frame. """ return translation*reference_orientation.I
bigcode/self-oss-instruct-sc2-concepts
def is_empty(value: object) -> bool: """ Check if value is None or not empty in case if not None. """ return (value is None) or (not value)
bigcode/self-oss-instruct-sc2-concepts
def count_attached(mol): """ Counts the number of atoms labelled 'attached'. Parameters ---------- mol : :class:`rdkit.Chem.rdchem.Mol` A molecule to have 'attached' atoms counted. Returns ------- :class:`int` The number of atoms with the property 'attached' in `mol`. """ return sum(1 for a in mol.GetAtoms() if a.HasProp('attached'))
bigcode/self-oss-instruct-sc2-concepts
def remove_method_from_itemname(itemname): """Return an itemname without any method name in it""" return itemname.split(':')[0]
bigcode/self-oss-instruct-sc2-concepts
def num(s): """Function will try to convert the variable to a float. If not possible it will return the original variable.""" try: return float(s) except: return s
bigcode/self-oss-instruct-sc2-concepts
import inspect def is_class(obj): """ Returns True if obj is a class, else False. """ return inspect.isclass(obj)
bigcode/self-oss-instruct-sc2-concepts
def sum_even_values(d: dict) -> int: """Returns the sum of all even values in d, using recursion if d contains nested dictionaries.""" total = 0 for value in d.values(): if type(value) == int: if not value % 2: total += value elif type(value) == dict: total += sum_even_values(value) return total
bigcode/self-oss-instruct-sc2-concepts
import re def string_builder(string): """ To match DaCe variable naming conventions, replaces all undesired characters with "_". """ newstring = string if string[0].isdigit(): newstring = "_" + string out = re.sub("[^a-zA-Z0-9_]", "_", newstring) return out
bigcode/self-oss-instruct-sc2-concepts
def translate_service_orm_to_json(orm): """Translate ORM to JSON for response payload.""" ret = {"service_id": orm.service_id, "schema": orm.schema, "config": {}} for config in orm.configs: if config.hostname not in ret["config"]: ret["config"][config.hostname] = {} ret["config"][config.hostname][config.schema] = config.config return ret
bigcode/self-oss-instruct-sc2-concepts
import inspect def _is_non_defaulted_positional_args(param: inspect.Parameter) -> bool: """Returns True if `param` is a positional argument with no default.""" return ((param.kind == param.POSITIONAL_OR_KEYWORD or param.kind == param.POSITIONAL_ONLY) and param.default is param.empty)
bigcode/self-oss-instruct-sc2-concepts
def idems(dit): """Convenience function for iterating dict-likes. If dit.items is defined, call it and return the result. Otherwise return dit itself. """ return dit.items() if hasattr(dit, 'items') else dit
bigcode/self-oss-instruct-sc2-concepts
def parse_data_url(data_url): """ Parse a data url into a tuple of params and the encoded data. E.g. >>> data_url = "data:image/png;base64,ABC123xxx" >>> params, encoded_data = parse_data_url(data_url) >>> params ('image/png', 'base64') >>> data 'ABC123xxx' """ # e.g. data:image/png;base64,xxx.. if not data_url.startswith('data:'): raise ValueError('not a data url') data_url = data_url[5:] params, data = data_url.split(',') params = params.split(';') return params, data
bigcode/self-oss-instruct-sc2-concepts
def are_strings(*args): """Tells wheter all the argument passed are of type string""" return all(map(lambda _: type(_) is str, args))
bigcode/self-oss-instruct-sc2-concepts
def get_host(environ): """ Return the real host for the given environment. """ if 'HTTP_X_FORWARDED_HOST' in environ: return environ['HTTP_X_FORWARDED_HOST'] elif 'HTTP_HOST' in environ: return environ['HTTP_HOST'] result = environ['SERVER_NAME'] if (environ['wsgi.url_scheme'], environ['SERVER_PORT']) not \ in (('https', '443'), ('http', '80')): result += ':' + environ['SERVER_PORT'] return result
bigcode/self-oss-instruct-sc2-concepts
def any_difference_of_one(stem, bulge): """ See if there's any difference of one between the two ends of the stem [(a,b),(c,d)] and a bulge (e,f) :param stem: A couple of couples (2 x 2-tuple) indicating the start and end nucleotides of the stem in the form ((s1, e1), (s2, e2)) :param bulge: A couple (2-tuple) indicating the first and last position of the bulge. :return: True if there is an overlap between the stem nucleotides and the bulge nucleotides. False otherwise """ for stem_part in stem: for part in stem_part: for bulge_part in bulge: if abs(bulge_part - part) == 1: return True return False
bigcode/self-oss-instruct-sc2-concepts
def fuzzy_not(mfx): """ Fuzzy NOT operator, a.k.a. complement of a fuzzy set. Parameters ---------- mfx : 1d array Fuzzy membership function. Returns ------- mfz : 1d array Fuzzy NOT (complement) of `mfx`. Notes ----- This operation does not require a universe variable, because the complement is defined for a single set. The output remains defined on the same universe. """ return 1. - mfx
bigcode/self-oss-instruct-sc2-concepts
def get_group_cv_splits(groups, cv): """ Presplit the groups using the given cross-validation scheme. Normally, the train/test split is done right before training and testing, but this function will presplit the data for all cross folds before any training/testing is done. This is useful for keeping the training and testing sets consistent between cross-predictions. """ groups_cv_splits = [] for group in groups: group_cv = [(train, test) for train, test in cv.split(group[0])] groups_cv_splits.append(group_cv) return groups_cv_splits
bigcode/self-oss-instruct-sc2-concepts
def power_pump(flate_pump_feed, rho_F, g, head_pump, ECE_motor, ECE_trans): """ Calculates the power of pump. Parameters ---------- flate_pump_feed : float The flow rate pump for Feed [m**3 / h] rho_F : float The density of feed, [kg / m**3] head_pump : float The hydraulic head of pump, [m] ECE_motor : float The energy conversion efficiency of motor, [dismensionless] ECE_trans : float The energy conversion efficiency of transfer, [dismensionless] Returns ------- power_pump : float The power of pump, [kW] References ---------- &&&& """ return (flate_pump_feed * rho_F * g * head_pump / (ECE_motor * ECE_trans))
bigcode/self-oss-instruct-sc2-concepts
def bin2hex(strbin): """ Convert a string representing a binary number into a string representing the same value in hexadecimal format. """ dic = { "0000":"0", "0001":"1", "0010":"2", "0011":"3", "0100":"4", "0101":"5", "0110":"6", "0111":"7", "1000":"8", "1001":"9", "1010":"A", "1011":"B", "1100":"C", "1101":"D", "1110":"E", "1111":"F" } while strbin.__len__()%4 != 0: strbin = '0' + strbin strh = "" for i in range(0, strbin.__len__()/4): strh = strh + dic[str(strbin[i*4:i*4+4])] return strh
bigcode/self-oss-instruct-sc2-concepts
def walk_derivation(derivation, combiner, leaf): """ Traverse a derivation as returned by parser.item.Chart.kbest. Apply combiner to a chart Item and a dictionary mapping nonterminals (and indices) to the result of all child items. """ if type(derivation) is not tuple: if derivation == "START": return None return leaf(derivation) else: item, children = derivation[0], derivation[1] childobjs = dict([(rel, walk_derivation(c, combiner, leaf)) for (rel, c) in children.items()]) if item == "START": return childobjs["START"] return combiner(item, childobjs)
bigcode/self-oss-instruct-sc2-concepts
import re def get_skipped_reason(data): """Return test case skip reason from report string. Args: data(str): test case report Returns: str: skip reason or None """ try: reason_rules = re.compile("Skipped:(.*?)..$") return ('\n'.join(reason_rules.findall(data))).strip() except TypeError: return None
bigcode/self-oss-instruct-sc2-concepts
import binascii import logging def checkHeader(filename, headers, size): """ The checkHeader function reads a supplied size of the file and checks against known signatures to determine the file type. :param filename: The name of the file. :param headers: A list of known file signatures for the file type(s). :param size: The amount of data to read from the file for signature verification. :return: Boolean, True if the signatures match; otherwise, False. """ with open(filename, 'rb') as infile: header = infile.read(size) hex_header = binascii.hexlify(header) for signature in headers: if hex_header == signature: return True else: pass logging.warn('The signature for {} ({}) does not match known signatures: {}'.format( filename, hex_header, headers)) return False
bigcode/self-oss-instruct-sc2-concepts
def replace_tup(tupl, old, new, count=-1): """ Creates a copy of ``tupl`` with all occurrences of value ``old`` replaced by ``new``. Objects are replaced by value equality, not id equality (i.e. ``==`` not ``is``). If the optional argument ``count`` is given, only the first count occurrences are replaced. :param tupl: The tuple to copy :type tupl: ``tuple`` :param old: The old value to replace :type old: ``any`` :param new: The new value to replace with :type new: ``any`` :param count: The number of occurrences to replace :type count: ``int`` :return: A copy of ``tupl`` with all occurrences of value ``old`` replaced by ``new``. :rtype: ``tuple`` """ assert type(tupl) == tuple, '%s is not a tuple' % tupl result = [] count = len(tupl) if count == -1 else count match = 0 for item in tupl: if item == old and match < count: result.append(new) match += 1 else: result.append(item) return tuple(result)
bigcode/self-oss-instruct-sc2-concepts
def identifier_to_flag(identifier): """ Turn an identifier back into its flag format (e.g., "Flag" -> --flag). """ if identifier.startswith('-'): raise ValueError('expected identifier, not flag name: %r' % identifier) ret = identifier.lower().replace('_', '-') return '--' + ret
bigcode/self-oss-instruct-sc2-concepts
import csv def write_csv(csv_list, filename): """ writes a single csv file to the current directory :param csv_list: 2d list containing the csv contents :param filename: name of the newly created csv file :return: True if write successful, False if not """ try: with open(filename, mode='w') as csv_file: csv_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) for row in csv_list: csv_writer.writerow([col for col in row]) return True except IOError: print("Error: could not create {}".format(filename)) return False
bigcode/self-oss-instruct-sc2-concepts
def ptsort(tu): """Return first element of input.""" return tu[0]
bigcode/self-oss-instruct-sc2-concepts
def probe(value): """ Factorization of n by probing. :param n: value to factorize. :returns: all proper divisors of n. >>> probe(10) [1, 2, 5, 10] >>> probe(12) [1, 2, 3, 4, 6, 12] """ value = abs(value) limit = value // 2 divisors = [1] divisor = 2 while divisor <= limit: if value % divisor == 0: divisors.append(divisor) divisor += 1 if not value == 1: divisors.append(value) return divisors
bigcode/self-oss-instruct-sc2-concepts
def find_ancilla_values(counts, ancilla_qubits, ancilla_location = 0): """Returns a dictionary with a count of each possible ancilla bit string. Parameters ---------- counts : dictionary counts for each possible output bit string ancilla_qubits : int number of ancilla qubits ancilla_location : int designates which bit string is relevant Returns ------- ancilla_values : dict dictionary containing the count of each possible ancilla bit string """ #build a list of all the possible ancilla in binary possible_ancilla_list = [] format_string = '0' + str(ancilla_qubits) + 'b' for i in range(2 ** (ancilla_qubits)): possible_ancilla_value = format(i, format_string) possible_ancilla_list.append(possible_ancilla_value) #use the list to initialise a dictionary which hold the results by ancilla ancilla_values = {i:0 for i in possible_ancilla_list} # loop through the results and summarise by ancilla for key, value in counts.items(): #split out the ancilla part of key ancilla = key.split()[ancilla_location] old_count = ancilla_values[ancilla] new_count = old_count + value ancilla_values[ancilla] = new_count return(ancilla_values)
bigcode/self-oss-instruct-sc2-concepts
def destroy_lvol_store(client, uuid=None, lvs_name=None): """Destroy a logical volume store. Args: uuid: UUID of logical volume store to destroy (optional) lvs_name: name of logical volume store to destroy (optional) Either uuid or lvs_name must be specified, but not both. """ if (uuid and lvs_name) or (not uuid and not lvs_name): raise ValueError("Exactly one of uuid or lvs_name must be specified") params = {} if uuid: params['uuid'] = uuid if lvs_name: params['lvs_name'] = lvs_name return client.call('destroy_lvol_store', params)
bigcode/self-oss-instruct-sc2-concepts
def url_normalize(url: str): """ Convert a URL into the standard format """ if url.startswith('//'): return 'http:' + url if url.startswith('www'): return 'http://' + url if not url.startswith('http'): return 'http://' + url return url
bigcode/self-oss-instruct-sc2-concepts
def gaze_duration(interest_area, fixation_sequence): """ Given an interest area and fixation sequence, return the gaze duration on that interest area. Gaze duration is the sum duration of all fixations inside an interest area until the area is exited for the first time. """ duration = 0 for fixation in fixation_sequence.iter_without_discards(): if fixation in interest_area: duration += fixation.duration elif duration > 0: break # at least one previous fixation was inside the IA and this fixation is not, so break return duration
bigcode/self-oss-instruct-sc2-concepts
def decrypt(ciphertext, cipher, shift): """ Caesar decryption of a ciphertext using a shifted cipher. :param ciphertext: the encrypted plaintext to decrypt. :param cipher: set of characters, shifted in a directed to used for character substitution. :param shift: offset to rotate cipher. :returns: decrypted cyphertext (plaintext). See: https://en.wikipedia.org/wiki/Caesar_cipher Example: >>> decrypt("gdkknzvnqkc", "abcdefghijklmnopqrstuvwxyz ", 1) 'hello world' >>> decrypt("ifmmpaxpsme", "abcdefghijklmnopqrstuvwxyz ", -1) 'hello world' """ # calculating shifted cipher shifted_cipher = cipher if shift > 0: while shift > 0: shifted_cipher = shifted_cipher[-1] + shifted_cipher[0:len(shifted_cipher) - 1] shift -= 1 else: while shift < 0: shifted_cipher = shifted_cipher[1:] + shifted_cipher[0] shift += 1 return "".join([cipher[shifted_cipher.index(character)] for character in ciphertext])
bigcode/self-oss-instruct-sc2-concepts
import glob def make_fileslist(path_list): """Get lists of files from paths which may contains wildcards and symbols.""" ret = [] for p in path_list: ret += glob.glob(p) return ret
bigcode/self-oss-instruct-sc2-concepts
def T1_sequence(length, target): """ Generate a gate sequence to measure relaxation time in a two-qubit chip. Parameters ---------- length : int Number of Identity gates. target : int Which qubit is measured. Returns ------- list Relaxation sequence. """ wait = ["Id"] prepare_1 = [f"rx90p[{str(target)}]"] * 2 S = [] S.extend(prepare_1) S.extend(wait * length) return S
bigcode/self-oss-instruct-sc2-concepts
def create_element(doc, parent, tag, value=None, attributes=None): """ Creates an XML element """ ele = doc.createElement(tag) parent.appendChild(ele) if value: text = doc.createTextNode(u"%s" % value) ele.appendChild(text) if attributes: [ele.setAttribute(k, str(v)) for k, v in attributes.items()] return ele
bigcode/self-oss-instruct-sc2-concepts
def get_min_max_values(data, col1, col2): """ extracts min and max value of two columns :param data: ptcf data frame :param col1: column 1 :param col1: column 2 :return: dict of min and max values of two columns """ return { 'ds1_min' : data[col1].min(), 'ds1_max' : data[col1].max(), 'ds2_min' : data[col2].min(), 'ds2_max' : data[col2].max() }
bigcode/self-oss-instruct-sc2-concepts
def create_dict_node_enode(set_proj_nodes, neighbors_dict, H, node, dict_node_enode, dict_enode_node): """ A function to create useful dictionaries to represent connections between nodes that are in the embedding and nodes that are not in the embedding. :param set_proj_nodes: Set of the nodes that are in the embedding :param neighbors_dict: Dictionary of all nodes and neighbors (both incoming and outgoing) :param H: H is the undirected version of our graph :param node: Current node :param dict_node_enode: explained below :param dict_enode_node: explained below :return: 1. dict_node_enode: key == nodes not in embedding, value == set of outdoing nodes in embedding (i.e there is a directed edge (i,j) when i is the key node and j is in the embedding) 2. dict_enode_node: key == nodes not in embedding, value == set of incoming nodes in embedding (i.e there is a directed edge (j,i) when i is the key node and j is in the embedding) """ set2 = neighbors_dict[node].intersection(set_proj_nodes) set_all = set(H[node]).intersection(set_proj_nodes) set_in = set_all - set2 if len(set2) > 0: dict_node_enode.update({node: set2}) if len(set_in) > 0: dict_enode_node.update({node: set_in}) return dict_node_enode, dict_enode_node
bigcode/self-oss-instruct-sc2-concepts
def upper(value): """Uppercase the string passed as argument""" return value.upper() if value else value
bigcode/self-oss-instruct-sc2-concepts
def pwr2modp(k, p): """Return 2**k mod p for any integer k""" if k < 0: assert p & 1 return pow((p + 1) >> 1, -k, p) return pow(2, k, p)
bigcode/self-oss-instruct-sc2-concepts
def QuadraticLimbDarkening(Impact, limb1, limb2): """Quadratic limb darkening. Kopal 1950, Harvard Col. Obs. Circ., 454, 1""" return 1 - limb1 * (1 - Impact) - limb2 * (1 - Impact) ** 2
bigcode/self-oss-instruct-sc2-concepts
import re def parse_bucket_url(url): """ Parse s3 url to get bucket name and object name. input: s3://test/templates/3.0/post_install.sh output: {"bucket_name": "test", "object_key": "templates/3.0/post_install.sh", "object_name": "post_install.sh"} """ match = re.match(r"s3://(.*?)/(.*)", url) if match: bucket_name = match.group(1) object_key = match.group(2) object_name = object_key.split("/")[-1] else: raise Exception("Invalid S3 url: {0}".format(url)) return {"bucket_name": bucket_name, "object_key": object_key, "object_name": object_name}
bigcode/self-oss-instruct-sc2-concepts
def scan_reverse(f, arr): """Scan over a list in reverse, using a function""" r=list(arr) for i in reversed(range(len(r))[1:]): r[i-1] = f(r[i-1],r[i]) return r
bigcode/self-oss-instruct-sc2-concepts
import itertools def juxtapose_text(text_a, text_b, buffer_len=15): """Places text_a to the left of text_b with a buffer of spaces in between""" lines_a = text_a.splitlines() lines_b = text_b.splitlines() longest_line_length_a = max(map(len, lines_a)) paired_lines = itertools.zip_longest(lines_a, lines_b, fillvalue="") a_columns = longest_line_length_a + buffer_len return "\n".join("{0:<{1}}{2}".format(a, a_columns, b) for a, b in paired_lines)
bigcode/self-oss-instruct-sc2-concepts
def color2gray(x): """Convert an RGB or RGBA (Red Green Blue Alpha) color tuple to a grayscale value.""" if len(x) == 3: r, g, b = x a = 1 elif len(x) == 4: r, g, b, a = x else: raise ValueError("Incorrect tuple length") return (r * 0.299 + 0.587*g + 0.114*b) * a
bigcode/self-oss-instruct-sc2-concepts
def pax_to_human_time(num): """Converts a pax time to a human-readable representation""" for x in ['ns', 'us', 'ms', 's', 'ks', 'Ms', 'G', 'T']: if num < 1000.0: return "%3.3f %s" % (num, x) num /= 1000.0 return "%3.1f %s" % (num, 's')
bigcode/self-oss-instruct-sc2-concepts
def check_answer(guess, a_followers, b_followers): """Take the user guess and follower counts and returns if they got it right.""" if a_followers > b_followers: return guess == "a" else: return guess == "b"
bigcode/self-oss-instruct-sc2-concepts
def to_yellow(string): """ Converts a string to yellow color (8bit) Returns: str: the string in yellow color """ return f"\u001b[33m{string}\u001b[0m"
bigcode/self-oss-instruct-sc2-concepts
def parse_json(request): """ Default content parser for JSON """ return request.json
bigcode/self-oss-instruct-sc2-concepts
def getUrl(sIpAddress): """Returns the full cgi URL of the target""" return 'http://' + sIpAddress + '/cgi-bin/xml-cgi'
bigcode/self-oss-instruct-sc2-concepts
def _initial_gaussian_params(xm, ym, z, width=5): """ Guesses the initial 2D Gaussian parameters given a spatial filter. Parameters ---------- xm : array_like The x-points for the filter. ym : array_like The y-points for the filter. z : array_like The actual data the parameters of which are guessed. width : float, optional The expected 1 s.d. width of the RF, in samples. (Default: 5) Returns ------- xc, yc : float Estimated center points for the data. a, b, c : float Upper-left, lower-right, and off-diagonal terms for the estimated precision matrix. """ # estimate means xi = z.sum(axis=0).argmax() yi = z.sum(axis=1).argmax() yc = xm[xi, yi] xc = ym[xi, yi] # compute precision matrix entries a = 1 / width b = 0 c = 1 / width return xc, yc, a, b, c
bigcode/self-oss-instruct-sc2-concepts
import re def requires(prefix=''): """Retrieve requirements from requirements.txt """ try: reqs = map(str.strip, open(prefix + 'requirements.txt').readlines()) return [req for req in reqs if not re.match(r'\W', req)] except Exception: pass return []
bigcode/self-oss-instruct-sc2-concepts