seed
stringlengths
1
14k
source
stringclasses
2 values
import torch def relative_to_abs(rel_traj, start_pos): """ Convert relative coordinates in 'natural' coordinates Inputs: - rel_traj: pytorch tensor of shape (seq_len, batch, 2) - start_pos: pytorch tensor of shape (batch, 2) Outputs: - abs_traj: pytorch tensor of shape (seq_len, batch, 2)...
bigcode/self-oss-instruct-sc2-concepts
def pal_draw_condition_1(x_start, x_stop, y_start, y_stop): """ First draw condition of polygonal audience lines. Stop values are bigger or equal to the start values Parameters ---------- x_start : float Start point on x-axis. x_stop : float Stop point on x-axis. y_start...
bigcode/self-oss-instruct-sc2-concepts
def parse_coco_categories(categories): """Parses the COCO categories list. The returned ``classes`` contains all class IDs from ``[0, max_id]``, inclusive. Args: categories: a dict of the form:: [ ... { "id": 2, ...
bigcode/self-oss-instruct-sc2-concepts
def reverse_words(s): """ Reverses order or words in string s. """ words = s.split() words_reversed = words[::-1] return ' '.join(words_reversed)
bigcode/self-oss-instruct-sc2-concepts
import requests def get_openlibrary_data(olid: str = "isbn/0140328726") -> dict: """ Given an 'isbn/0140328726', return book data from Open Library as a Python dict. Given an '/authors/OL34184A', return authors data as a Python dict. This code must work for olids with or without a leading slash ('/')....
bigcode/self-oss-instruct-sc2-concepts
def findInfectInFamily(tx, query, id): """ Method that executes the query to find the infected member of a family :param tx: is the transaction :param query: is the query to execute :param id: is the id of the positive Person """ result = tx.run(query, id=id).data() return result
bigcode/self-oss-instruct-sc2-concepts
def compute_max_firing_rate(spiketrains, runtime): """ Compute maximum firing rate :param spiketrains: spike trains of neurins :param runtime: simulation runtime :return: float """ rates = list() for spiketrain in spiketrains: rates.append(len(spiketrain) * (1000 / runtime)) ...
bigcode/self-oss-instruct-sc2-concepts
def refresh_time_stats(bot): """ Returns formatted stats on the last refresh. """ stats = bot.memory['ratbot']['stats'].get('starsystem_refresh') if not stats: return "No starsystem refresh stats are available." return ( "Refresh took {total:.2f} seconds. (Load: {load:.2f}, Prun...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def split_changes_into_list(changes: str) -> List[str]: """ Given a string of chord alterations (e.g., suspensions or added tones), split them into a list of individual alterations. Parameters ---------- changes : str A string representing a chord alterations, ...
bigcode/self-oss-instruct-sc2-concepts
def autoNorm1(dataSet): """ 归一化特征值,消除属性之间量级不同导致的影响 归一化公式: Y = (X-Xmin)/(Xmax-Xmin) 其中的 min 和 max 分别是数据集中的最小特征值和最大特征值。该函数可以自动将数字特征值转化为0到1的区间。 """ # 计算每种属性的最大值、最小值、极差 minVals = dataSet.min(0) maxVals = dataSet.max(0) ranges = maxVals - minVals normDataSet = (dataSet - m...
bigcode/self-oss-instruct-sc2-concepts
import operator from typing import OrderedDict def build_node_id_mapping(nodes): """ Build the mapping from tree node to array index >>> nodes = [('funny', None, None, 3), (',', None, None, 2), ('.', None, None, 2), ('engaging', None, None, 4), ('film', None, None, 2), ('warm', None, None, 3), ('A', ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict import pkg_resources def get_versions() -> Dict[str, str]: """Returns version info for all Open Mafia (sub-)packages.""" prefix = "open-mafia" z = sorted( [ (p.key, p.version) for p in pkg_resources.working_set if p.key.startswith(prefix...
bigcode/self-oss-instruct-sc2-concepts
import re def pull_stats(summary: list) -> dict: """ Convert stats to a dictionary. Each line in the summary table in the log file needs to be parsed by first converting the table to a comma-separated list for easy parsing, then taking the first column as the statistical category and placing the ...
bigcode/self-oss-instruct-sc2-concepts
def merge_dicts(*args): """Merge multiple dictionaries in a new one treating None as an empty dictionary. merge_dicts(dict1, [dict2 [...]]) -> dict1.update(dict2);dict1.update ... Parameters ---------- *args : dict-like Returns ------- dict Example ------- >>> d1 = d...
bigcode/self-oss-instruct-sc2-concepts
import re def should_ignore_line(line): """ Determine whether or not a line should be ignored for now. """ patterns_to_ingore = [ re.compile('#!/usr/bin/env python'), re.compile('from __future__ import .+'), re.compile('^#[\s\S]*'), re.compile('^\s+$') ] return ...
bigcode/self-oss-instruct-sc2-concepts
def decode_ports(ports, filter_proto): """Given a string like '901-902/tcp,30/udp', return a list of ports.""" if not ports: return [] results = [] for protoport in ports.split(','): port, proto = protoport.split('/') if proto != filter_proto: continue # Expa...
bigcode/self-oss-instruct-sc2-concepts
import json def read_json_filter(path): """Reads a json filter from a file. For example: [">", 3.14, ["field", "000002"]] """ with open(path) as json_data: return json.load(json_data)
bigcode/self-oss-instruct-sc2-concepts
def get_reverse_list(ori_shape, transforms): """ get reverse list of transform. Args: ori_shape (list): Origin shape of image. transforms (list): List of transform. Returns: list: List of tuple, there are two format: ('resize', (h, w)) The image shape before resize,...
bigcode/self-oss-instruct-sc2-concepts
def ask(prompt: str='', default: str='') -> str: """Print the ``prompt``, get user's answer, return it -- or a default.""" if prompt: if default: prompt = prompt + ' [' + default + ']' prompt = prompt + ' ' answer = None while not answer: answer = input(prompt) ...
bigcode/self-oss-instruct-sc2-concepts
import re def parse_ldd_output(output): """Parses the output from a run of 'ldd' on a binary. Returns a dictionary of {path: address} for each library required by the specified binary. Arguments: output(bytes, str): The output to parse Example: >>> sorted(parse_ldd_output(''' ...
bigcode/self-oss-instruct-sc2-concepts
def _is_line_important(line_content, frames): """Check if the line contains a frame; it means the line is important.""" for frame in frames: if frame in line_content: return True return False
bigcode/self-oss-instruct-sc2-concepts
def string_to_list(a): """Transform a string with coma separated values to a list of values.""" return a if isinstance(a, list) or a is None else a.split(",")
bigcode/self-oss-instruct-sc2-concepts
def _sort_resources(resources): """ Sorts a stack's resources by LogicalResourceId Parameters ---------- resources : list Resources to sort Returns ------- list List of resources, sorted """ if resources is None: return [] return sorted(resources, ke...
bigcode/self-oss-instruct-sc2-concepts
def fix_checkbox(params): """ Replace param_checkbox with param-indexed. """ pol_params = {} # drop checkbox parameters. for param, data in params.items(): if param.endswith("checkbox"): base_param = param.split("_checkbox")[0] pol_params[f"{base_param}-indexed"] ...
bigcode/self-oss-instruct-sc2-concepts
def mode(var, k=1): """ Returns the `k`th most probable value of the random variable `var`. """ pairs = sorted(var._dist.keys(), key=lambda val: var[val], reverse=True) return pairs[k - 1]
bigcode/self-oss-instruct-sc2-concepts
def change_extension(filename, new_ext): """ Change file extension """ fn = '.'.join(filename.split('.')[:-1] + [new_ext]) return fn
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def generate_userlist(users: Dict[str, str]) -> str: """Generate valid userlist.txt from the given dictionary of usernames:passwords. Args: users: a dictionary of usernames and passwords Returns: A multiline string, containing each pair of usernames and passwords i...
bigcode/self-oss-instruct-sc2-concepts
def make_id_response(id): """ Usually used for requests that create single resources. :param id: ID of of the created resource. :return: Single ID response. """ return {'id': id}
bigcode/self-oss-instruct-sc2-concepts
def PySequence_GetSlice(space, w_obj, start, end): """Return the slice of sequence object o between i1 and i2, or NULL on failure. This is the equivalent of the Python expression o[i1:i2].""" return space.getslice(w_obj, space.newint(start), space.newint(end))
bigcode/self-oss-instruct-sc2-concepts
def specify_grid(grid): """Specify the grid to search on (`F` for use of xorca_brokenline). Parameters ---------- grid : str Name of the grid (T, U, V, F). Returns ------- S : str Name of the dummy variable living on the specified grid. """ # make sure the letter d...
bigcode/self-oss-instruct-sc2-concepts
def _instance_tags(hostname, role, tags=None): """Return instance tags (common tags + instance name and role). """ if tags is None: tags = [] return [{ 'ResourceType': 'instance', 'Tags': tags + [ {'Key': 'Name', 'Value': hostname.lower()}, {'Key': 'Role'...
bigcode/self-oss-instruct-sc2-concepts
import torch def mbcuda(t: torch.Tensor) -> torch.Tensor: """Short for "maybe cuda" this moves a tensor (or model) to cuda if available """ if torch.cuda.is_available(): return t.cuda() else: return t
bigcode/self-oss-instruct-sc2-concepts
def get_subgraph(G, nodes): """ NetworkX subgraph method wrapper """ return G.subgraph(nodes)
bigcode/self-oss-instruct-sc2-concepts
import types def is_generator(val): """ Checks whether a variable is a generator. Parameters ---------- val The variable to check. Returns ------- bool True is the variable is a generator. Otherwise False. """ return isinstance(val, types.GeneratorType)
bigcode/self-oss-instruct-sc2-concepts
def vecDistanceSquared(inPtA, inPtB): """calculate the square of the distance between two points""" ddx = inPtA[0] - inPtB[0] ddy = inPtA[1] - inPtB[1] ddz = inPtA[2] - inPtB[2] return ddx*ddx + ddy*ddy + ddz*ddz
bigcode/self-oss-instruct-sc2-concepts
def count_daily_prefixes(pfx_raw_data): """ Count how many prefixes have been announced by each AS in input. Note: input should contain data for only one day. :param pfx_raw_data: generator that yields dictionaries containing BGP announces for one day (from jarvis) ...
bigcode/self-oss-instruct-sc2-concepts
def flatten_errors(errors, path=''): """Flatten Cerberus errors into the JSONAPI structure.""" flat_errors = [] for key, values in errors.items(): for value in values: if isinstance(value, dict): flat_errors.extend(flatten_errors(value, path='{0}/{1}'.format(path, key))) ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any import inspect def safe_is_sub(sub: Any, parent: Any) -> bool: """Is this a subclass of parent.""" is_class = inspect.isclass(sub) return is_class and issubclass(sub, parent)
bigcode/self-oss-instruct-sc2-concepts
import torch def encode_boxes_to_anchors(boxes, anchors, eps=1e-8): """ Create anchors regression target based on anchors Args: boxes: ground truth boxes. anchors: anchor boxes on all feature levels. eps: small number for stability Returns: outputs: anchors w.r.t. ground tr...
bigcode/self-oss-instruct-sc2-concepts
def get_headers_dict(base_headers: list[str]): """Set headers for the request""" headers_dict = {} for line in base_headers: parts = line.split(':') headers_dict[parts[0]] = parts[1].strip() return headers_dict
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def unisoformat(s): """Turn result of .isoformat() back into datetime.""" return datetime.strptime(s, '%Y-%m-%dT%H:%M:%S')
bigcode/self-oss-instruct-sc2-concepts
def binary_search(a, x, left=0, right=-1): """ Returns the index of x if it exists in a. Otherwise returns the index of either its left or right neighbor. right is inclusive. """ n = len(a) if right < 0: right += n while left < right: mid = left + (right - left) // 2 ...
bigcode/self-oss-instruct-sc2-concepts
def shoulder_to_dict(s): """Return a dict of the user defined values/attributes in a Shoulder model""" return { 'active': s.active, 'crossrefEnabled': s.crossrefEnabled, 'datacenter': s.datacenter, 'date': s.date, 'isArk': s.isArk, 'isCrossref': s.isCrossref, ...
bigcode/self-oss-instruct-sc2-concepts
import collections def _name_regions(regions, vertex_slice): """Convert a list of regions into the correct form for a method expecting two dictionaries describing the regions. """ regions = collections.OrderedDict({ i: r for i, r in enumerate(regions, start=1) if r is not None }) regio...
bigcode/self-oss-instruct-sc2-concepts
import inspect def get_caller_file_name(skip_frames=1): """ Get the file name of the original caller of the calling function. :param skip_frames: The number of frames to skip to get the caller. If you want your filename, set to 0, if you want your caller's leave to default or set to 1, and any nu...
bigcode/self-oss-instruct-sc2-concepts
import re def is_aws_ecr(registry): """Checks whether registry is an AWS ECR registry.""" return re.match(r"[0-9]+\.dkr\.ecr\.[^.]+\.amazonaws\.com", registry) is not None
bigcode/self-oss-instruct-sc2-concepts
import re def parse_unit(line, unit_type): """Parse line to unit representation with unit_type.""" regex = r'''(\d+) # number of units [\w\s]+? (\d+) # hit points [\w\s]+? (\([\w;,\s]+\))? # immunity and weaknesses ...
bigcode/self-oss-instruct-sc2-concepts
def equiangular_dimension_unpack(nodes, ratio): """Calculate the two underlying dimensions from the total number of nodes Args: nodes (int): combined dimensions ratio (float): ratio between the two dimensions Returns: int, int: separated dimensions """ dim1 = int((nodes...
bigcode/self-oss-instruct-sc2-concepts
def count_ports(port_mask): """Return the number of ports of given portmask""" ports_in_binary = format(int(port_mask, 16), 'b') nof_ports = ports_in_binary.count('1') return nof_ports
bigcode/self-oss-instruct-sc2-concepts
import functools def _positional(max_pos_args): """A decorator to declare that only the first N arguments may be positional. Note that for methods, n includes 'self'. """ def positional_decorator(wrapped): @functools.wraps(wrapped) def positional_wrapper(*args, **kwds): if len(args) > max_pos_a...
bigcode/self-oss-instruct-sc2-concepts
def convert_example_test(example, tokenizer, max_seq_length=512, pad_to_max_seq_len=False): """ Builds model inputs from a sequence. A BERT sequence has the following format: - single sequence: ``[CLS] X [SEP]`` Ar...
bigcode/self-oss-instruct-sc2-concepts
import random def create_random_string(length=7, chars='ABCDEFGHJKMNPQRSTUVWXYZ23456789', repetitions=False): """ Returns a random string, based on the provided arguments. It returns capital letters and numbers by default. Ambiguous characters are left out, repetitions will b...
bigcode/self-oss-instruct-sc2-concepts
def file_get_contents(filepath): """Get file contents""" with open(filepath) as f: return f.read()
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def convert_to_set(convert_this: Union[list, set, str, tuple]) -> set: """ Convert a string, a tuple, or a list into a set (i.e. no duplicates, unordered)""" if isinstance(convert_this, set): # functions using this expect a set, so everything # else just captu...
bigcode/self-oss-instruct-sc2-concepts
def get_word_string(word, guesses): """ This function will return a string of the word with the correct guesses. """ # Initialize the string. string = "" # Loop through the word. for letter in word: # Check if the letter has been guessed. if letter in guesses: # Add the letter to the string. string +=...
bigcode/self-oss-instruct-sc2-concepts
def get_resource_names_output(resources): """ Creates the output dict with the names of all resources to be created. """ names = [resource['name'] for resource in resources] return {'name': 'resources', 'value': names}
bigcode/self-oss-instruct-sc2-concepts
import torch def batch_lstsq(B, A): """Compute the least-squares solution. Finds ``x`` that minimizes ``Ax - B`` Parameters ---------- input : torch.Tensor (b, m, k) A : torch.Tensor (b, m, n) Returns ------- torch.Tensor (b, n, k) least squares solution....
bigcode/self-oss-instruct-sc2-concepts
import six def php_serialize(value): """ Serialize a value for use with PHP's deserialize() function. This function can serialize bytes, strings, integers, floats, booleans, None, lists, dicts and custom objects implementing __php__(). Args: value: The value to serialize. Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def dict_from_file(filename, key_type=str): """Load a text file and parse the content as a dict. Each line of the text file will be two or more columns splited by whitespaces or tabs. The first column will be parsed as dict keys, and the following columns will be parsed as dict values. Args: ...
bigcode/self-oss-instruct-sc2-concepts
def unite_characteristics(species): """ This function unites the characteristics of all the given species Parameters: species (list of species or ParallelSpecies object) """ characteristics = set() if species is not None: for spe in species: characterist...
bigcode/self-oss-instruct-sc2-concepts
def layer_is_in_mark(layer, mark): """ Whether the given layer is in the given mark. """ return layer["mark"] == mark or ("type" in layer["mark"] and layer["mark"]["type"] == mark)
bigcode/self-oss-instruct-sc2-concepts
def rescale(n, after=[0,1], before=[]): """ Helper function to rescale a vector between specified range of values :param numpy array n: a vector of numbers to be rescale :param list after: range of values to which to scale n :param list before: range of values in which n is contained """ ...
bigcode/self-oss-instruct-sc2-concepts
import itertools def _merge(d, keys): """ Merge multiple lists from a dictionary into one iterator. e.g. _merge({'a': [1, 2], 'b': [3]}, ['a', 'b']) -> iter(1, 2, 3) :param d: dictionary :type d: dict :param keys: keys to merge :type keys: [hashable] :returns: iterator ...
bigcode/self-oss-instruct-sc2-concepts
def add_nipsa_action(index, annotation): """Return an Elasticsearch action for adding NIPSA to the annotation.""" return { "_op_type": "update", "_index": index, "_type": "annotation", "_id": annotation["_id"], "doc": {"nipsa": True} }
bigcode/self-oss-instruct-sc2-concepts
def player_listing(table): """ Returns the list of seats with players and stacks, for the hand history. """ _str = '' for i, s in enumerate(table.seats): if s.player is None: _str += 'Seat #{}:\n'.format(i) else: _str += 'Seat #{}: {}(${})\n'.format(i, str(s.player), ...
bigcode/self-oss-instruct-sc2-concepts
def det_prob_query(p1: float, k: int, l: int) -> float: """ Compute the probability of finding point q < cR Parameters ---------- p1 P_1 as determined with Union[floky.stats.collision_prob_cosine, floky.stats.collision_prob_l2] k Number of hash digits. l Number of ha...
bigcode/self-oss-instruct-sc2-concepts
def dual_filter(cond, seq): """filter `seq` on `cond`; return two lists: (matches, non_matches)""" pos,neg = [],[] for x in seq: (pos if cond(x) else neg).append(x) return pos,neg
bigcode/self-oss-instruct-sc2-concepts
from typing import List def quantile(xs: List[float], p: float) -> float: """Returns the pth-percentile value in x""" p_index = int(p * len(xs)) return sorted(xs)[p_index]
bigcode/self-oss-instruct-sc2-concepts
import re def explode_ltr_model_definition(definition): """ Parse a string describing a ltr featureset or model (featureset|model):name[@storename] Parameters ---------- definition: string the model/featureset definition Returns ------- list: 3 elements list: type, na...
bigcode/self-oss-instruct-sc2-concepts
def first(xs): """Grab the first item from a list-like thing.""" return xs[0]
bigcode/self-oss-instruct-sc2-concepts
def model_trapezoidal_pulses(pileup_time, energy1, energy2, cfg): """ Models the pileup energy based on a trapezoidal filter. We have 4 scenarios for the pileup. The final energy depends on when the pileup signal peaks: 1. fully inside the gap of the first signal, 2. between the gap and the ...
bigcode/self-oss-instruct-sc2-concepts
def print_files(arguments): """Prints the current location of raw database files.""" print ("Files for database '%s':" % arguments.name) for k in arguments.files: print(k) return 0
bigcode/self-oss-instruct-sc2-concepts
def factorial_r(n): """ Input: a number. Output: find the factorial of the input number using recursion. """ if n == 0: return 0 if n == 1: return 1 else: return (n * factorial_r(n-1))
bigcode/self-oss-instruct-sc2-concepts
import torch def mixup_criterion(preds, target): """Implements loss for Mixup for EEG data. See [1]_. Implementation based on [2]_. Parameters ---------- preds : torch.Tensor Predictions from the model. target : torch.Tensor | list of torch.Tensor For predictions without mixu...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def is_file(file_obj): """Check a file exists on the system. Examples -------- :: >>> from pyutil.sys_checks import is_file >>> if is_file('path/to/file'): >>> pass """ p = Path(file_obj) return p.is_file()
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import Tuple def make_in_list_sql_clause( database_engine, column: str, iterable: Iterable ) -> Tuple[str, list]: """Returns an SQL clause that checks the given column is in the iterable. On SQLite this expands to `column IN (?, ?, ...)`, whereas on Postgres it...
bigcode/self-oss-instruct-sc2-concepts
def filter_cannonical(df): """Retains only cannonical chromosomes in bed-like df.""" df = df[df.loc[:, 0].str.match("chr[0-9|X|Y]+[a|b]?$")] return df
bigcode/self-oss-instruct-sc2-concepts
import typing def type_hints(f): """Same as `typing.get_type_hints` but returns `{}` if not allowed type.""" allowed_types = typing._allowed_types # type:ignore return typing.get_type_hints(f) if isinstance(f, allowed_types) else {}
bigcode/self-oss-instruct-sc2-concepts
def get_function(name, entries): """Generates lookup function with given name and lookup table entries.""" contents = """ absl::optional<tensorflow::gtl::FlatSet<int>> {name}( const tensorflow::string &op_name) {{ static std::array<OpIndexInfo, {count}> a = {{{{ """.format( name=name, count=len(entries) +...
bigcode/self-oss-instruct-sc2-concepts
import re def remove_unnecessary_spaces(text): """Removes spaces at the beginning, end and multiple spaces in between in the given text""" return re.sub(' +', ' ', text).strip()
bigcode/self-oss-instruct-sc2-concepts
def count_leaf_items(item_list): """Recursively counts and returns the number of leaf items in a (potentially nested) list. """ print(f"List: {item_list}") count = 0 for item in item_list: if isinstance(item, list): print("Encountered sublist") count +...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def str2datetime(dcm_date: str) -> datetime: """Parse a date in DICOM string format and return a datetime object. Strings can come in the following formats: YYYYMMDD (date), or YYYYMMDDHHMMSS.FFFFFF&ZZXX (datetime) -as specified by the DICOM standard. Parameters...
bigcode/self-oss-instruct-sc2-concepts
def _scipy_distribution_positional_args_from_dict(distribution, params): """Helper function that returns positional arguments for a scipy distribution using a dict of parameters. See the `cdf()` function here https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html#Methods\ to see a...
bigcode/self-oss-instruct-sc2-concepts
def str_point(point: tuple, precision: int = 1): """Return a printed tuple with precision""" prec_str = "{:." + str(precision) + "f}" format_str = "(" + prec_str + ", " + prec_str + ")" x, y = point return format_str.format(x, y)
bigcode/self-oss-instruct-sc2-concepts
def feedback_calculate(answer, guess): """ In this function I'm handling the guess from the player or computer. I'm returning this value as described in the article, Yet another mastermind strategy. Its going to be a list with 2 items. - The first number refers to the amount of 'pawns' that ar...
bigcode/self-oss-instruct-sc2-concepts
def combine_bboxes(bboxes, threshold=0.6): """ If the bboxes are close together, combine them into one. We check this by comparing the sum of areas over the area of the combined bbox. If it's over a threshold, we go ahead and combine. Inputs: bboxes - list of (x0, y0, x1, y1) threso...
bigcode/self-oss-instruct-sc2-concepts
def calc_unsaturated_evaporation(pet, unsatStore, fieldCap, wetFrac): """ Calculate evaporation from the unsaturated zone Parameters ---------- pet : int or float Potential evapotranspiration [mm day^-1] unsatStore : int or float Storage in the unsaturated zone [mm] fieldCap : i...
bigcode/self-oss-instruct-sc2-concepts
def sanitize_filename(s): """Sanitizes a string so it could be used as part of a filename.""" def replace_insane(char): if char in u' .\\/|?*<>:"' or ord(char) < 32: return '_' return char return u''.join(map(replace_insane, s)).strip('_')
bigcode/self-oss-instruct-sc2-concepts
def get_current_triplett(sequence, position, forward=True): """returns the triplett of the current position and the position within the triplett""" if not forward: sequence = sequence[::-1] position = len(sequence)-position-1 triplett_position = position % 3 start_of_triplett = int(posit...
bigcode/self-oss-instruct-sc2-concepts
def get_chains(struct): """Returns all chains of a Bio.PDB.Structure.Structure.""" return struct.child_list[0].child_list
bigcode/self-oss-instruct-sc2-concepts
def get_weekday(day_datetime): """ UTILITY FUNCTION takes the datetime object and returns its week day. """ week_days = {0:'monday', 1:'tuesday', 2:'wednesday', 3:'thursday', 4:'friday', 5:'saturday', ...
bigcode/self-oss-instruct-sc2-concepts
import requests def get_player(id): """Return a snooker player's full name based on his ID.""" player = requests.get('http://api.snooker.org/', params={'p': id}) player = player.json()[0] # the data consists of a single dictionary in a list return f"{player['FirstName']} {player['LastName']}"
bigcode/self-oss-instruct-sc2-concepts
import struct import socket def ip2int(ip): """Convert IP as string to integer.""" return struct.unpack('!L',socket.inet_aton(ip))[0]
bigcode/self-oss-instruct-sc2-concepts
def fill_mean(df): """Fill NaN with mean.""" df = df.fillna(df.mean().fillna(0).to_dict()) return df
bigcode/self-oss-instruct-sc2-concepts
def normalise_suffix(suffix): """Bring suffix to lowercase without dot.""" if suffix.startswith('.'): suffix = suffix[1:] return suffix.lower()
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def pretty_date(time): """ Get a datetime object or a int() Epoch timestamp and return a pretty string like 'an hour ago', 'Yesterday', '3 months ago', 'just now', etc Based on https://stackoverflow.com/a/1551394/713980 Adapted by sven1103 """ now = datet...
bigcode/self-oss-instruct-sc2-concepts
def _get_queue_arguments(rabbit_ha_queues, rabbit_queue_ttl): """Construct the arguments for declaring a queue. If the rabbit_ha_queues option is set, we try to declare a mirrored queue as described here: http://www.rabbitmq.com/ha.html Setting x-ha-policy to all means that the queue will be mi...
bigcode/self-oss-instruct-sc2-concepts
def get_dict_from_result(db_result): """ Returns a list of dictionaries where each dictionary is {field:value} pairs for one row. """ d, a = {}, [] for rowproxy in db_result: # rowproxy.items() returns an array like [(field0, value0), (field1, value1)] for column, value in rowpr...
bigcode/self-oss-instruct-sc2-concepts
def Q_014_1(n): """ 14. 先頭からN行を出力 自然数Nをコマンドライン引数などの手段で受け取り,入力のうち先頭のN行だけを表示せよ. """ data = [] with open('data/hightemp.txt', 'r') as f: data = [line.strip() for line, _ in zip(f, range(10))] return data
bigcode/self-oss-instruct-sc2-concepts
import re def skip_member(app, what, name, obj, skip, options): """Ignore ugly auto-generated doc strings from namedtuple.""" doc = getattr(obj, "__doc__", "") or "" # Handle when __doc__ is missing on None is_namedtuple_docstring = bool(re.fullmatch("Alias for field number [0-9]+", doc)) return is_n...
bigcode/self-oss-instruct-sc2-concepts