seed
stringlengths
1
14k
source
stringclasses
2 values
import torch def custom_collate_fn(batch): """ Since all images might have different number of BBoxes, to use batch_size > 1, custom collate_fn has to be created that creates a batch Args: batch: list of N=`batch_size` tuples. Example [(img_1, bboxes_1, ci_1, labels_1), ..., (img_N, bboxe...
bigcode/self-oss-instruct-sc2-concepts
def ferc1_etl_parameters(etl_settings): """Read ferc1_to_sqlite parameters out of test settings dictionary.""" return etl_settings.ferc1_to_sqlite_settings
bigcode/self-oss-instruct-sc2-concepts
def table2tsv(table): """Represent a list of lists of strings (a "table") as a "tsv" (tab separated value) string. """ return '\n'.join(['\t'.join(row) for row in table])
bigcode/self-oss-instruct-sc2-concepts
def ashift(num1, num2): """ ASHIFT num1 num2 outputs ``num1`` arithmetic-shifted to the left by ``num2`` bits. If num2 is negative, the shift is to the right with sign extension. The inputs must be integers. """ return num1 >> num2
bigcode/self-oss-instruct-sc2-concepts
def tuples_sorted_by_keys(adict): """Return list of (key, value) pairs of @adict sorted by keys.""" return [(key, adict[key]) for key in sorted(adict.keys())]
bigcode/self-oss-instruct-sc2-concepts
def index_of(seq, value, from_index=0): """ Description ---------- Return the index of a value in a sequence.\n Returns -1 if the value was not found. Parameters ---------- seq : (list or tuple or string) - sequence to iterate\n value: any - value to search for\n from_index : in...
bigcode/self-oss-instruct-sc2-concepts
def coverage(pileup): """Returns the sum of nucleotide reads (no gap or N) per position""" return pileup.sum(axis=0)[:4, :].sum(axis=0)
bigcode/self-oss-instruct-sc2-concepts
def split_phases(df): """ Separates DataFrame into groups by unique values of a column 'Phase', and returns a tuple of DataFrames. """ return( tuple([df.groupby('Phase').get_group(p) for p in df.Phase.unique()]) )
bigcode/self-oss-instruct-sc2-concepts
import re def FindMethods(section): """Spin through the 'method code index' section and extract all method signatures. When found, they are added to a result list.""" # Match lines like: # |[abcd] com/example/app/Class.method:(args)return # capturing the method signature methodPa...
bigcode/self-oss-instruct-sc2-concepts
def get_event_delete_role(bot, guild): """Return the event delete role, if it exists""" result = bot.db.get_event_delete_role_id(guild.id) if result: for role in guild.roles: if role.id == result.get('event_delete_role_id'): return role
bigcode/self-oss-instruct-sc2-concepts
def digitalSum(n): """Calculates the sum of the digits of `n`.""" if n < 10: return n else: return n % 10 + digitalSum(n // 10)
bigcode/self-oss-instruct-sc2-concepts
def get_graph_last_edge(g, filter_out_types=set()): """ Get the last edge of the graph or an empty edge if there is non :param g: a graph as a dictionary :param filter_out_types: a set fo edge types to filter out, if not empty the last edge of the specified type is returned :return: an edge as a di...
bigcode/self-oss-instruct-sc2-concepts
def to_number(s): """ Convert a string to a number. If unsuccessful, return the de-blanked string. """ ret = s # remove single quotes if "'" in ret: ret = ret.strip("'").strip() # try converting to booleans / None if ret == 'True': return True elif ret == 'False': ...
bigcode/self-oss-instruct-sc2-concepts
import json def get_cat_to_name_mapping(file): """ Read the json file provided and return a dictionary containing the mapping between categories and label names :param file: path to JSON file containing mapping between categories and label names :return cat_to_name: dictionary containing mapping betw...
bigcode/self-oss-instruct-sc2-concepts
def _format_time(total_seconds): """Format a time interval in seconds as a colon-delimited string [h:]m:s""" total_mins, seconds = divmod(int(total_seconds), 60) hours, mins = divmod(total_mins, 60) if hours != 0: return f"{hours:d}:{mins:02d}:{seconds:02d}" else: return f"{mins:02d}...
bigcode/self-oss-instruct-sc2-concepts
def split_into_quadrants(m): """ Split a nxn matrix into quadrants. Given A, returns A11, A12, A21, and A22. """ mid = m.shape[0] // 2 return m[:mid:, :mid:], m[:mid:, mid:], m[mid:, :mid], m[mid:, mid:]
bigcode/self-oss-instruct-sc2-concepts
def compreso(num, low, high): """ checks whether or not a number is between low and high """ return num>=low and num<=high
bigcode/self-oss-instruct-sc2-concepts
def print_gains(odrv, axis): """ Prints gains. Also returns them. """ axis_config = axis.controller.config # shorten that print("Position:", axis_config.pos_gain ) print("Velocity:", axis_config.vel_gain) print("Velocity Integrator:", axis_config.vel_integrator_gain) return axis_config....
bigcode/self-oss-instruct-sc2-concepts
def categorize_local_files(manifest): """Categorize the files in the lambda function's directory into two bins: python files and other files""" python = [] other = [] for filename in manifest.basedir.iterdir(): path = filename.relative_to(manifest.basedir) if path.suffix == '.py': ...
bigcode/self-oss-instruct-sc2-concepts
def read_paralogs(paralogs_file): """Read list of paralogs.""" if paralogs_file is None: # then nothing to return return set() f = open(paralogs_file, "r") paralogs = set(x.rstrip() for x in f.readlines()) f.close() return paralogs
bigcode/self-oss-instruct-sc2-concepts
def seconds_into_day(time): """Takes a time in fractional days and returns number of seconds since the start of the current day. Parameters ---------- time: float The time as a float. Returns ------- int The day's duration in seconds. """ return(int(round(86400....
bigcode/self-oss-instruct-sc2-concepts
def getattrs(attrs, getclasses): """return all attributes in the attribute list attrs, which are instances of one of the classes in getclasses""" return [attr for attr in attrs if isinstance(attr, tuple(getclasses))]
bigcode/self-oss-instruct-sc2-concepts
import time def utcut2dow(ut): """UTC UT -> day-of-week: 0..6 (Mon..Sun).""" return time.gmtime(ut).tm_wday
bigcode/self-oss-instruct-sc2-concepts
import torch def _safe_det_3x3(t: torch.Tensor): """ Fast determinant calculation for a batch of 3x3 matrices. Note, result of this function might not be the same as `torch.det()`. The differences might be in the last significant digit. Args: t: Tensor of shape (N, 3, 3). Returns: ...
bigcode/self-oss-instruct-sc2-concepts
import types from typing import Sequence from typing import Tuple def get_public_symbols( root_module: types.ModuleType) -> Sequence[Tuple[str, types.FunctionType]]: """Returns `(symbol_name, symbol)` for all symbols of `root_module`.""" fns = [] for name in getattr(root_module, "__all__"): o = getattr(...
bigcode/self-oss-instruct-sc2-concepts
def bud_cons(c1, r, e1, e2): """ Defines the budget constraint e = e1 + e2/(1+r) is total endowment """ e = e1 + e2/(1+r) return e*(1+r) - c1*(1+r)
bigcode/self-oss-instruct-sc2-concepts
import importlib def get_absolute_path_from_module_source(module: str) -> str: """Get a directory path from module source. E.g. `zenml.core.step` will return `full/path/to/zenml/core/step`. Args: module: A module e.g. `zenml.core.step`. """ mod = importlib.import_module(module) retur...
bigcode/self-oss-instruct-sc2-concepts
def write_peak_bedtool_string(cluster): """ Format Peak into NarrowBed format :param cluster: Peak object :return: str, format to NarrowBed format with tab-delimited, [chrom, start, stop, name, pval, strand, thick_start, thick_stop] """ cluster_info_list = [ cluster.chrom, cluste...
bigcode/self-oss-instruct-sc2-concepts
def remove_empty_string_list(str_list): """ Removes any empty strings from a list of strings :param str_list: List of strings :return: List of strings without the empty strings """ return list(filter(None, str_list))
bigcode/self-oss-instruct-sc2-concepts
import re def upper_to_under(var): """ Insert underscore before upper case letter followed by lower case letter and lower case all sentence. """ return re.sub('([a-z0-9])([A-Z])', r'\1_\2', re.sub('(.)([A-Z][a-z]+)', r'\1_\2', var)).lower()
bigcode/self-oss-instruct-sc2-concepts
def compress(s: str) -> str: """ Compress `s` by dropping spaces before ' ,.' characters and ensuring there is exactly one space before question mark """ dest = "" for a, b in zip(s, s[1:]): if a == ' ' and b in " ,.": pass # do not append to dest elif a != ' ' and b == '?': dest += a + ' ' else: d...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime import pytz def to_iso_time(timestamp): """Receives an arbitrary timestamp in UTC format (most likely in unix timestamp) and returns it as ISO-format. :param timestamp: arbitrary timestamp :return: timestamp in ISO 8601 and UTC timezone """ if isinstance(timestamp, (...
bigcode/self-oss-instruct-sc2-concepts
def get_fields(feature): """Return a dict with all fields in the given feature. feature - an OGR feature. Returns an assembled python dict with a mapping of fieldname -> fieldvalue""" fields = {} for i in range(feature.GetFieldCount()): field_def = feature...
bigcode/self-oss-instruct-sc2-concepts
def _format_inputs(x): """Transform inputs into (m,n,1) format for cost/activation functions. Returns formatted array. """ if x.ndim == 1: # vector return x.reshape(1, -1, 1) elif x.ndim == 2: if x.shape[0] == 1: # either single-row matrix or 1x1 matrix return x.T.resh...
bigcode/self-oss-instruct-sc2-concepts
def _GetPrincipleQuantumNumber(atNum): """ Get the principle quantum number of atom with atomic number equal to atNum """ if atNum<=2: return 1 elif atNum<=10: return 2 elif atNum<=18: return 3 elif atNum<=36: return 4 elif atNum<=54: return 5...
bigcode/self-oss-instruct-sc2-concepts
def mjd2lst(mjd, lng): """ Stolen from ct2lst.pro in IDL astrolib. Returns the local sidereal time at a given MJD and longitude. """ mjdstart = 2400000.5 jd = mjd + mjdstart c = [280.46061837, 360.98564736629, 0.000387933, 38710000.0] jd2000 = 2451545.0 t0 = jd - jd2000 t = t0/36525. ...
bigcode/self-oss-instruct-sc2-concepts
def postpend_str(base_word: str, postpend: str, separator: str='') -> str: """Appends str:postpend to str:base_word with default str:separator, returns a str """ return f'{base_word}{separator}{postpend}'
bigcode/self-oss-instruct-sc2-concepts
def uniform(n: int) -> tuple: """ Return a Uniform(n) distribution as a tuple. """ return (1.0 / n, ) * n
bigcode/self-oss-instruct-sc2-concepts
def extended_euclidean_algorithm(a, b): """Extended Euclidean algorithm Returns r, s, t such that r = s*a + t*b and r is gcd(a, b) See <https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm> """ r0, r1 = a, b s0, s1 = 1, 0 t0, t1 = 0, 1 while r1 != 0: q = r0 // r1 ...
bigcode/self-oss-instruct-sc2-concepts
def rotate(text, key): """ Caesar cipher the provided text with the provided key. :param text string - Text to cipher. :param key string - The key to use in the cipher. :return text - ciphered text """ alpha = 'abcdefghijklmnopqrstuvwxyz' out = '' for index, char in enumerate(text):...
bigcode/self-oss-instruct-sc2-concepts
def isoformat(dt): """ Formats a datetime object to an ISO string. Timezone naive datetimes are are treated as UTC Zulu. UTC Zulu is expressed with the proper "Z" ending and not with the "+00:00" offset declaration. :param dt: the :class:`datetime.datetime` to encode :returns: an en...
bigcode/self-oss-instruct-sc2-concepts
def get_region_dir(hparams): """Return brain region string that combines region name and inclusion info. If not subsampling regions, will return :obj:`'all'` If using neural activity from *only* specified region, will return e.g. :obj:`'mctx-single'` If using neural activity from all *but* specified ...
bigcode/self-oss-instruct-sc2-concepts
def _call(partial, *args, **kwargs): """Calls a partial created using `make`. Args: partial: The partial to be called. *args: Additional positional arguments to be appended to the ones given to make. **kwargs: Additional keyword arguments to augment and override the ones ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def from_isoformat(t): """Converts time from ISO-8601 string to datetime object""" return datetime.strptime(t, "%Y-%m-%dT%H:%M:%S.%f")
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable from typing import Optional import types def copy_definition( definition: Callable, name: Optional[str] = None ) -> Callable: """ Copies a definition with same code, globals, defaults, closure, and name. Parameters ---------- definition Definition to be...
bigcode/self-oss-instruct-sc2-concepts
import itertools def sublists(lst, min_elmts=0, max_elmts=None): """Build a list of all possible sublists of a given list. Restrictions on the length of the sublists can be posed via the min_elmts and max_elmts parameters. All sublists have will have at least min_elmts elements and not more than m...
bigcode/self-oss-instruct-sc2-concepts
import zipfile def create_xml_list_from_zip(filepath): """ Opens the .zip file and extracts a list of .xml filenames :param filepath: filepath to the .zip file :return: list of .xml filenames """ return list(filter(lambda x: x[-3:] == 'xml', zipfile.ZipFile(filepath, 'r').namelist()))
bigcode/self-oss-instruct-sc2-concepts
import re def extractIdentifierFromFullURL(url): """Extracts just the PID from a full URL. Handles URLs on v1 or v2 and meta/object/resolve/etc endpoints. Arguments: url : str Returns: None if no match. Otherwise returns the identifier as a string. """ if not isinstance(url, str): ...
bigcode/self-oss-instruct-sc2-concepts
def find_length_from_labels(labels, label_to_ix): """ find length of unpadded features based on labels """ end_position = len(labels) - 1 for position, label in enumerate(labels): if label == label_to_ix['<pad>']: end_position = position break return end_position
bigcode/self-oss-instruct-sc2-concepts
def fileContents(fn): """ Return the contents of the named file """ return open(fn, 'rb').read()
bigcode/self-oss-instruct-sc2-concepts
def count_elements(seq) -> dict: """Tally elements from `seq`.""" hist = {} for i in seq: hist[i] = hist.get(i, 0) + 1 return hist
bigcode/self-oss-instruct-sc2-concepts
import re def parse_attributes_block_identifier(block): """Return the identifier in `block`. Parameters ========== block : string Block to search in Returns ======= Either: identifier : string If identifier found None If no identifier found...
bigcode/self-oss-instruct-sc2-concepts
import re def find_matching_pattern(List, pattern): """ Return elements of a list of strings that match a pattern and return the first matching group """ reg_pattern=re.compile(pattern) MatchedElements=[] MatchedStrings=[] for l in List: match=reg_pattern.search(l) if m...
bigcode/self-oss-instruct-sc2-concepts
def get_total(taxa_list, delim): """Return the total abundance in the taxa list. This is not the sum b/c taxa lists are trees, implicitly. """ total = 0 for taxon, abund in taxa_list.items(): tkns = taxon.split(delim) if len(tkns) == 1: total += abund return total
bigcode/self-oss-instruct-sc2-concepts
import re def punctuation_density(text, punctuation=r'[^\w\s]'): """Returns the punctuation density of the given text. Arguments: text (str): The input text. punctuation (str): A regex pattern for matching punctuation characters. Defaults to r'[,.!?:;\\/]'. Returns: (f...
bigcode/self-oss-instruct-sc2-concepts
def create_subparser(subparsers): """Creates this module's subparser. Args: subparsers: Special handle object (argparse._SubParsersAction) which can be used to add subparsers to a parser. Returns: Object representing the created subparser. """ parser = subparsers.add_pa...
bigcode/self-oss-instruct-sc2-concepts
def validate(message): """ Check if the message is in the correct format. """ if not ('x' in message and 'y' in message): return False if not(isinstance(message['x'], float)) or not(isinstance(message['y'], float)): return False return True
bigcode/self-oss-instruct-sc2-concepts
def linearize(solution): """Converts a level-ordered solution into a linear solution""" linear_solution = [] for section in solution[0]: for operation in section: if not (operation.op[0] == 'P' and operation.op[1].isupper()): linear_solution.append(operation) return...
bigcode/self-oss-instruct-sc2-concepts
def option_to_cblas(x): """As above, but for CBLAS data-types""" return { 'layout': "CBLAS_ORDER", 'a_transpose': "CBLAS_TRANSPOSE", 'b_transpose': "CBLAS_TRANSPOSE", 'ab_transpose': "CBLAS_TRANSPOSE", 'side': "CBLAS_SIDE", 'triangle': "CBLAS_UPLO", 'diago...
bigcode/self-oss-instruct-sc2-concepts
def get_remote_name(spec): """ Return the value to use for the "remote_name" parameter. """ if spec.mitogen_mask_remote_name(): return 'ansible' return None
bigcode/self-oss-instruct-sc2-concepts
def _is_module(pkg): """ Is this a module pacakge. Eg. foo-1-2.module+el8.1.0+2940+f62455ee.noarch or for el9: foo-1-2.module_el9+96+b062886b """ return '.module+' in pkg.release or '.module_' in pkg.release
bigcode/self-oss-instruct-sc2-concepts
def arg_hex2int(v): """ Parse integers that can be written in decimal or hex when written with 0xXXXX. """ return int(v, 0)
bigcode/self-oss-instruct-sc2-concepts
import math def Urms_calc(ua,ub,uc): """Function to calculate rms value of scalar phasor quantities.""" return math.sqrt((pow(abs(ua),2)+pow(abs(ub),2)+pow(abs(uc),2))/3.0)/math.sqrt(2)
bigcode/self-oss-instruct-sc2-concepts
import csv def load_log(filename): """ Load the contents of a single log file. """ time = [] code = [] mesg = [] with open(filename, "r") as csvfile: reader = csv.reader(csvfile) for t, c, m in reader: time.append(float(t)) code.append(int(c)) ...
bigcode/self-oss-instruct-sc2-concepts
def is_junk(c): """ Return True if string `c` is a junk copyright that cannot be resolved otherwise by the parsing. It would be best not to have to resort to this, but this is practical. """ junk = set([ 'copyrighted by their authors', 'copyrighted by their authors.', 'co...
bigcode/self-oss-instruct-sc2-concepts
def readval(file, ty): """Reads a line from file with an item of type ty :param file: input stream, for example sys.stdin :param ty: a type, for example int :returns: an element of type ty """ return ty(file.readline())
bigcode/self-oss-instruct-sc2-concepts
import jinja2 def render_template(template_body: str, **template_vars) -> str: """render a template with jinja""" if template_vars: template_body = jinja2.Template(template_body).render(**template_vars) return template_body
bigcode/self-oss-instruct-sc2-concepts
def formatter_str(formatstr): """ Creates a formatter function from format string, i.e. '%s, %s' etc :param formatstr: The formatting string :return: Formatter function using formatstr """ return lambda item: formatstr % item
bigcode/self-oss-instruct-sc2-concepts
import requests import hashlib def get_hash(resource_url): """ Access the URL provided and calculate an MD5 hash of whatever is returned. Throw an exception, if the URL is not accessible. """ req = requests.get(resource_url, stream=True) m = hashlib.md5() for chunk in req.iter_content(chunk_si...
bigcode/self-oss-instruct-sc2-concepts
def line_strip(line): """ Remove comments and replace commas from input text for a free formatted modflow input file Parameters ---------- line : str a line of text from a modflow input file Returns ------- str : line with comments removed and commas replaced ...
bigcode/self-oss-instruct-sc2-concepts
def _merge(left, right): """ Function merges left and right parts Args: left: left part of array right: right part of array Returns: Sorted and merged left + right parts """ merge_result = [] i = 0 j = 0 while i < len(left) and j < len(right): if lef...
bigcode/self-oss-instruct-sc2-concepts
def _get_input_output_names(onnx_model): """ Return input and output names of the ONNX graph. """ input_names = [input.name for input in onnx_model.graph.input] output_names = [output.name for output in onnx_model.graph.output] assert len(input_names) >= 1, "number of inputs should be at least 1...
bigcode/self-oss-instruct-sc2-concepts
def read_lines(file_path): """ read file as a list of lines """ with open(file_path) as f: return [l.strip() for l in f.readlines()]
bigcode/self-oss-instruct-sc2-concepts
def convert_red(string): """Return red text""" return f"{string}"
bigcode/self-oss-instruct-sc2-concepts
def _h_3ab(P): """Define the boundary between Region 3a-3b, h=f(P) >>> "%.6f" % _h_3ab(25) '2095.936454' """ return 0.201464004206875e4+3.74696550136983*P-0.0219921901054187*P**2+0.875131686009950e-4*P**3
bigcode/self-oss-instruct-sc2-concepts
def fnorm(f, normalization): """ Normalize the frequency spectrum.""" return f / normalization
bigcode/self-oss-instruct-sc2-concepts
def neighbours( x, y, world ): """ Získá počet sousedů dané buňky. Parametry: x (int) X-ová souřadnice y (int) Y-ová souřadnice world (list) 2D pole s aktuálním stavem. Vrací: int Počet sousedů buňky na souřadnicích [x;y] """ # Počet sousedů ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict def remap_list(target_list: List[int], mapping: Dict[int, int]) -> List[int]: """ Take a list of atom indices and remap them using the given mapping. """ return [mapping[x] for x in target_list]
bigcode/self-oss-instruct-sc2-concepts
import ast from typing import Optional from typing import List def read_object_name(node: ast.AST, name: Optional[List[str]] = None) -> str: """Parse the object's (class or function) name from the right-hand size of an assignement nameession. The parsing is done recursively to recover the full import pat...
bigcode/self-oss-instruct-sc2-concepts
import re def get_one_match(expr, lines): """ Must be only one match, otherwise result is None. When there is a match, strip leading "[" and trailing "]" """ # member names in the ld_headers output are between square brackets expr = rf'\[({expr})\]' matches = list(filter(None, (re.search(e...
bigcode/self-oss-instruct-sc2-concepts
import json def _get_synset_labels(filepath: str) -> dict: """ Gets synsets from json file in a dict Args: filepath: json file path Returns: Dict having the following structure: {str id : (int synset_ID, str label_name )} """ with open(filepath, "r") as f: ra...
bigcode/self-oss-instruct-sc2-concepts
def is_cap(word: str) -> bool: """Return True if the word is capitalized, i.e. starts with an uppercase character and is otherwise lowercase""" return word[0].isupper() and (len(word) == 1 or word[1:].islower())
bigcode/self-oss-instruct-sc2-concepts
def get_depth(od): """Function to determine the depth of a nested dictionary. Parameters: od (dict): dictionary or dictionary-like object Returns: int: max depth of dictionary """ if isinstance(od, dict): return 1 + (max(map(get_depth, od.values())) if od else 0) return...
bigcode/self-oss-instruct-sc2-concepts
def add_dicts_by_key(in_dict1, in_dict2): """ Combines two dictionaries and adds the values for those keys that are shared """ both = {} for key1 in in_dict1: for key2 in in_dict2: if key1 == key2: both[key1] = in_dict1[key1] + in_dict2[key2] return both
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_output_stem(attributes): """Get output file stem, specific to HYPE.""" short_to_stem = dict(tas="Tobs", tasmin="TMINobs", tasmax="TMAXobs", pr="Pobs") shortname = attributes["short_name"] if sh...
bigcode/self-oss-instruct-sc2-concepts
from typing import Collection from typing import Optional def max_offset(offsets: "Collection[Optional[str]]") -> "Optional[str]": """ Return the most "recent" offset from a collection of offsets. :param offsets: A collection of offsets to examine. :return: The largest offset, or ``None`` if unknown....
bigcode/self-oss-instruct-sc2-concepts
def calculate_distance(P1, P2): """Calculates the distance of given points (1D to infinity-D).""" if len(P1) != len(P2): raise ValueError('Different dimension of given points.') square_sum = 0 for i in range(len(P1)): square_sum += (P1[i] - P2[i])**2 return square_sum**(1 / 2)
bigcode/self-oss-instruct-sc2-concepts
def chunk_it(seq, num): """Split a sequence in a 'num' sequence of ~same size """ avg = len(seq) / float(num) out = [] last = 0.0 while last < len(seq): out.append(seq[int(last):int(last + avg)]) last += avg return sorted(out, reverse=True)
bigcode/self-oss-instruct-sc2-concepts
def _ensure_unix_line_endings(path): """Replace windows line endings with Unix. Return path to modified file.""" out_path = path + "_unix" with open(path) as inputfile: with open(out_path, "w") as outputfile: for line in inputfile: outputfile.write(line.replace("\r\n", "...
bigcode/self-oss-instruct-sc2-concepts
def cut_off_ringing(k, P, ir_cutoff=5e-5, uv_cutoff=1e2): """ Cut off ringing tail at high and low k Parameters ---------- k: 1d numpy array Note does not need to be ln-space P: 1d numpy array Function evaluated at corresponding k """ if ir_cutoff < k.min(): ir_cutoff = k.min() if uv_cutoff > k.max(): uv_...
bigcode/self-oss-instruct-sc2-concepts
def grab_value_from_file(filename): """ Return the value from the first line of a file. """ return open(filename, 'r').readline().strip().split()[0]
bigcode/self-oss-instruct-sc2-concepts
import ipaddress def is_ipv4_address(ip_address): """ Checks if given ip is ipv4 :param ip_address: str ipv4 :return: bool """ try: ipaddress.IPv4Address(ip_address) return True except ipaddress.AddressValueError as err: return False
bigcode/self-oss-instruct-sc2-concepts
def _is_kanji(char): """ Check if given character is a Kanji. """ return ord("\u4e00") < ord(char) < ord("\u9fff")
bigcode/self-oss-instruct-sc2-concepts
def multiline_input(prompt): """Prompt for multiline input""" lines=[] print(prompt+" (input will end after entering a blank line) : >") while True: line=input() if not line.strip(): break else: lines.append(line) return "\n".join(lines)
bigcode/self-oss-instruct-sc2-concepts
def fatorial(numero=1, show=False): """ -> Calcula o Fatorial de um número. :param numero: O número a ser calculado. :param show: (opcional) Mostrar ou não a conta. :return: O valor do Fatorial de um número n. """ fat = 1 ext = '' for i in range(numero, 0, -1): ...
bigcode/self-oss-instruct-sc2-concepts
def test_add_to_registry( CallableRegistry, # noqa: N803 PropertyRegistry, CachedPropertyRegistry, CallableParamRegistry, PropertyParamRegistry, CachedPropertyParamRegistry, ): """A member can be added to registries and accessed as per registry settings.""" @CallableRegistry.registry()...
bigcode/self-oss-instruct-sc2-concepts
def loss(y, ybar, sparm): """Loss is 1 if the labels are different, 0 if they are the same.""" return 100.0*int(y != ybar)
bigcode/self-oss-instruct-sc2-concepts
def flat_correct(ccd, flat, min_value=None, norm_value=None): """Correct the image for flat fielding. The flat field image is normalized by its mean or a user-supplied value before flat correcting. Parameters ---------- ccd : `~astropy.nddata.CCDData` Data to be transformed. flat ...
bigcode/self-oss-instruct-sc2-concepts
def format_response_data(sparkl_response): """ Builds easy-access object from response data sent back by SPARKL. """ # Get name of response/reply and list of output fields try: response_name = sparkl_response['attr']['name'] fields_data_list = sparkl_response['content'] # Retur...
bigcode/self-oss-instruct-sc2-concepts
def coding_problem_12(budget, choices): """ There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters. For example, if N is 4, then there are 5 un...
bigcode/self-oss-instruct-sc2-concepts