seed
stringlengths
1
14k
source
stringclasses
2 values
def collection_attribs(col): """Returns a list of the unique non-subscripted attributes of items in `col`.""" attribs = (attrib for item in col for attrib in item.__dict__ if attrib[0] != '_') return list(set(attribs))
bigcode/self-oss-instruct-sc2-concepts
def f_to_c(f): """ Convert fahrenheit to celcius """ return (f - 32.0) / 1.8
bigcode/self-oss-instruct-sc2-concepts
import math def e_dist(p1,p2): """ Takes two points and returns the euclidian distance """ x1,y1=p1 x2,y2=p2 distance = math.sqrt((x1-x2)**2+(y1-y2)**2) return int(distance)
bigcode/self-oss-instruct-sc2-concepts
import json def serialize(d): """ Serialize a dict as a json string. To be used in client requests """ return json.dumps(d)
bigcode/self-oss-instruct-sc2-concepts
def power(n): """Return 2 to the n'th power""" return 2 ** n
bigcode/self-oss-instruct-sc2-concepts
def flipBit(int_type, offset): """Flips the bit at position offset in the integer int_type.""" mask = 1 << offset return(int_type ^ mask)
bigcode/self-oss-instruct-sc2-concepts
def expand_pv(pv): """ Returns the LCS Process Variable in full syntax AADDDNNNCMM as a string where AA is two character area, DD is device type, NNN is device number, C is channel type, MM is channel number Returns partial PVs when input string is incomplete. ...
bigcode/self-oss-instruct-sc2-concepts
import random def generate_equations(allowed_operators, dataset_size, min_value, max_value): """Generates pairs of equations and solutions to them. Each equation has a form of two integers with an operator in between. Each solution is an integer with the result of the operaion. allowed_ope...
bigcode/self-oss-instruct-sc2-concepts
def parsedFile(file): """Take a parsed file and return the list Of Chords and Interval Vectors. The file was already parsed possibly from corpus. Then with chordify and PC-Set we compute a list of PC-chords and Interval Vectors. """ mChords = file.chordify() chordList = [] chordVectors = []...
bigcode/self-oss-instruct-sc2-concepts
def grab_job_links(soup): """ Grab all non-sponsored job posting links from a Indeed search result page using the given soup object Parameters: soup: the soup object corresponding to a search result page e.g. https://ca.indeed.com/jobs?q=data+scientist&l=Toronto&start=20 ...
bigcode/self-oss-instruct-sc2-concepts
def gene2bin(parameters, gene, geneType): """ geneBin = gene2bin(parameters, gene, geneType) Turns genes into the binary-string form gene: integer geneType: string geneBin: string, of all ones and zeros >>> geneType = 'repn' >>> parameters = {'genetics': {geneT...
bigcode/self-oss-instruct-sc2-concepts
def unique_items(seq): """A function that returns all unique items of a list in an order-preserving way""" id_fn = lambda x: x seen_items = {} result = [] for item in seq: marker = id_fn(item) if marker in seen_items: continue seen_items[marker] = 1 result.append(item...
bigcode/self-oss-instruct-sc2-concepts
def checkComp(parts, ind, wmap): """ Finds longest compound terms from list of tokens starting at an index. :param parts: List of tokens :param ind: Index of the current token :param wmap: Dictionary mapping token to lemma :returns: Longest compound term, index after the longest compound ter...
bigcode/self-oss-instruct-sc2-concepts
def rgb_to_hex(rgb): """Returns the hex color code for the rgb tuple.""" hexcodes = ("%02x" % int(v * 255) for v in rgb) return "#%s" % "".join(hexcodes)
bigcode/self-oss-instruct-sc2-concepts
def _num_frame_valid(nsp_src, nsp_win, len_hop): """Computes the number of frames with 'valid' setting""" return (nsp_src - (nsp_win - len_hop)) // len_hop
bigcode/self-oss-instruct-sc2-concepts
def slice(ds, idx_start, idx_stop): """Retrieve a slice of the dataset.""" if type(ds) != tuple: raise TypeError("'ds' isn't a tuple") if len(ds) != 2: raise ValueError("'ds' isn't a 2-element tuple") if idx_stop < idx_start: raise RuntimeError("'idx_start' value of the range has a greater value then 'i...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def keyhash(string): """Hash the string using sha-1 and output a hex digest. Helpful for anonymizing known_mods.""" return hashlib.sha1(string.encode('utf-8')).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def remove_query_string(url): """ Removes query string from a url :param url: string with a url :return: clean base url """ if not isinstance(url, str): raise TypeError('Argument must be a string') return url.split('?')[0]
bigcode/self-oss-instruct-sc2-concepts
def file_mode_converter(num: int): """ 十进制mode 转 user:group:other mode 0444 <--> 292 444 --> 100 100 100(2) --> 292(10) :param num: 十进制数字 :return: ser:group:other mode 格式:0ugo """ # 数字转二进制字符串 user = (num & 0b111000000) >> 6 group = (num & 0b111000) >> 3 other = n...
bigcode/self-oss-instruct-sc2-concepts
def listify(i): """ Iterable to list. """ return list(i)
bigcode/self-oss-instruct-sc2-concepts
def aztec_xihuitl_date(month, day): """Return an Aztec xihuitl date data structure.""" return [month, day]
bigcode/self-oss-instruct-sc2-concepts
def intersect_bounds( bbox0: tuple[float, float, float, float], bbox1: tuple[float, float, float, float] ) -> tuple[float, float, float, float]: """Get the intersection in w s e n Parameters: bbox0: bounding coordinates bbox1: bounding coordinates Returns: intersection coor...
bigcode/self-oss-instruct-sc2-concepts
def bar(self, *args, **kwargs): """ Make a bar plot Wraps matplotlib bar() See plot documentation in matplotlib for accepted keyword arguments. """ if len(self.dims) > 1: raise NotImplementedError("plot can only be called up to one-dimensional array.") return self._plot1D('bar',*args, *...
bigcode/self-oss-instruct-sc2-concepts
def auth_path(index, height): """Return the authentication path for a leaf at the given index. Keyword arguments: index -- the leaf's index, in range [0, 2^height - 1] height -- the height of the binary hash tree Returns: The authentication path of the leaf at the given index as a list of nod...
bigcode/self-oss-instruct-sc2-concepts
def scene_to_dict(scene, use_base64=False): """ Export a Scene object as a dict. Parameters ------------- scene : trimesh.Scene Scene object to be exported Returns ------------- as_dict : dict Scene as a dict """ # save some basic data about the scene export = ...
bigcode/self-oss-instruct-sc2-concepts
def get_environment(hostname): """Get whether dev or qa environment from Keeper server hostname hostname(str): The hostname component of the Keeper server URL Returns one of 'DEV', 'QA', or None """ environment = None if hostname: if hostname.startswith('dev.'): environment ...
bigcode/self-oss-instruct-sc2-concepts
def _import_string(names): """return a list of (name, asname) formatted as a string""" _names = [] for name, asname in names: if asname is not None: _names.append(f"{name} as {asname}") else: _names.append(name) return ", ".join(_names)
bigcode/self-oss-instruct-sc2-concepts
def _eff_2_nom(effective_rate, piy): """Convert an effective rate to a nominal rate. :effective_rate: effective rate to be changed :piy: number of periods in a year for the effective rate """ return effective_rate * piy
bigcode/self-oss-instruct-sc2-concepts
def is_fasta_label(x): """Checks if x looks like a FASTA label line.""" return x.startswith(">")
bigcode/self-oss-instruct-sc2-concepts
def keep_firstn(lst, n): """Keep only the first n elems in a list.""" if len(lst) <= n: return lst else: return lst[:n]
bigcode/self-oss-instruct-sc2-concepts
import torch def combine_obj_pixels(obj_pix, obj_dim): """Combine obj-split pixels into a single image. Args: obj_pix: B, ..., Nobj, ..., C, H, W obj_dim: The dimension to reduce over -- which corresponds to objs Returns B, ..., ..., C, H, W """ if obj_pix is None: ...
bigcode/self-oss-instruct-sc2-concepts
def _svg_convert_size(size): """ Convert svg size to the px version :param size: String with the size """ # https://www.w3.org/TR/SVG/coords.html#Units conversion_table = { "pt": 1.25, "pc": 15, "mm": 3.543307, "cm": 35.43307, "in": 90 } if len(si...
bigcode/self-oss-instruct-sc2-concepts
import re def parse_ticket_links(raw_links): # type: (str) -> list """ Parses the link IDs from the ticket link response An example to an expected 'raw_links' is: "RT/4.4.4 200 Ok id: ticket/68315/links Members: some-url.com/ticket/65461, some-url.com/ticket/65462, ...
bigcode/self-oss-instruct-sc2-concepts
def calculate_dbot_score(score: int) -> int: """Transforms cyber risk score (reputation) from SOCRadar API to DBot Score and using threshold. Args: score: Cyber risk score (reputation) from SOCRadar API Returns: Score representation in DBot """ return_score = 0 # Malicious ...
bigcode/self-oss-instruct-sc2-concepts
def tolerance_tests_to_report(test_list_instance): """return tolerance tests to be reported for this test_list_instance""" return test_list_instance.tolerance_tests()
bigcode/self-oss-instruct-sc2-concepts
def parse_like_term(term): """ Parse search term into (operation, term) tuple. Recognizes operators in the beginning of the search term. * = case insensitive (can precede other operators) ^ = starts with = = exact :param term: Search term """ cas...
bigcode/self-oss-instruct-sc2-concepts
import re def _get_first_sentence(s): """ Get the first sentence from a string and remove any carriage returns. """ x = re.match(".*?\S\.\s", s) if x is not None: s = x.group(0) return s.replace('\n', ' ')
bigcode/self-oss-instruct-sc2-concepts
def get_binding_data_vars(ds, coord, as_names=False): """Get the data_vars that have this coordinate Parameters ---------- ds: xarray.Dataset coord_name: str Return ------ list List of data_var names """ if not isinstance(coord, str): coord = coord.name out ...
bigcode/self-oss-instruct-sc2-concepts
import calendar def leap_years_between(year1: int, year2: int) -> int: """ determine how many leap years there will be between the years year1 and year2 inclusive >>> leap_years_between(2018,2020) 1 >>> leap_years_between(2017,2022) 1 >>> leap_years_between(2000,2020) 6 """ retur...
bigcode/self-oss-instruct-sc2-concepts
def clamp(x, _min, _max): """Clamp a value between a minimum and a maximum""" return min(_max, max(_min, x))
bigcode/self-oss-instruct-sc2-concepts
def cytoscape_element_from_client(client): """Generates a cytoscape element from a Client proto. Args: client: A Client proto. Returns: A cytoscape element dictionary with values derived from the proto. """ client_element = { "data": { "id": client.name, ...
bigcode/self-oss-instruct-sc2-concepts
def kv_parser(inp): """ Converts a url-encoded string to a dictionary object. """ return {obj[0]:obj[1] for obj in (obj.split('=') for obj in inp.split('&')) if len(obj) == 2}
bigcode/self-oss-instruct-sc2-concepts
def postorder_optimised(preorder: list, length: int) -> list: """ Use a static index pre_index to iterate over the list items one by one when the loop returns, store the root item in list. Time Complexity: O(n) Space Complexity: O(n) """ min_val, max_val, pre_index = -1000_000, 1000_000, 0 ...
bigcode/self-oss-instruct-sc2-concepts
import string import random def rndstr(size=16): """ Returns a string of random ascii characters or digits :param size: The length of the string :return: string """ _basech = string.ascii_letters + string.digits return "".join([random.choice(_basech) for _ in range(size)])
bigcode/self-oss-instruct-sc2-concepts
import re def clean_html(raw_html): """ Utility function for replace HTML tags from string. """ ltgt = re.compile('<.*?>') whitespace = re.compile('\s+') clean_text = whitespace.sub(" ", ltgt.sub("", raw_html)).replace("\n", " ") return clean_text
bigcode/self-oss-instruct-sc2-concepts
import json def load_json(file_name_template, record_id): """Helper function to return JSON data saved to an external file. file_name_template -- Template for building file name. Expected to contain a string substitution element whose value is specified by the record_id parameter. e.g. 'json/s...
bigcode/self-oss-instruct-sc2-concepts
import requests def get_tag_list_from_docker_hub(repo, **kwargs): """Retrieves the list of tags from a docker repository on Docker Hub.""" docker_token_url = "https://auth.docker.io/token" docker_token_url += "?service=registry.docker.io&scope=repository:{}:pull" def get_token_from_docker_hub(repo, *...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Tuple def filter_multiple_pronunications( lexicon: List[Tuple[str, List[str]]] ) -> List[Tuple[str, List[str]]]: """Remove multiple pronunciations of words from a lexicon. If a word has more than one pronunciation in the lexicon, only the first one is kept, ...
bigcode/self-oss-instruct-sc2-concepts
import copy def get_category_obj(data, category_name): """Extract obj with `name` == `category_name` from `data`.""" cats = copy.copy(data) while(cats): cat = cats.pop() if cat['name'] == category_name: return cat if 'children' in cat: cats.extend(cat['child...
bigcode/self-oss-instruct-sc2-concepts
def skip_comments(lines): """Filter out lines starting with a #.""" return (line for line in lines if not line.startswith('#'))
bigcode/self-oss-instruct-sc2-concepts
def format_number(num): """ Formats a one or two digit integer to fit in four spaces. Returns a string of the formatted number string. """ result = " " + str(num) + " " if num < 10: result = result + " " return result
bigcode/self-oss-instruct-sc2-concepts
def extract_spec_norm_kwargs(kwargs): """Extracts spectral normalization configs from a given kwarg.""" return dict( iteration=kwargs.pop("iteration", 1), norm_multiplier=kwargs.pop("norm_multiplier", .99))
bigcode/self-oss-instruct-sc2-concepts
def parse_in(line): """Parse an incoming IRC message.""" prefix = '' trailing = [] if not line: print("Bad IRC message: ", line) return None if line[0] == ':': prefix, line = line[1:].split(' ', 1) if line.find(' :') != -1: line, trailing = line.split(' :', 1) ...
bigcode/self-oss-instruct-sc2-concepts
def name_blob(mosaic_info, item_info): """ Generate the name for a data file in Azure Blob Storage. This follows the pattern {kind}/{mosaic-id}/{item-id}/data.tif where kind is either analytic or visual. """ prefix = "analytic" if "analytic" in mosaic_info["name"] else "visual" return f"{pr...
bigcode/self-oss-instruct-sc2-concepts
def optional(**kwargs) -> dict: """Given a dictionary, this filters out all values that are ``None``. Useful for routes where certain parameters are optional. """ return { key: value for key, value in kwargs.items() if value is not None }
bigcode/self-oss-instruct-sc2-concepts
def drop_engine_after(prev_engine): """ Removes an engine from the singly-linked list of engines. Args: prev_engine (projectq.cengines.BasicEngine): The engine just before the engine to drop. Returns: Engine: The dropped engine. """ dropped_engine = prev_engine.next_...
bigcode/self-oss-instruct-sc2-concepts
def _get_material_sets(cell_sets): """Get the cell sets that are materials.""" material_names = [] material_cells = [] if cell_sets: set_names = list(cell_sets.keys()) for set_name in set_names: if "MATERIAL" in set_name.upper(): material_names.append(set_name...
bigcode/self-oss-instruct-sc2-concepts
def unit_name(unit): """ Return name of unit (must of course match unit_t in opendps/uui.h) """ if unit == 0: return "unitless" # none if unit == 1: return "A" # ampere if unit == 2: return "V" # volt if unit == 3: return "W" # watt if unit == 4: ...
bigcode/self-oss-instruct-sc2-concepts
def headers(token=None): """ Creates a dict of headers with JSON content-type and token, if supplied. :param token: access token for account :return: dictionary of headers """ data = {'Content-Type': 'application/json'} if token: data['Token'] = token return data
bigcode/self-oss-instruct-sc2-concepts
def bmatrix(arr): """ Converts a numpy array (matrix) to a LaTeX bmatrix Args: arr: Array Returns: LaTeX bmatrix as a string Raises: ValueError: If the array has more than two dimensions """ if len(arr.shape) > 2: raise ValueError('bmatrix can at most displa...
bigcode/self-oss-instruct-sc2-concepts
def get_cookie(self, name, default=False): """Gets the value of the cookie with the given name,else default.""" if name in self.request.cookies: return self.request.cookies[name] return default
bigcode/self-oss-instruct-sc2-concepts
def XML_calib(calib_data: list, cf: int = 1): """Transforms a calibration array of floats into a .xml formatation. Args: calib_data (list): list of the calibration data for the microphone. Returns: str: string of calibration data in a .xml format. """ new_pos = '<pos\tName="Point {...
bigcode/self-oss-instruct-sc2-concepts
def quadratic_cutoff(r_cut: float, ri: float, ci: float): """A quadratic cutoff that goes to zero smoothly at the cutoff boundary. Args: r_cut (float): Cutoff value (in angstrom). ri (float): Interatomic distance. ci (float): Cartesian coordinate divided by the distance. Returns: ...
bigcode/self-oss-instruct-sc2-concepts
import requests def get_number_of_records(parameters): """ :param parameters: Dictionary with parameters of query to Zenodo API (dict) :return: Number of records retrieved from the query (int) """ response_hits = requests.get('https://zenodo.org/api/records/', params=parameters) hits = respons...
bigcode/self-oss-instruct-sc2-concepts
import token import requests def get_payment_details(trans_id: str) -> dict: """ Takes the transaction_id from the request and returns the status info in json. It transaction_id is different from the transaction_ref so it should be grabbed from the request in the redirect url """ url = f"https://a...
bigcode/self-oss-instruct-sc2-concepts
def _deep_map(func, *args): """Like map, but recursively enters iterables Ex: >>> _deep_map(lambda a, b: a + b, (1, 2, (3, (4,), 5)), (10, 20, (30, (40,), 50))) [11, 22, [33, [44], 55]] """ try: return [_deep_map(func, *z) for z in z...
bigcode/self-oss-instruct-sc2-concepts
def get_review_request_id(regex, commit_message): """Returns the review request ID referenced in the commit message. We assume there is at most one review request associated with each commit. If a matching review request cannot be found, we return 0. """ match = regex.search(commit_message) ret...
bigcode/self-oss-instruct-sc2-concepts
import re def get_version_parts(version, for_sorting=False): """Returns a list containing the components of the version string as numeric values. This function can be used for numeric sorting of version strings such as '2.6.0-rc1' and '2.4.0' when the 'for_sorting' parameter is specified as true.""" ...
bigcode/self-oss-instruct-sc2-concepts
def _compressed_suffix(compression): """Returns a suitable suffix (including leading dot, eg ".bz2") for the selected compression method.""" if compression is True: # select best compression -- but is xz always the best? return ".xz" elif compression in ("xz", "bz2", "gz"): # valid compression i...
bigcode/self-oss-instruct-sc2-concepts
def sort_by(comparator, list): """Sorts the list according to the supplied function""" return sorted(list, key=comparator)
bigcode/self-oss-instruct-sc2-concepts
def ramp(duration, initial, final): """Defines a linear ramp. f(t) = (final - initial)*t/duration + initial Args: duration (float): Duration of ramp initial (float): Starting value of ramp final (float): Ending value of ramp Returns: func: Function that takes a single ...
bigcode/self-oss-instruct-sc2-concepts
import csv def csv_to_list(filename): """ creates a list of the contents of the csv """ out = [] with open(filename, newline = '') as f: #open csv file containing names reader = csv.reader(f) #read the file for row in reader: #loop over rows of the file out += row #add co...
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce def arr2(value, *forms): """ Clojure's second threading macro implementation. The logic is the same as `thread_first`, but puts the value at the end of each form. See https://clojuredocs.org/clojure.core/->> :param value: Initial value to process. :type valu...
bigcode/self-oss-instruct-sc2-concepts
def get_atoms_per_fu(doc): """ Calculate and return the number of atoms per formula unit. Parameters: doc (list/dict): structure to evaluate OR matador-style stoichiometry. """ if 'stoichiometry' in doc: return sum([elem[1] for elem in doc['stoichiometry']]) return sum([elem[1] for...
bigcode/self-oss-instruct-sc2-concepts
def batch_to_single_instance(X): """ Take the first instance of an array that contains a batch of items. Parameters ---------- X : nd array, shape: [batch_size, \\*instance_shape] A numpy array whose first axis is the batch axis. Returns ------- x : (n-1)d array, shape: [\\*in...
bigcode/self-oss-instruct-sc2-concepts
def _unpack_one_element_list(scalar_or_list): """If the value is a list and it only has one value, we unpack it; otherwise, we keep the list. This is used for size parameter inside tf.io.SparseFeature. """ if isinstance(scalar_or_list, list) and len(scalar_or_list) == 1: return scalar_or_lis...
bigcode/self-oss-instruct-sc2-concepts
import re def humansorted_strings(l): """Sort a list of strings like a human Parameters ---------- l : list A list of strings Returns ------- list The sorted list """ def alphanum_key(s): key = re.split(r'(\d+)', s) key[1::2] = map(int, key[1::2]) ...
bigcode/self-oss-instruct-sc2-concepts
def make_ratings_hash(ratings): """ Make a hashtable of ratings indexed by (userid,itemid) @param ratings: pandas.DataFrame of ratings @return a hashed version of the input ratings, which maps (userid, itemid) tuples to the relevant rating. """ rhash = {} # for every 3-colu...
bigcode/self-oss-instruct-sc2-concepts
def argmax(list, score_func=None): """ If a score function is provided, the element with the highest score AND the score is returned. If not, the index of highest element in the list is returned. If the list is empty, None is returned. """ if len(list) == 0: return None scores = list...
bigcode/self-oss-instruct-sc2-concepts
def get_loc_11(number=1): """Turn the the number for loc_11 into a string""" n = str(number) return n
bigcode/self-oss-instruct-sc2-concepts
def mark_backend_unsupported(func): """Mark a method as being not supported by a backend.""" func._oculy_backend_unsupported = True return func
bigcode/self-oss-instruct-sc2-concepts
import io def fetch_image(session, url, timeout=10): """download the satellite image for a tile. Args: session: the HTTP session to download the image from url: the tile imagery's url to download the image from timeout: the HTTP timeout in seconds. Returns: The satellite ...
bigcode/self-oss-instruct-sc2-concepts
def make_double_digit_str(num: int) -> str: """ useful for file names, turns 9 into "09" but keeps 15 as "15" :param num: one or two digit number :return: two digit number string """ return str(num) if num > 9 else "0" + str(num)
bigcode/self-oss-instruct-sc2-concepts
import math def get_es(temp): """ Reference page number: 29 Parameters ------------------------------ temp: (``float``) Air temperature in degrees Celcius Returns ------------------------------ es: (``float``) The saturation vapour pressure """ es = 0.6108 * mat...
bigcode/self-oss-instruct-sc2-concepts
def upper(name: str) -> str: """Convert the name value to uppercase. Arguments: name: name of the attr. Returns: The uppercase value. """ return name.upper()
bigcode/self-oss-instruct-sc2-concepts
def bubble_sort(some_list): """ https://en.wikipedia.org/wiki/Bubble_sort We continuously loop through the data set, swapping next-door-neighbors that are out of order. In this way, values will BUBBLE one spot towards their correct positions once per loop. O(N^2) """ iters = 0 did_swap ...
bigcode/self-oss-instruct-sc2-concepts
def get_selected_tests(args, tests, sources): """Return the selected tests.""" for exclude_test in args.exclude: tests_copy = tests[:] for i, test in enumerate(tests_copy): if test.startswith(exclude_test): tests.pop(i) sources.pop(i) return tests,...
bigcode/self-oss-instruct-sc2-concepts
def read_file(path): """ Return the contents of a file Arguments: - path: path to the file Returns: - contents of the file """ with open(path, "r") as desc_file: return desc_file.read().rstrip()
bigcode/self-oss-instruct-sc2-concepts
import textwrap import re def pytd_src(text): """Add a typing.Union import if needed.""" text = textwrap.dedent(text) if "Union" in text and not re.search("typing.*Union", text): return "from typing import Union\n" + text else: return text
bigcode/self-oss-instruct-sc2-concepts
import torch def KLD(mean, log_std): """ Calculates the Kullback-Leibler divergence of given distributions to unit Gaussians over the last dimension. See Section 1.3 for the formula. Inputs: mean - Tensor of arbitrary shape and range, denoting the mean of the distributions. log_std - T...
bigcode/self-oss-instruct-sc2-concepts
def has_duplicates(lst: list) -> bool: """Checks if a list has duplicate values""" return len(lst) != len(set(lst))
bigcode/self-oss-instruct-sc2-concepts
from dateutil import tz def datetime_to_isodate(datetime_): """Convert Python datetime to GitHub date string. :param str datetime_: datetime object to convert .. note:: Supports naive and timezone-aware datetimes """ if not datetime_.tzinfo: datetime_ = datetime_.replace(tzinfo=tz.tzutc(...
bigcode/self-oss-instruct-sc2-concepts
def _encode_csv(iterable_items): """ Encodes CSVs with special characters escaped, and surrounded in quotes if it contains any of these or spaces, with a space after each comma. """ cleaned_items = [] need_escape_chars = '"\\' need_space_chars = ' ,' for item in iterable_items: n...
bigcode/self-oss-instruct-sc2-concepts
def acquisitions_from_ifg_dates(ifg_dates): """Given a list of ifg dates in the form YYYYMMDD_YYYYMMDD, get the uniqu YYYYMMDDs that acquisitions were made on. Inputs: ifg_dates | list | of strings in form YYYYMMDD_YYYYMMDD. Called imdates in LiCSBAS nomenclature. Returns: acq_dates | l...
bigcode/self-oss-instruct-sc2-concepts
def merge_dicts_into(target, *dicts): """Merge the provided dicts into the target dict.""" for d in dicts: target.update(d) return target
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def check_on_grid(position: Tuple[int, int]) -> bool: """Checks if a given position is on the grid.""" return all([-1 < coord < 10 for coord in position])
bigcode/self-oss-instruct-sc2-concepts
import pathlib def git_repo_kwargs(repos_path: pathlib.Path, git_dummy_repo_dir): """Return kwargs for :func:`create_project_from_pip_url`.""" return { "url": "git+file://" + git_dummy_repo_dir, "parent_dir": str(repos_path), "name": "repo_name", }
bigcode/self-oss-instruct-sc2-concepts
def _decrement_lower_bound(interval): """ Decrement the lower bound of a possibly inverted interval. i.e. turn (1, 5) into (0, 5) and (5, 1) into (5, 0). Intervals in m8 alignment files can be inverted. """ (bound_one, bound_two) = interval if bound_one < bound_two: return (bound_one...
bigcode/self-oss-instruct-sc2-concepts
def fetch_object(service, obj_type, obj_name, create=False, create_args={}, **fetch_args): """Helper function to fetch objects from the Watson services. Params ====== - service: a Watson service instance - obj_type: object type, one of: "environment", "configuration", "collection", "workspace" ...
bigcode/self-oss-instruct-sc2-concepts
def atof(text): """ helper for natural_keys attempt to convert text to float, or return text :param text: arbitrary text :return: float if succeeded to convert, the input text as is otherwise """ try: retval = float(text) except ValueError: retval = text return retval
bigcode/self-oss-instruct-sc2-concepts