seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def osr_proj(input_osr):
"""Return the projection WKT of a spatial reference object
Args:
input_osr (:class:`osr.SpatialReference`): the input OSR
spatial reference
Returns:
WKT: :class:`osr.SpatialReference` in WKT format
"""
return input_osr.ExportToWkt() | bigcode/self-oss-instruct-sc2-concepts |
def day_lags(lags):
"""Translate day lags into 15-minute lags"""
return [l * 96 for l in lags] | bigcode/self-oss-instruct-sc2-concepts |
def deg2dmm(degrees: float, latlon: str) -> str:
"""
Convert decimal degrees to degrees decimal minutes string.
:param float degrees: degrees
:param str latlon: "lat" or "lon"
:return: degrees as dm.m formatted string
:rtype: str
"""
if not isinstance(degrees, (float, int)):
r... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def log_interpolate(log_a, log_b, alpha_logit):
"""Numerically stable implementation of log(alpha * a + (1-alpha) * b)."""
log_alpha = -torch.nn.functional.softplus(torch.tensor(-alpha_logit))
log_1_minus_alpha = -torch.nn.functional.softplus(torch.tensor(alpha_logit))
y = torch.logsumexp... | bigcode/self-oss-instruct-sc2-concepts |
def _get_deterministic_value_for_table_name(table_name, max_value):
"""
For a given table_name, returns hash of the table_name limited by max_value.
"""
return hash(table_name) % max_value | bigcode/self-oss-instruct-sc2-concepts |
def one_of_k_encoding_unk(x, allowable_set):
"""
taken from https://github.com/thinng/GraphDTA
function which one hot encodes x w.r.t. allowable_set with one bit reserved for elements not in allowable_set
x:
element from allowable_set
allowable_set: list
list of all known elements
... | bigcode/self-oss-instruct-sc2-concepts |
def _subtract_intervals(x, y):
"""Set difference for lists of intervals. That is, returns a list of
intervals that bounds all values bounded by x that are not also bounded by
y. x and y are expected to be in sorted order.
For example _subtract_intervals([(1, 10)], [(2, 3), (9, 15)]) would
return [(... | bigcode/self-oss-instruct-sc2-concepts |
def _normalize_version_number(version):
"""Turn a version representation into a tuple."""
# trim the v from a 'v2.0' or similar
try:
version = version.lstrip('v')
except AttributeError:
pass
# if it's an integer or a numeric as a string then normalize it
# to a string, this ens... | bigcode/self-oss-instruct-sc2-concepts |
def sum(a, b):
"""Compute the sum of two numbers, a and b"""
return a + b | bigcode/self-oss-instruct-sc2-concepts |
def is_iterable(value, include_maps=False, include_sets=True):
"""Returns whether value is iterable.
``include_maps``
Maps are technically iterable, defaulting to their keys, but you
commonly want to find if it is a list-like type and leave maps alone,
so this is False by default.
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def grid_cell_to_xy(pos: int, grid_size: int = 5) -> Tuple[int, int]:
"""Converts an integer from 0-24 into an (x, y) position."""
num_cells = grid_size * grid_size - 1
if not 0 <= pos <= num_cells:
raise ValueError(f'Grid cell does not exist in grid of size {grid_size}')
x = pos ... | bigcode/self-oss-instruct-sc2-concepts |
def predict_tf_lite(model, image):
"""
TFLite model prediction (forward propagate)
:param model: TFLite interpreter
:param image: Input image
:return: Numpy array with logits
"""
input_details = model.get_input_details()
output_details = model.get_output_details()
model.set_tensor(in... | bigcode/self-oss-instruct-sc2-concepts |
def out_features(model):
"""Try to extract number of output features from the last layer of a
model. This is often useful when building encoder-decoder models or
stacking encoders and classification heads. Not sure how airtight the
logic is here so use with caution.
Parameters
----------
mo... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def _get_metadata(tokens):
"""Find and parse metadata (if present)."""
for token in tokens:
if token.type == "front_matter":
return yaml.safe_load(token.content)
return {} | bigcode/self-oss-instruct-sc2-concepts |
def elem_apply(fns, elems):
"""apply list of functions to list of elements,
element-wise"""
return map(lambda a, b: a(b), fns, elems) | bigcode/self-oss-instruct-sc2-concepts |
import re
def KCamelToShouty(s):
"""Convert |s| from kCamelCase or CamelCase to SHOUTY_CASE.
kFooBar -> FOO_BAR
FooBar -> FOO_BAR
FooBAR9 -> FOO_BAR9
FooBARBaz -> FOO_BAR_BAZ
"""
if not re.match(r'^k?([A-Z][^A-Z]+|[A-Z0-9]+)+$', s):
return s
# Strip the leading k.
s = re.sub(r'^k', '', s)
# A... | bigcode/self-oss-instruct-sc2-concepts |
def merge_slow_csv_and_eddypro(stationName,slow_df,eddy_df, mergedCsvOutDir):
"""Merge slow data and EddyPro data DataFrames
Parameters
----------
stationName: name of the station
slow_df: pandas DataFrame that contains all slow variables for the entire
measurement period
eddy_df: panda... | bigcode/self-oss-instruct-sc2-concepts |
def merge_fast_two(one, two):
""" Merge two dictionaries performantly into an instance of “dict”.
Based on this extremely beloved SO answer:
https://stackoverflow.com/a/26853961/298171
"""
# N.B. the dict-expanded operands appear here in the opposite order
# from their posit... | bigcode/self-oss-instruct-sc2-concepts |
def transform_y(f_x_y, xf_and_dxf_dyprime):
"""Transform f_x_y(x,y) into f_x_yprime(x,yprime)
xf is the inverse transformation: from yprime to y
y = xf(yprime, *xf_params)
dxf_dyprime is its derivative with respect to yprime"""
def f_x_yprime(x,yprime,p):
xf, dxf_dyprime = xf_and_dxf_dyprime(yprime, p)
return ... | bigcode/self-oss-instruct-sc2-concepts |
def get_all_env_names(envs):
"""Returns set of all env names from envs."""
result = set()
for e in envs.values():
result.update(e.keys())
return result | bigcode/self-oss-instruct-sc2-concepts |
def compute_optimal_action_with_environment_dynamics(
observation, environment_dynamics):
"""Computes the optimal action using the environment dynamics.
Args:
observation: a (possibly batched) observation.
environment_dynamics: environment dynamics object (an instance of
`non_stationary_stochasti... | bigcode/self-oss-instruct-sc2-concepts |
import struct
def pack_long(l) :
"""pack_long(l)
returns big-endian representation of unsigned long integer"""
arr = []
while l > 0 :
arr.insert(0, struct.pack("B", l & 0xff))
l >>= 8
return ''.join(arr) | bigcode/self-oss-instruct-sc2-concepts |
def create_hash(key, size): # O(1)
"""
Creates a hash by taking the first character in a string, getting its
ASCII value and apply a modular function to the provided size
>>> create_hash(42, 5)
4
>>> create_hash(42, 4)
0
>>> create_hash(122.12, 4)... | bigcode/self-oss-instruct-sc2-concepts |
def hamming(s, t):
"""
Calculate the Hamming distance between two strings. From Wikipedia article: Iterative with two matrix rows.
:param s: string 1
:type s: str
:param t: string 2
:type s: str
:return: Hamming distance
:rtype: float
"""
if len(s) != len(t):
raise Value... | bigcode/self-oss-instruct-sc2-concepts |
def getStr(bytes_arr):
"""Create string from ASCIIZ string buffer"""
strng = ""
for value in bytes_arr:
if value != 0:
strng = strng + chr(value)
else:
break
return strng | bigcode/self-oss-instruct-sc2-concepts |
def modulo11(base):
"""Calcula o dígito verificador (DV) para o argumento usando "Módulo 11".
:param str base: String contendo os dígitos sobre os quais o DV será
calculado, assumindo que o DV não está incluído no argumento.
:return: O dígito verificador calculado.
:rtype: int
"""
pes... | bigcode/self-oss-instruct-sc2-concepts |
def get_parse_dates(file):
"""Return a list of columns for which dates have to be parsed."""
parse_dates = [
'click_time',
'attributed_time'
]
if 'test' in file:
parse_dates.remove('attributed_time')
return parse_dates | bigcode/self-oss-instruct-sc2-concepts |
def huffman_decoding(data, root):
"""Decodes data using Huffman Coding compression algorithm.
Args:
data: A str in binary to be encoded using the provided Huffman Tree
root: A HuffmanNode object representing the root node of a Huffman Tree
to be used to decode the provided data
... | bigcode/self-oss-instruct-sc2-concepts |
def force_column(arr):
"""Turns 1d numpy array into an (N, 1) shaped column"""
return arr.reshape((len(arr), 1)) | bigcode/self-oss-instruct-sc2-concepts |
import re
def dict_from_regex_match(pattern, input_, type_dispatcher=None):
"""Return a dict from matching `pattern` to `input_`.
If match failed, returns None.
Parameters
----------
pattern : str, `re.Pattern`
The regex that matches to the `input_`.
input_ : str
The string ... | bigcode/self-oss-instruct-sc2-concepts |
def getUserUpdateTuple(user):
"""
Converts a user object to a tuple that can be given to an SQL update query
@param user: The user object
@return: The tuple of values
"""
tuple = (
user.name,
user.telegram_firstName,
user.expectedMessageType,
str(user.tempParams),
user.wantsMenu,
user.course,
user.w... | bigcode/self-oss-instruct-sc2-concepts |
def param_dict_from_output(output_line):
"""
Generate a parameter dictionary with enough variables to correctly estimate the rates of
reactions.
:param output_line: (pandas series) any row from the relevant UCLCHEM output
"""
param_dict={
"initialDens":output_line["Density"],
"initialTemp":output_line["gasT... | bigcode/self-oss-instruct-sc2-concepts |
import codecs
def output(counter, top_n=None, output_counts=True):
"""Prints a counter with optional formatting
:param counter: A Counter object to print
:param top_n: The top N most common terms to print (default print all)
:param output_counts: If true, prints term followed by count, separated by ta... | bigcode/self-oss-instruct-sc2-concepts |
import math
def binary_search(t, x, start, end):
"""Find the index i of t with t[i] <= x <= t[i+1].
Under the assumption that t is nondecreasing t[j] <= t[j+1]."""
mid = math.floor((start + end) / 2)
if ((start - end) == 0) or ((t[mid] <= x) and (x < t[mid+1])):
return mid
elif t[mid] <= x... | bigcode/self-oss-instruct-sc2-concepts |
def validator(value):
""" Trivial validator. """
return value | bigcode/self-oss-instruct-sc2-concepts |
def _xcom_pull(task, key="return_value"):
"""Generates a Jinja template that pulls an XCom variable for a task.
XCom allows data to be shared between different tasks.
Args:
task: The task instance.
key: The XCom key to retrieve the value for. (default: return_value)
Returns:
The Jinja template re... | bigcode/self-oss-instruct-sc2-concepts |
def get_objects(resource, bucket_name, prefix=""):
"""List objects inside a bucket"""
client = resource.meta.client
next_token = ""
content = []
directory = []
add_list = lambda keys, values: keys.extend(values) if values is not None else None
while True:
response = client.list_obje... | bigcode/self-oss-instruct-sc2-concepts |
def echo(value):
"""
Returns the given argument.
:param value: argument to be returned
:return: the given argument
>>> echo(0)
0
>>> [echo(x) for x in range(3)]
[0, 1, 2]
"""
return value | bigcode/self-oss-instruct-sc2-concepts |
def update_chr_prefix(regions, mode='remove'):
"""
Add or remove the (annoying) 'chr' string from specified regions.
The method will automatically detect regions that don't need to be
updated and will return them unchanged.
Parameters
----------
regions : str or list
One or more re... | bigcode/self-oss-instruct-sc2-concepts |
import json
import random
def get_random_user(in_file):
""" Open up user input json and grab a random user from the specified users """
with open(in_file) as data_file:
data = json.load(data_file)
users = data["dm_users"]
return random.choice(users) | bigcode/self-oss-instruct-sc2-concepts |
from math import floor, ceil
def truncate(value, args='10'):
"""
Truncates a string after a certain number of characters.
final_len: Number of characters the final returned value should be,
after the truncate and string is concatenated.
str: the string that will be concatenated to the truncated ... | bigcode/self-oss-instruct-sc2-concepts |
def getVersionString(plist, key=None):
"""Gets a version string from the plist.
If a key is explictly specified, the value of that key is
returned without modification, or an empty string if the
key does not exist.
If key is not specified:
if there's a valid CFBundleShortVersionString, returns... | bigcode/self-oss-instruct-sc2-concepts |
def hexdump(data, saddr=0, compress=True, length=16, sep='.'):
""" Return string array in hex dump.format
:param data: {List} The data array of {Bytes}
:param saddr: {Int} Absolute Start Address
:param compress: {Bool} Compressed output (remove duplicated content, rows)
:param length: {Int... | bigcode/self-oss-instruct-sc2-concepts |
def ans_entity_full(ner_tag, new_ans):
"""Returns a function that yields new_ans iff every token has |ner_tag|."""
def func(a, tokens, q, **kwargs):
for t in tokens:
if t['ner'] != ner_tag: return None
return new_ans
return func | bigcode/self-oss-instruct-sc2-concepts |
def split_df(df, split_col, split_vals):
"""
takes a data frame and splits is according to the values in the specified column, the number of returned data frames
will be equal to the number of passed split values
:param df: the data frame that shall be splitted
:param split_col: defines the column b... | bigcode/self-oss-instruct-sc2-concepts |
import configparser
from pathlib import Path
def get_version() -> str:
"""
Gets the current version from the setup.cfg file
"""
config = configparser.ConfigParser()
path = Path(__file__).parent.parent / "setup.cfg"
config.read(path)
return str(config["metadata"]["version"]) | bigcode/self-oss-instruct-sc2-concepts |
def present(span):
"""Accepts a spaCy Span and returns True if the text contains non-whitespace characters."""
return span and span.text.strip() | bigcode/self-oss-instruct-sc2-concepts |
def template_function(message: str, show: bool = True) -> str:
"""Return a message if `show` is True.
Args:
message (str): The message to be returned.
show (bool): Flag to return the message.
Return:
The message. Is show is True, empty string otherwise.
"""
return message ... | bigcode/self-oss-instruct-sc2-concepts |
def isiterable(obj):
"""
Test if the argument is an iterable.
:param obj: Object
:type obj: any
:rtype: boolean
"""
try:
iter(obj)
except TypeError:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def flatten(nested_list: list) -> list:
"""
Flatten an input list which could have a hierarchical multi nested list
:param nested_list: The source list
:return: The flatten list
"""
if len(nested_list) == 0:
return []
if type(nested_list[0]) is list:
return flatten(nested_lis... | bigcode/self-oss-instruct-sc2-concepts |
def build_object_spec(client_factory, root_folder, traversal_specs):
"""Builds the object Spec.
:param client_factory: Factory to get API input specs
:param root_folder: Root folder reference as the starting point for
traversal
:param traversal_specs: filter specs required for t... | bigcode/self-oss-instruct-sc2-concepts |
def get_filenames_and_urls(url_df, method_list=None, organ_list=None):
"""Takes in dataframe and returns corresponding filename(s) and url(s).
Takes in dataframe (with sample information stored), a list of methods,
and a list of organs.
Returns filenames and figshare URLs associated with inputs.
If... | bigcode/self-oss-instruct-sc2-concepts |
def remSpecialChar(text):
"""removes special LaTeX/BibTeX characters from a string"""
text = text.replace("{","").replace("}","")
text = text.replace("\\","")
text = text.replace("&","")
return text | bigcode/self-oss-instruct-sc2-concepts |
def read_file(filename: str) -> bytes:
"""
Opens a file, reads its contents as bytes, and returns it.
:param filename: A filename
:return: The bytes in the file
:raises IOError: upon failure
"""
with open(filename, 'rb') as file:
return file.read() | bigcode/self-oss-instruct-sc2-concepts |
import json
def get_owner_ids(json_filename):
"""Return a set with all the owner IDs in posts from ‘json_filename’."""
with open(json_filename, 'r', newline='') as json_file:
owner_ids = set()
for line in json_file:
json_dict = json.loads(line)['_node']
owner_ids.add(in... | bigcode/self-oss-instruct-sc2-concepts |
def check_word_lengths(start_word, stop_word):
"""Check if the both words are of equal length.
:param start_word: Starting word
:param stop_word: Stopping word
:returns: True if lengths are equal, False otherwise
:rtype: bool
"""
if len(start_word) != len(stop_word):
print("Words {... | bigcode/self-oss-instruct-sc2-concepts |
import timeit
def benchmark_it(func, repeat=3, number=1000):
"""
Benchmark <func> by taking the shortest time of <repeat==3> test runs.
"""
#print(s.ljust(20), end=" ")
res = func()
print(str(func) + ' took {:>5.0f} ms'.format(min(timeit.repeat(func,
r... | bigcode/self-oss-instruct-sc2-concepts |
def dir_Gen(row_num, dataframe):
"""
Gets the directory of the data from the remarks column
"""
row = dataframe.loc[row_num]
directions = row['remarks']
directionsList = [x.strip() for x in directions.split(',')[:-1]]
return directionsList | bigcode/self-oss-instruct-sc2-concepts |
def get_user_id(conn, user_name):
"""Get ID of a user based on user name.
Must be an exact match. Case sensitive.
Parameters
----------
conn : ``omero.gateway.BlitzGateway`` object
OMERO connection.
user_name : str
Name of the user for which an ID is to be returned.
Return... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def shape_str(element_type, shape):
"""Return human-friendly description of array shape."""
dim_0 = "?" if shape[0] in (Any, None) else shape[0]
sub_shape = element_type if len(shape) == 1 else shape_str(element_type, shape[1:])
return "[{0} x {1}]".format(dim_0, sub_shape) | bigcode/self-oss-instruct-sc2-concepts |
def _get_image_and_label_from_entry(entry):
""" Get the image's path and its label from a dataset entry.
Args:
entry: string containing the path to a image and its label.
Return:
file_path: string with the path where a image is stored.
label: int representing the... | bigcode/self-oss-instruct-sc2-concepts |
def format_coords(df, col_to_convert, col_new_name):
"""
Takes col_to_convert and creates a list of a set of strings that
contain coordinates in an integer form.
Parameters
----------
df : df
pd.DataFrame that contains Neotoma information.
col_to_convert : string
Name of co... | bigcode/self-oss-instruct-sc2-concepts |
def find_neighbors(ID, neighboring_matrix):
"""Filters all polygons which are actually neighbors to given polygon.
Args:
ID (int): ID of specific polygon under consideration.
neighboring_matrix (dataframe): output from neighboring_polys().
Returns:
dataframe: dataframe containig ID... | bigcode/self-oss-instruct-sc2-concepts |
import time
def try_with_times(times, interval, sleep_first, logger, tag, func, *args, **kwargs):
"""
Try a function with certain chances and retry intervals
:param times: Amount of chances
:param interval: Interval between retries
:param logger: Logger to log information
:param tag: Tag of th... | bigcode/self-oss-instruct-sc2-concepts |
def camera_to_world_frame(P, R, T):
""" Inverse of world_to_camera_frame
Args
P: Nx3 points in camera coordinates
R: 3x3 Camera rotation matrix
T: 3x1 Camera translation parameters
Returns
X_cam: Nx3 points in world coordinates
"""
assert len(P.shape) == 2
assert P.shap... | bigcode/self-oss-instruct-sc2-concepts |
def enforce_ordered_labels(labels):
"""Transform the label sequence to an ordered form.
This is the same type of label sequence used in the paper "Discriminative
neural clustering for speaker diarisation". This makes the label sequence
permutation invariant.
Args:
labels: an array of integers
Returns... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
from typing import Tuple
def check_letter_in_word(secret_word: str, user_guess: str, current_word: str,
wrong_guesses: List[str]) -> Tuple[str, List[str]]:
"""Check if the user's guess is in the word.
Args:
secret_word (str): The secret word chosen by ... | bigcode/self-oss-instruct-sc2-concepts |
def result_to_str(result):
"""Return a string based on the attributes of the supplied Result.
Usage example:
>>> result_to_str(Result('error', 'nullPointer', 'my.cpp', [1], 'bad'))
'my.cpp (1): (error) nullPointer - bad'
:error: an Result, probably from parse_output()
:returns: a strin... | bigcode/self-oss-instruct-sc2-concepts |
def make_false(unused_value):
"""Makes a False boolean value lambda."""
return False | bigcode/self-oss-instruct-sc2-concepts |
def knot2mph(k):
"""
Converts knots to miles per hour.
"""
if k == None:
return None
return k * 1.15078 | bigcode/self-oss-instruct-sc2-concepts |
import math
def _distance_at_cutoff(variance, similarity_cutoff):
"""Return distance that gives similarity_cutoff for a gaussian kernel with given variance."""
return math.sqrt(
variance * math.log(1.0 / similarity_cutoff)) | bigcode/self-oss-instruct-sc2-concepts |
def round_decimals(dataframe, decimals=3):
"""
Rounds the decimals in teh dataframe to the
given number of decimal places.
:param dataframe: a pandas dataframe with float
values in a column.
:param decimals: an integer
:return: return a dataframe with float values
rounded to 3 decimals.
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Counter
def get_class_weights2(y, smooth_factor=0):
"""
Returns the normalized weights for each class based on the frequencies of the samples
:param smooth_factor: factor that smooths extremely uneven weights
:param y: list of true labels (the labels must be hashable)
:return: d... | bigcode/self-oss-instruct-sc2-concepts |
def thermalcond(x, So, Gb):
"""
Calculate thermal conductivity of wood at moisture content, volumetric
shrinkage, and basic specific gravity.
Example:
k = thermalcond(12, 12.3, 0.54)
Inputs:
x = moisture content, %
So = volumetric shrinkage, Table 4-3, %
Gb = basic s... | bigcode/self-oss-instruct-sc2-concepts |
def single_index_function(index):
"""Creates a function that returns an index for every single wavelength
Arg:
index(complex): the index of refraction to be returned
Returns:
callable: returns the complex index for an argument of any float
"""
get_index = lambda wavelengths: index
... | bigcode/self-oss-instruct-sc2-concepts |
def extract_authors(elem):
"""extract the authors from an xml element
Args:
elem (xml): xml element
Returns:
tuple: containing a dictionary with authors
"""
authors = list(elem)
authors = {"Authors":
", ".join(["{} {}"
.format((((author... | bigcode/self-oss-instruct-sc2-concepts |
def classify_line(features, model, l_encoder=None):
"""
Classifies the features based on the given model.
If a label encoder is specified, it reverses the encoding of the label
:param features: a vector of features
:param model: a Classification Model
:param l_encoder: a LabelEncoder
:return... | bigcode/self-oss-instruct-sc2-concepts |
def rho2_rho1(M1, gamma):
"""Density ratio across a normal shock (eq. 3.53)
:param <float> M1: Mach # before the shock
:param <float> gamma: Specific heat ratio
:return <float> Density ratio r2/r1
"""
n1 = (gamma + 1.0) * M1 ** 2
d1 = 2.0 + (gamma - 1.0) * M1 ** 2
return n1 / d1 | bigcode/self-oss-instruct-sc2-concepts |
import copy
def create_full_dict(param, name_list, fixed_list=["adjust_element2", "adjust_element3"]):
"""
Create full param dict so each item has the same nested dict.
This is for GUI purpose only.
Pamameters
----------
param : dict
all parameters including element
name_list : li... | bigcode/self-oss-instruct-sc2-concepts |
def _echo_value(value):
"""To use when no unit conversion is desired"""
return value | bigcode/self-oss-instruct-sc2-concepts |
def MakeExt( ext ):
"""Returns a file extension, starting with a dot if the given one does not."""
return ( '' if not ext or ext.startswith( '.' ) else '.' ) + ext | bigcode/self-oss-instruct-sc2-concepts |
def isNotBH(q):
"""In : q (state : string)
Out: Boolean
Given a state q, check if non-black-hole,
i.e. not 'BH'.
"""
return (q != 'BH') | bigcode/self-oss-instruct-sc2-concepts |
import unicodedata
def _strip_accents(word):
"""Removes accent from the input word."""
return ''.join(char for char in unicodedata.normalize('NFD', word) if unicodedata.category(char) != 'Mn') | bigcode/self-oss-instruct-sc2-concepts |
def clean_line(str, delimiter):
"""Split a string into 'clean' fields.
str the string to process
delimiter the delimiter string to split 'line' with
Returns a list of 'cleaned' field strings.
Any fields that were initially zero length will be removed.
If a field contains '\n' it isn't... | bigcode/self-oss-instruct-sc2-concepts |
import re
def split_line(line):
""" Split a line
Treat part enclosed by parentheses as a single unit
"""
line = re.sub('\s*=\s*','=',line)
parts = []
for p in re.split(',|\s',line):
part = p.strip()
if len(part)>0:
parts.append(part)
output = []
i = 0
#... | bigcode/self-oss-instruct-sc2-concepts |
def local_indicies(lead_step, child_steps):
"""
Returns a tuple of indices surrounding the lead_step
"""
imin = 0
imax = len(child_steps) - 1
mid = 0
while imin < imax:
mid = (imax + imin)/2
if(child_steps[mid][0] < lead_step):
imin = mid + 1
else:
... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def load_from_yaml(path, verbose=False):
"""
Load python object stored in yaml file.
:param path: file path to load
:param verbose:
:return: loaded object
"""
with open(path, 'r') as f:
if verbose:
print("Loading data from '" + path + "'")
return yam... | bigcode/self-oss-instruct-sc2-concepts |
def split_and_prune_lines(lines):
"""Split input lines into tokenized lines, suppressing comment
(beginning with hash token) or empty lines.
Tokenization is by whitespace, i.e., with split.
The tokenized lines are returned as tuples rather than lists to
support downstream processing. For instance... | bigcode/self-oss-instruct-sc2-concepts |
def _loc(target):
"""Return target location for constructing commands.
Args:
target: Blaze target name available to this build.
Returns:
$(location target)
"""
return "$(location %s)" % target | bigcode/self-oss-instruct-sc2-concepts |
def _list_display(short_description=None, admin_order_field=None):
"""
Set the short_description and admin_order_field attributes on the decorated
function.
"""
def decorator(f):
if short_description:
f.short_description = short_description
if admin_order_field:
... | bigcode/self-oss-instruct-sc2-concepts |
def ints_to_rgb(r, g=None, b=None):
"""Convert ints in the [0...255] range to the standard [0...1] range.
Parameters:
:r:
The Red component value [0...255]
:g:
The Green component value [0...255]
:b:
The Blue component value [0...255]
Returns:
The color as an (r, g, b) tuple in... | bigcode/self-oss-instruct-sc2-concepts |
def _format_optionals(optionals, extra_optionals):
"""
Formats a list of optional clauses into a string containing
multiple OPTIONALs.
"""
optional_str = ""
if optionals:
for optional in optionals:
optional_str += """OPTIONAL
{{
{}
}}
... | bigcode/self-oss-instruct-sc2-concepts |
def sortbykey(dictlist, sortkey):
"""
Sort a list of dictionaries by a common key and return the sorted list
>>> sortbykey([{'A': 3}, {'A': 1}, {'A': 2}])
[{'A': 1}, {'A': 2}, {'A': 3}]
:param dictlist: a list of dictionaries sharing a common key
:param sortkey: a dictionary key used t... | bigcode/self-oss-instruct-sc2-concepts |
def venv(request):
"""Fixture for --venv."""
return request.config.getoption("--venv") | bigcode/self-oss-instruct-sc2-concepts |
def slice_geo_data(ld):
"""given a list of raw record dictionaries, pull out geo data,
and convert to floats
"""
float_fields = ["latitude","longitude"]
result = []
for rec in ld:
newr = {}
for field in float_fields:
newr[field] = float(rec[field])
result.app... | bigcode/self-oss-instruct-sc2-concepts |
def missing_edges(x,y):
"""
Counts edges that are present in the original structure (x) but
are missing in the learned structure (y). (lower is better)
"""
missing = 0
for rv in x.nodes():
if not y.has_node(rv):
missing += x.degree(rv)
else:
for child in x.children(rv):
if child not in y.children(rv... | bigcode/self-oss-instruct-sc2-concepts |
def constraint_adjacent(m, n) :
"""Returns True if m and n are adjacent, otherwise False.
Assume m and n are ints."""
if abs(m-n) == 1:
return True
else:
return False
raise NotImplementedError | bigcode/self-oss-instruct-sc2-concepts |
from bs4 import BeautifulSoup
def parse_html_for_quotes(html):
""" Parse html for quote pattern, return list of quotes that match """
soup = BeautifulSoup(html, features='html.parser')
quotes = soup.find_all('li')
return [str(q) for q in quotes if '<ul>' in str(q)] | bigcode/self-oss-instruct-sc2-concepts |
def bin2str(b):
"""
Binary to string.
"""
ret = []
for pos in range(0, len(b), 8):
ret.append(chr(int(b[pos:pos + 8], 2)))
return ''.join(ret) | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
from operator import mul
def accumulating_product_reduce(items):
"""Calculate the accumulating product of a list.
Uses functools.reduce.
Arguments:
items {[list]} -- List of numbers.
Returns:
[list] -- List of accumulating products.
"""
return [... | bigcode/self-oss-instruct-sc2-concepts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.