seed
stringlengths
1
14k
source
stringclasses
2 values
def map_to_lie_algebra(v): """Map a point in R^N to the tangent space at the identity, i.e. to the Lie Algebra Arg: v = vector in R^N, (..., 3) in our case Return: R = v converted to Lie Algebra element, (3,3) in our case""" # make sure this is a sample from R^3 assert v.size()[...
bigcode/self-oss-instruct-sc2-concepts
def quadratic_item_score(i): """Function is similar to inverted and linear functions but weights are decreasing at non-linear rate and accelerate with the item position. Parameters ---------- i : int Item position. Returns ------- result : float Inverted square ...
bigcode/self-oss-instruct-sc2-concepts
def shrink_to_fit(column_sizes, terminal_width): """ If the total size of all columns exceeds the terminal width, then we need to shrink the individual column sizes to fit. In most tables, there are one or two columns that are much longer than the other columns. We therefore tailor the shrinking algorit...
bigcode/self-oss-instruct-sc2-concepts
def swap(record): """ Swap (token, (ID, URL)) to ((ID, URL), token) Args: record: a pair, (token, (ID, URL)) Returns: pair: ((ID, URL), token) """ token = record[0] keys = record[1] return (keys,token)
bigcode/self-oss-instruct-sc2-concepts
def normalizeLanguage(lang): """ Normalizes a language-dialect string in to a standard form we can deal with. Converts any dash to underline, and makes sure that language is lowercase and dialect is upercase. """ lang=lang.replace('-','_') ld=lang.split('_') ld[0]=ld[0].lower() #Filter out meta languages suc...
bigcode/self-oss-instruct-sc2-concepts
def least_squares_gradient(y, tx, w): """ Compute the gradient of the mean square error with respect to w, and the current error vector e. Takes as input the targeted y, the sample matrix w and the feature vector w. This function is used when solving gradient based method, such that least_squares_GD() ...
bigcode/self-oss-instruct-sc2-concepts
def find_ngrams(seq, n): """ Computes the ngrams for a sequence. :type seq: a list of of strings :param seq: a sequence :return a list where ngrams are stored """ return zip(*[seq[i:] for i in range(n)])
bigcode/self-oss-instruct-sc2-concepts
import re def split_parts(sep, output): """Split the output string according to the regexp sep.""" regexp = re.compile(sep) lines = output.split('\n') idx = [] num = 0 for line in lines: if regexp.search(line): idx.append(num) num = num + 1 arr = [] start = ...
bigcode/self-oss-instruct-sc2-concepts
def _multi_bleu(hypothesis, reference_set, aligner): """ Compute a list of scores with the aligner. :param hypothesis: a single hypothesis. :param reference_set: a reference set. :param aligner: a callable to compute the semantic similarity of a hypothesis and a list of references. :return:...
bigcode/self-oss-instruct-sc2-concepts
def is_number(s): """ Check if a string is a number """ try: float(s) return True except ValueError: return False
bigcode/self-oss-instruct-sc2-concepts
def execute(instructions): """ Execute instructions, return a tuple of accumulator and exit reason. """ index = 0 accumulator = 0 list_of_pc = set() while True: if index in list_of_pc: return (accumulator, "cycle") if index == len(instructions): return...
bigcode/self-oss-instruct-sc2-concepts
import torch def subsequent_chunk_mask( size: int, chunk_size: int, num_left_chunks: int = -1, device: torch.device = torch.device("cpu"), ) -> torch.Tensor: """Create mask for subsequent steps (size, size) with chunk size, this is for streaming encoder Args: siz...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def check_label_match(frame_labels: Dict, labelset: Dict) -> bool: """ Check that the labels of the frame matches the labels of the rules. :frame_labels (Dict) The labels of the frame. :labelset (Dict) The labels of the ruleset. Return a boolean describing the status of t...
bigcode/self-oss-instruct-sc2-concepts
def _handle_ai_platform_response(uri, response): """Handle response to AI platform from both get/post calls. Args: uri: Request uri. response: Response from the request. Returns: Request results in json format. Raises: ValueError: When the request fails, the ValueError will be raised with ...
bigcode/self-oss-instruct-sc2-concepts
def filter_abst(abst, slots_to_abstract): """Filter abstraction instruction to only contain slots that are actually to be abstracted.""" return [a for a in abst if a.slot in slots_to_abstract]
bigcode/self-oss-instruct-sc2-concepts
def lower_case_underscore_to_camel_case(text): """ Converts string or unicdoe from lower case underscore to camel case :param text: str, string to convert :return: str """ # NOTE: We use string's class to work on the string to keep its type split_string = text.split('_') class_ = text._...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def fqualname_of(obj: Any) -> str: """Gets the fully-qualified name for the given object.""" return "{}.{}".format(obj.__class__.__module__, obj.__class__.__qualname__)
bigcode/self-oss-instruct-sc2-concepts
import re def shell_escape_filename(filename): """ Escape filename for use as shell argument. """ return re.sub(r'(\s|[\\\'"|()<>{}$&#?*`!;])', r'\\\1', filename)
bigcode/self-oss-instruct-sc2-concepts
import torch def to_device(obj, device): """ Move a tensor, tuple, list, or dict onto device. """ if torch.is_tensor(obj): return obj.to(device) if isinstance(obj, tuple): return tuple(to_device(t, device) for t in obj) if isinstance(obj, list): return [to_device(t, dev...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def are_supports_coordinated(orders: List[str]) -> bool: """Return False if any supports or convoys are not properly coordinated e.g. if "F BLA S A SEV - RUM", return False if "A SEV" is not ordered "A SEV - RUM" 0 1 2 3 4 5 6 """ required = {} ordered = ...
bigcode/self-oss-instruct-sc2-concepts
def _e_f(rho, rhou, e, p): """Computes the flux of the energy equation.""" return (e + p) * rhou / rho
bigcode/self-oss-instruct-sc2-concepts
def _extract_doc_comment_simple(content, line, column, markers): """ Extract a documentation that starts at given beginning with simple layout. The property of the simple layout is that there's no each-line marker. This applies e.g. for python docstrings. :param content: Presplitted lines of the s...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def DatetimeFromString(date): """Parses a datetime from a serialized string.""" if date == 'None': return None if not date or isinstance(date, datetime): return date # Strip bad characters. date = date.strip('\t\n ') valid_formats = [ '%Y-%m-%d %H:%M:%S.%f %Z',...
bigcode/self-oss-instruct-sc2-concepts
def anyone_certified(task, **kwargs): """ Default assignment policy, we leave the task in the awaiting processing pool. """ return task
bigcode/self-oss-instruct-sc2-concepts
def rfnnodes(rf): """Return the total number of decision and leaf nodes in all trees of the forest.""" return sum(t.tree_.node_count for t in rf.estimators_)
bigcode/self-oss-instruct-sc2-concepts
def sum_of_squares(limit): """ Returns the sum of all squares in the range 1 up to and including limit. """ return sum([i ** 2 for i in range(limit+1)])
bigcode/self-oss-instruct-sc2-concepts
def fact(n): """ factorial of n :param n: int :return: int """ if type(n) != int: n = int(n) if n == 1: return 1 else: acc = 1 for x in range(1,n+1): acc = acc * x return int(acc)
bigcode/self-oss-instruct-sc2-concepts
def exponential_decay(lr0, s): """ Create exponential decay: reduce learning rate by s every specified iteration. Parameters ---------- lr0 : float initial learning rate s: float decay rate, e.g. 0.9 (mostly higher than in other methods) Returns ------- exponential_...
bigcode/self-oss-instruct-sc2-concepts
def is_kwarg(argument: str) -> bool: """`True` if argument name is `**kwargs`""" return "**" in argument
bigcode/self-oss-instruct-sc2-concepts
def isabs(s): """Test whether a path is absolute""" return s.startswith('/')
bigcode/self-oss-instruct-sc2-concepts
def list_extremum(data: list, type=0) -> tuple: """ 找到list中的极值,并返回索引,若极值有多个,则返回多个索引 Args: data: list数据 type: 1表示执行最大值操作,0表示最小值操作 Returns: 极值,索引的列表 """ if type == 1: # 极大值 ex = max(data) elif type == 0: # 极小值 ex = min(data) else: ...
bigcode/self-oss-instruct-sc2-concepts
def filter_data(df, condition): """ Filter data by keeping only the values that satisfy the conditions given Parameters - df: (pandas dataframe) dataframe - conditions: (string) string that contains conditions to be used to filter dataframe. Ex: if the user...
bigcode/self-oss-instruct-sc2-concepts
def _render(env, template_str, data): """Uses the environment to render the provided template string using the provided data""" template = env.from_string(template_str) return template.render(data)
bigcode/self-oss-instruct-sc2-concepts
def ExtractDependencies(input): """ Create a list of dependencies from input list of lines Each element contains the name of the object and a list of files that it depends on. Dependencies that contain "/usr/" are removed as they are system headers. """ deps = [] for line in input: headersLine = line.startswit...
bigcode/self-oss-instruct-sc2-concepts
def format_sbatch_options(**sbatch_options): """Format sbatch options""" options = [] for k, v in sbatch_options.items(): val = "" if v is not None: val = f"={v}" options.append(f"--{k}{val}") return options
bigcode/self-oss-instruct-sc2-concepts
def bytes2NativeString(x, encoding='utf-8'): """ Convert C{bytes} to a native C{str}. On Python 3 and higher, str and bytes are not equivalent. In this case, decode the bytes, and return a native string. On Python 2 and lower, str and bytes are equivalent. In this case, just just ret...
bigcode/self-oss-instruct-sc2-concepts
import requests def exec_request(url, timeout): """Executes request given in url and returns a dictionary with content""" data = requests.get(url, timeout=timeout) data.raise_for_status() # Raise in case of failed status return data.json()
bigcode/self-oss-instruct-sc2-concepts
def Compare(token1, token2): """Compares two tokens and determines their relative order. Args: token1: The first token to compare. token2: The second token to compare. Returns: A negative integer, zero, or a positive integer as the first token is before, equal, or after the second ...
bigcode/self-oss-instruct-sc2-concepts
def _get_inner_type(typestr): """ Given a str like 'org.apache...ReversedType(LongType)', return just 'LongType' """ first_paren = typestr.find('(') return typestr[first_paren + 1:-1]
bigcode/self-oss-instruct-sc2-concepts
def set_fba_name(source, year): """ Generate name of FBA used when saving parquet :param source: str, source :param year: str, year :return: str, name of parquet """ return source if year is None else f'{source}_{year}'
bigcode/self-oss-instruct-sc2-concepts
def aramaic_turoyo_input_normal(field, text): """ Prepare a string from one of the query fields for subsequent processing: replace common shortcuts with valid characters of Turoyo (Neo-Aramaic). """ if field not in ('wf', 'lex', 'root'): return text text = text.replace('\'', 'ʕ') ...
bigcode/self-oss-instruct-sc2-concepts
def Dictionary_to_XmlTupleString(python_dictionary): """transforms a python dictionary into a xml line in the form <Tuple key1="value1" key2="value2"..keyN="valueN" />""" prefix="<Tuple " postfix=" />" inner="" xml_out="" for key,value in python_dictionary.items(): inner=inner+'{0}="...
bigcode/self-oss-instruct-sc2-concepts
def remove_fields_duplicated(bids_fields): """Remove duplicated fields in a list. Args: bids_fields: List of fields Returns: list """ seen = set() seen_add = seen.add return [x for x in bids_fields if not (x in seen or seen_add(x))]
bigcode/self-oss-instruct-sc2-concepts
def get_image_modality(image_modality): """Change image_modality (string) to rgb (bool), flow (bool) and audio (bool) for efficiency""" if image_modality.lower() == "all": rgb = flow = audio = True elif image_modality.lower() == "joint": rgb = flow = True audio = False elif imag...
bigcode/self-oss-instruct-sc2-concepts
def get_scan_resource_label(system_type: str) -> str: """ Given a system type, returns the label to use in scan output """ resource_label_map = { "redshift_cluster": "Redshift Cluster", "rds_instance": "RDS Instance", "rds_cluster": "RDS Cluster", } resource_label = resou...
bigcode/self-oss-instruct-sc2-concepts
def replaceValue(mapping, old, new, strategy=None): """ Replace old values with new ones following dict strategy. The parameter strategy is None per default for inplace operation. A copy operation is injected via strateg values like copy.copy or copy.deepcopy Note: A dict is returned regardles...
bigcode/self-oss-instruct-sc2-concepts
def isIn( obj, container ): """ Returns a boolean whether or not 'obj' is present in 'container'. """ return obj in container
bigcode/self-oss-instruct-sc2-concepts
import hashlib def wep_make_gravatar_img(email: str) -> str: """ Returns a string pointing to a Gravatar image based on an email address. Args: email: the email associated with a given Gravatar image Returns: a link of the form <https://www.gravatar.com/avatar/:hash>, where `...
bigcode/self-oss-instruct-sc2-concepts
def total_travel_distance(journey): """ Return the total travel distance of your PyCon journey in kilometers rounded to one decimal. """ return round(sum(trip.distance for trip in journey),1) pass
bigcode/self-oss-instruct-sc2-concepts
def selection_sort(L): """ Implementation of a selection sort algorithm Complexity: O(n^2) :param L: List-object """ index = 0 while index != len(L): for i in range(index, len(L)): if L[i] < L[index]: L[index], L[i] = L[i], L[index] index += 1 ...
bigcode/self-oss-instruct-sc2-concepts
def _get_opt_provider(target, provider): """Returns the given provider on target, if present.""" return target[provider] if provider in target else None
bigcode/self-oss-instruct-sc2-concepts
def luminance_newhall1943(V, **kwargs): """ Returns the *luminance* :math:`R_Y` of given *Munsell* value :math:`V` using *Sidney M. Newhall, Dorothy Nickerson, and Deane B. Judd (1943)* method. Parameters ---------- V : numeric *Munsell* value :math:`V`. \*\*kwargs : \*\*, optio...
bigcode/self-oss-instruct-sc2-concepts
import collections import json def load_queries(path: str): """ Loads queries into a dictionary of query_id -> (query, question) """ queries = collections.OrderedDict() with open(path) as f: raw_json = f.read() parsed_json = json.loads(raw_json) for topic in parsed_json: ...
bigcode/self-oss-instruct-sc2-concepts
def mel_sampling( audio, frame_duration_ms = 1200, overlap_ms = 200, sample_rate = 16000 ): """ Generates audio frames from audio. This is for melspectrogram generative model. Takes the desired frame duration in milliseconds, the audio, and the sample rate. Parameters ---------- audio: np.a...
bigcode/self-oss-instruct-sc2-concepts
def examine_neighbors(g, x, y): """ Examine the 8 neighbors of the cell at coordinates "x" by "y", and return the number of neighbor cells which are closed. """ c = 0 w, h = g.size() if x - 1 >= 0: if g.get(x - 1, y): c += 1 if x + 1 < w: if g.get(x + 1, y):...
bigcode/self-oss-instruct-sc2-concepts
def determine_nonschema_privileges_for_schema(role, objkind, schema, dbcontext): """ Determine all non-schema privileges granted to a given role for all objects of objkind in the specified schema. Results will be returned as two sets: objects granted write access and objects granted read access. We...
bigcode/self-oss-instruct-sc2-concepts
def number_freq_plots(runs, map_label): """Calculate the number of plots needed for allfreq plots and frequency histogram plots """ num_cpu_plots = len(map_label) has_devfreq_data = False for run in runs: if len(run.devfreq_in_power.data_frame) > 0: has_devfreq_data = True ...
bigcode/self-oss-instruct-sc2-concepts
def get_region(context): """ Return the AWS account region for the executing lambda function. Args: context: AWS lambda Context Object http://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html Returns: str : AWS Account Region """ return str(context.invoked_functi...
bigcode/self-oss-instruct-sc2-concepts
def find_min_pos(input_list): """Function to find index with minimum value.""" length = len(input_list) if length == 0: return -1 curr_min = input_list[0] curr_min_index = 0 for j in range(1, length): if curr_min > input_list[j]: curr_min = input_list[j] curr_min_index = j return cu...
bigcode/self-oss-instruct-sc2-concepts
import requests import time def get_limited(url, params = None, auth = None): """ Get a GitHub API response, keeping in mind that we may be rate-limited by the abuse system """ number_of_retries = 0 resp = requests.get(url, params = params, auth=auth) while resp.status_code == 403 and number_o...
bigcode/self-oss-instruct-sc2-concepts
import collections def index_rules_by_namespace(rules): """ compute the rules that fit into each namespace found within the given rules. for example, given: - c2/shell :: create reverse shell - c2/file-transfer :: download and write a file return the index: c2/shell: [create reve...
bigcode/self-oss-instruct-sc2-concepts
def which_argument(arguments, options): """Return which of the given constant options was specified in the given argument source parsed by docopt.""" for check in options: if arguments[check]: return check
bigcode/self-oss-instruct-sc2-concepts
def each_n(iterable, n): """Iterate iterable with n-tuples.""" a = iter(iterable) return zip(*[a] * n)
bigcode/self-oss-instruct-sc2-concepts
import copy def _format_label(label_txt, values, date, date_format=None): """ Replaces '{date}' and other placeholders in label_txt by formatting with date string and values given by -v key=value """ values = copy.deepcopy(values) if 'date' not in values: values['date'] = date.strftim...
bigcode/self-oss-instruct-sc2-concepts
def construct_constraint(year, index): """ This function is a convenience function that returns a valid demand constraint for one year. The wrapper function construct_constraint is needed because we need a reference to year in the wrapped meet_demand function in model.buy[year, supplier, block] and mode...
bigcode/self-oss-instruct-sc2-concepts
def parse(file_name): """Parse the data file into a list of int""" with open(file_name, "r") as f: return [int(x) for x in f.readline().split(",")]
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def PathFromLabel(label: str) -> Optional[str]: """Create a workspace relative path from a bazel label. Args: A bazel label, e.g. "//foo:bar.cc". Returns: A workspace-relative path, e.g. "foo/bar.cc". If the label does not resolve to a path, returns None. """ # First, ...
bigcode/self-oss-instruct-sc2-concepts
import typing import hashlib def get_hashed_percentage_for_object_ids( object_ids: typing.Iterable[int], iterations: int = 1 ) -> float: """ Given a list of object ids, get a floating point number between 0 and 1 based on the hash of those ids. This should give the same value every time for any li...
bigcode/self-oss-instruct-sc2-concepts
def check_poly_types(df): """ Special checks to ensure the Poly_Types field adheres to what we want apart from domain/schema checks. Args: df: Pandas dataframe of feature class table containing the field 'Poly_Type' Returns: errors: list of error message strings to print to the c...
bigcode/self-oss-instruct-sc2-concepts
def _field_index(header, field_names, index): """Determine a field index. If the index passed is already a valid index, that index is returned. Otherwise, the header is searched for a field name matching any of the passed field names, and the index of the first one found is returned. If no mat...
bigcode/self-oss-instruct-sc2-concepts
import torch def _sigmoid_then_2d(x): """Transform 1-dim logits to valid y_proba Sigmoid is applied to x to transform it to probabilities. Then concatenate the probabilities with 1 - these probabilities to return a correctly formed ``y_proba``. This is required for sklearn, which expects probabil...
bigcode/self-oss-instruct-sc2-concepts
import re def parse_combined_float_list(float_string_list): """Parses a list of strings, where each element of the list is a single string which is a list of floats to be parsed. Assumes the data delimiter is whitespace or comma, and removes any white space at the beginning and end of the string a...
bigcode/self-oss-instruct-sc2-concepts
def create_value_dict(data_agg, super_star_avg_prices_2_agents, super_star_avg_prices_3_agents ): """ A function to create a comprehensive dictionary with all values that we need to create the plot. Args: data_agg (DataFrame): Da...
bigcode/self-oss-instruct-sc2-concepts
def get_referenced_filenames(license_matches): """ Return a list of unique referenced filenames found in the rules of a list of ``license_matches`` """ unique_filenames = [] for license_match in license_matches: for filename in license_match['matched_rule']['referenced_filenames']: ...
bigcode/self-oss-instruct-sc2-concepts
def section_break(qty: int=2) -> str: """Return multiple line break characters. :param int qty: number of line break characters (default: 2) :returns: multiple new line characters :rtype: str """ return '\n' * int(qty)
bigcode/self-oss-instruct-sc2-concepts
import hashlib def get_hash(text): """Return a hash of the given text for use as an id. Currently SHA1 hashing is used. It should be plenty for our purposes. """ return hashlib.sha1(text.encode('utf-8')).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def _select_class_label(top_k_rows, label_index): """ Gets the class label based on majority voting :param top_k_rows: a list in the form of [(dist, row),...] :param label_index: the index in the rows where the label is located :return: the most common label """ labels = [] for tuple in top...
bigcode/self-oss-instruct-sc2-concepts
def rotate3_inertia(RotMat,relInertia): """ Rotates an inertia tensor. A derivation of the formula in this function can be found in Crandall 1968, Dynamics of mechanical and electromechanical systems. This function only transforms an inertia tensor for rotations with respect to a fixed point. To tra...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import Tuple from typing import List def increase_version_number(version_buffer: Union[Tuple[int, int, int], List[int]]) -> List[int]: """ Increases the number of the version with an increment of 0.0.1. Args: version_buffer: (Union[Tuple[int, int, int], List[i...
bigcode/self-oss-instruct-sc2-concepts
import math def get_num_elements(n): """Return the number of elements from the number of possible pairwise combinations. Essentially, the reverse of the previous function. We only consider the solution for [-b + sqrt(b^2 - 4ac)] for practical reasons. """ return int(1 + math.sqrt(1 + (8 * n))) //...
bigcode/self-oss-instruct-sc2-concepts
def two_list_dictionary(keys, values): """Given keys and values, make dictionary of those. >>> two_list_dictionary(['x', 'y', 'z'], [9, 8, 7]) {'x': 9, 'y': 8, 'z': 7} If there are fewer values than keys, remaining keys should have value of None: >>> two_list_dicti...
bigcode/self-oss-instruct-sc2-concepts
def walk_to_s(tree, pos): """ Takes the tree being searched and the position from which the walk up is started. Returns the position of the first S encountered and the path taken to get there from the dominating NP. The path consists of a list of tree positions. Args: tree: the tree bein...
bigcode/self-oss-instruct-sc2-concepts
def digits(m) -> int: """Parses a phrase representing a digit sequence, returning it as an integer.""" return int(m.digit_string)
bigcode/self-oss-instruct-sc2-concepts
def fedoralink_classes(obj): """ Get the original fedoralink classes of of a given object. They might be different to real classes (via getmro) because fedoralink autogenerates types when deserializing from RDF metadata/Indexer data. :param obj: an instance of FedoraObject :return: list of class...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def yearmonth(value): """ Returns the input converted to a string in format YYYY-mm Args: value (datetime): date to convert Returns: output (str): formatted in YYYY-mm """ output = datetime.strftime(value, '%Y-%m') return output
bigcode/self-oss-instruct-sc2-concepts
import requests def url_check(url): #Description """Boolean return - check to see if the site exists. This function takes a url as input and then it requests the site head - not the full html and then it checks the response to see if it's less than 400. If it is less tha...
bigcode/self-oss-instruct-sc2-concepts
def rule_separation(value: float, layer1: str, layer2: str): """Min space between different layers""" error = f"min {layer1} {layer2} separation {value}um" return f"{layer1}.separation({layer2}, {value})" f".output('{error}', '{error}')"
bigcode/self-oss-instruct-sc2-concepts
from textwrap import dedent def txt(s: str) -> str: """ dedents a triple-quoted indented string, and strips the leading newline. Converts this: txt(''' hello world ''') into this: "hello\nworld\n" """ return dedent(s.lstrip("\n"))
bigcode/self-oss-instruct-sc2-concepts
import re def _clean_xml(xml_string): """Replace invalid characters with "?". :type xml_string: str :arg xml_string: XML string :rtype: str :returns: valid XML string """ invalid_chars = re.compile(r'[\000-\010\013\014\016-\037]') return invalid_chars.sub('?', xml_string)
bigcode/self-oss-instruct-sc2-concepts
import functools import warnings def remove_parameters(removed_params, reason, end_version='future'): """Decorator to deprecate but not renamed parameters in the decorated functions and methods. Parameters ---------- removed_params : list[string] ...
bigcode/self-oss-instruct-sc2-concepts
def degseq_to_data(degree_sequence): """ Takes a degree sequence list (of Integers) and converts to a sorted (max-min) integer data type, as used for faster access in the underlying database. EXAMPLE:: sage: from sage.graphs.graph_database import degseq_to_data sage: degseq_to_data...
bigcode/self-oss-instruct-sc2-concepts
def pivot_smooth_norm(df, smooth_value, rows_variable, cols_variable, values_variable): """ Turns the pandas dataframe into a data matrix. Args: df (dataframe): aggregated dataframe smooth_value (float): value to add to the matrix to account for the priors rows_variable (str): name o...
bigcode/self-oss-instruct-sc2-concepts
def detect(code): """Detects if a scriptlet is urlencoded.""" # the fact that script doesn't contain any space, but has %20 instead # should be sufficient check for now. return ' ' not in code and ('%20' in code or code.count('%') > 3)
bigcode/self-oss-instruct-sc2-concepts
def parse_voice_flags(flags): """Parses flags and returns a dict that represents voice playing state.""" # flags: [0-9]{8} if flags[0] == '0': return {'voice': 'stop'} else: return {'voice': { 'number': int(flags[1:3]), 'repeat': int(flags[4:6]) }}
bigcode/self-oss-instruct-sc2-concepts
import warnings def deprecated(replaced_by_func): """ This decorator is used to mark functions as deprecated. It also points the user to the newer function that should be used instead. """ def wrap(f): def new_func(*args, **kwargs): warnings.simplefilter('always', DeprecationWa...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def enterprise_1_11_artifact() -> Path: """ Return the path to a build artifact for DC/OS Enterprise 1.11. """ return Path('/tmp/dcos_generate_config_1_11.ee.sh')
bigcode/self-oss-instruct-sc2-concepts
def nocache(response): """Add Cache-Control headers to disable caching a response""" response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0' return response
bigcode/self-oss-instruct-sc2-concepts
from typing import List def parse_pdv(text: str) -> List[List[str]]: """ Parse pipe delimited values. """ rows = [] lines = text.split('\n') for line in lines: row = [] cols = line.split('|') for col in cols: col2 = col.strip() row.append(col2)...
bigcode/self-oss-instruct-sc2-concepts
def wall_dimensions(walls): """ Given a list of walls, returns a tuple of (width, height).""" width = max(walls)[0] + 1 height = max(walls)[1] + 1 return (width, height)
bigcode/self-oss-instruct-sc2-concepts
import math def millify(n): """Abbreviate a number to nearest thousand, million, etc. Adapted from: https://stackoverflow.com/a/3155023/10696164 Parameters ---------- n : int The number to abbreviate Returns ------- millified : str The number abbreviated to the neare...
bigcode/self-oss-instruct-sc2-concepts