seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import math
def RE(bigramprob, token2p, token1p):
"""Returns the Relative Entropy.
Relative entropy is P1*log2(P1/P2) where here P1 is P(rightword)
and P2 is P(right word | left word)."""
return token1p * math.log(token1p/(bigramprob/token2p), 2) | bigcode/self-oss-instruct-sc2-concepts |
def spread(spread_factor: int, N: int, n: int) -> float:
"""Spread the numbers
For example, when we have N = 8, n = 0, 1, ..., 7, N,
we can have fractions of form n / N with equal distances between them:
0/8, 1/8, 2/8, ..., 7/8, 8/8
Sometimes it's desirable to transform such sequence with finer st... | bigcode/self-oss-instruct-sc2-concepts |
def count_inversion(sequence):
"""
Count inversions in a sequence of numbers
"""
s = list(sequence)
a = 0
b = True
while b:
b = False
for i in range(1, len(s)):
if s[i-1] > s[i]:
s[i], s[i-1] = s[i-1], s[i]
a += 1
... | bigcode/self-oss-instruct-sc2-concepts |
def _ParsePlusMinusList(value):
"""Parse a string containing a series of plus/minuse values.
Strings are seprated by whitespace, comma and/or semi-colon.
Example:
value = "one +two -three"
plus = ['one', 'two']
minus = ['three']
Args:
value: string containing unparsed plus minus values.
Re... | bigcode/self-oss-instruct-sc2-concepts |
def load_id01_monitor(logfile, scan_number):
"""
Load the default monitor for a dataset measured at ID01.
:param logfile: Silx SpecFile object containing the information about the scan and
image numbers
:param scan_number: the scan number to load
:return: the default monitor values
"""
... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def time_delta(t1, t2):
"""
Takes two datetime strings in the
following format :
Sun 10 May 2015 13:54:36 -0700
and returns the time difference in
seconds between them.
Parameters
----------
t1, t2 : string
Input two timestamps to compute
... | bigcode/self-oss-instruct-sc2-concepts |
import json
import base64
def get_key(path):
"""
This is to retrieve a stored key and username combination to access the EPC API.
These values are stored in a JSON file in a local directory and hidden by the .gitignore to avoid
making these public. The key is then encoded as per the EPC documentation.... | bigcode/self-oss-instruct-sc2-concepts |
def _get_edge_length_in_direction(curr_i: int, curr_j: int, dir_i: int, dir_j: int, i_rows: int, i_cols: int,
edge_pixels: set) -> int:
"""
find the maximum length of a move in the given direction along the perimeter of the image
:param curr_i: current row index
:param ... | bigcode/self-oss-instruct-sc2-concepts |
def __model_forward_pass__(args, model, obs_traj_seq, pred_traj_len, seq_start_end, metadata, curr_sample, model_fun):
"""
Wrapper call to the model forward pass, which depending on the exact model, may require different kinds of input
:param args: command line arguments that contain several parameters to c... | bigcode/self-oss-instruct-sc2-concepts |
def check_database(con, dbname):
"""Check a database exists in a given connection"""
cur = con.cursor()
sql = """SELECT 0 FROM pg_database WHERE datname = '%s'"""
cur.execute(sql % dbname)
result = cur.fetchall()
if result:
return(True)
else:
return(False) | bigcode/self-oss-instruct-sc2-concepts |
import math
def _circle_loss(labels,
scores,
rank_discount_form=None,
gamma=64.,
margin=0.25):
"""Returns the circle loss given the loss form.
Args:
labels: A list of graded relevance.
scores: A list of item ranking scores.
rank_disc... | bigcode/self-oss-instruct-sc2-concepts |
def get_filename_with_dead_code_stats(hist_repo, repo_to_measure):
"""Get the filename that contains dead code statistic."""
return "repositories/{repo}/dashboard/{repo_to_measure}.dead_code.txt".format(
repo=hist_repo, repo_to_measure=repo_to_measure) | bigcode/self-oss-instruct-sc2-concepts |
def sort_work(params, priority):
"""
Returns a dictionary as params but ordered by score
Input:
params = dictionary of the form {input_name : value}
priority = the list of input_name ordered by score calculated by score_function
Output:
sorted_dict = the same dictionary as params b... | bigcode/self-oss-instruct-sc2-concepts |
import re
def camelize(string, uppercase_first_letter=True):
"""
Convert strings to CamelCase.
From inflection package: https://github.com/jpvanhal/inflection
Examples::
>>> camelize("device_type")
'DeviceType'
>>> camelize("device_type", False)
'deviceType'
"""
if not strin... | bigcode/self-oss-instruct-sc2-concepts |
import time
def time_to_call_it_a_day(settings, start_time):
"""Have we exceeded our timeout?"""
if settings.timeout <= 0:
return False
return time.time() >= start_time + settings.timeout | bigcode/self-oss-instruct-sc2-concepts |
def _convert_change_list_to_new_query_json(inp_json, change_list):
"""
As the json for the new query would be very similar to the json of the
requested query, the oversights only return a list of changes to
be made in the current json.
This function takes as input the current json, applies the list ... | bigcode/self-oss-instruct-sc2-concepts |
def input_file(tmpdir_factory):
"""Generate a temporary file used for testing the parse_file method."""
rows = [('81 : (1,53.38,€45) (2,88.62,€98) (3,78.48,€3) (4,72.30,€76) '
'(5,30.18,€9) (6,46.34,€48)'), '8 : (1,15.3,€34)',
('75 : (1,85.31,€29) (2,14.55,€74) (3,3.98,€16) (4,26.24,€55... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def datetime_from_qdatedit(qdatedit):
"""
Return the Python datetime object corresponding to the value of
the provided Qt date edit widget.
"""
return datetime(
qdatedit.date().year(),
qdatedit.date().month(),
qdatedit.date().day()) | bigcode/self-oss-instruct-sc2-concepts |
def clean_url(url):
""" Strips the ending / from a URL if it exists.
Parameters
----------
url : string
HTTP URL
Returns
-------
url : string
URL that is stripped of an ending / if it existed
"""
if url[-1] == '/':
return url[:-1]
return url | bigcode/self-oss-instruct-sc2-concepts |
import requests
import json
def call_rest_api(endpoint, query):
"""
Call REST API endpoint
:param endpoint:e.g. 'http://127.0.0.1:9500/wind_deg_to_wind_rose'
:param query: e.g. query = {'wind_deg': wind_deg}
:return:
"""
response = requests.get(endpoint, params=query)
if response.sta... | bigcode/self-oss-instruct-sc2-concepts |
def display_rows(content, message, is_ratio=True):
"""Return content formatted for display to terminal.
keyword args:
content list -- A list of tuples obtained from a SQL query
message string -- A string used as the title of the formatted output
is_ratio boolean -- A boolean used to determine if '%... | bigcode/self-oss-instruct-sc2-concepts |
def _read_file(fname):
"""
Args:
fname (str): Name of the grammar file to be parsed
Return:
list: The grammar rules
"""
with open(fname) as input_file:
re_grammar = [x.strip('\n') for x in input_file.readlines()]
return re_grammar | bigcode/self-oss-instruct-sc2-concepts |
def _clean_col_name(column):
"""Removes special characters from column names
"""
column = str(column).replace(" ", "_").replace("(","").replace(")","").replace("[","").replace("]","")
column = f"[{column}]"
return column | bigcode/self-oss-instruct-sc2-concepts |
def italics(text: str) -> str:
"""Make text to italics."""
return f'_{text}_' | bigcode/self-oss-instruct-sc2-concepts |
import torch
def prepare_batch(batch):
"""This is the collate function
The mass spectra must be padded so that they fit nicely as a tensor.
However, the padded elements are ignored during the subsequent steps.
Parameters
----------
batch : tuple of tuple of torch.Tensor
A batch of da... | bigcode/self-oss-instruct-sc2-concepts |
def reversed_list (seq) :
"""Returns a reversed copy of `seq`.
>>> reversed_list ([1, 2, 3, 4, 5])
[5, 4, 3, 2, 1]
>>> reversed_list ([1])
[1]
>>> reversed_list ([])
[]
"""
result = list (seq)
result.reverse ()
return result | bigcode/self-oss-instruct-sc2-concepts |
def grouper(some_list, count=2):
"""
splits a list into sublists
given: [1, 2, 3, 4]
returns: [[1, 2], [3, 4]]
"""
return [some_list[i:i+count] for i in range(0, len(some_list), count)] | bigcode/self-oss-instruct-sc2-concepts |
def _recur_flatten(key, x, out, sep='.'):
"""Helper function to flatten_dict
Recursively flatten all nested values within a dict
Args:
key (str): parent key
x (object): object to flatten or add to out dict
out (dict): 1D output dict
sep (str): flattened key separato... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def calculate_digest(body):
"""Calculate the sha256 sum for some body (bytes)"""
hasher = hashlib.sha256()
hasher.update(body)
return hasher.hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
import signal
import errno
def _settable_signal(sig) -> bool:
"""Check whether provided signal may be set.
"""
try:
old = signal.signal(sig, lambda _num, _frame: ...)
except OSError as e:
# POSIX response
assert e.errno == errno.EINVAL
return False
except ValueError... | bigcode/self-oss-instruct-sc2-concepts |
def u2t(x):
"""
Convert uint-8 encoding to 'tanh' encoding (aka range [-1, 1])
"""
return x.astype('float32') / 255 * 2 - 1 | bigcode/self-oss-instruct-sc2-concepts |
def first_non_empty(data_or_instance, field_or_fields, default=None):
"""
Return the first non-empty attribute of `instance` or `default`
:type data_or_instance: object or dict
:param data_or_instance: the instance or the resource
:type field_or_fields: str or tuple or list
:param field_or_fiel... | bigcode/self-oss-instruct-sc2-concepts |
def get_tile_size(model_height, model_width, padding, batch_height, batch_width):
"""
Calculate the super tile dimension given model height, padding, the number of tiles vertically and horizontally
:param model_height: the model's height
:param model_width: the model's width
:param padding: padding
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def ndc_to_screen_points_naive(points, imsize):
"""
Transforms points from PyTorch3D's NDC space to screen space
Args:
points: (N, V, 3) representing padded points
imsize: (N, 2) image size = (height, width)
Returns:
(N, V, 3) tensor of transformed points
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def normalize(qualName):
"""
Turn a fully-qualified Python name into a string usable as part of a
table name.
"""
return qualName.lower().replace('.', '_') | bigcode/self-oss-instruct-sc2-concepts |
def load_language_modeling(from_path: str) -> list:
"""Load language modeling dataset.
"""
dataset = []
with open(from_path, 'r', encoding='utf-8') as reader:
for line in reader.readlines():
dataset.append(line.strip())
return dataset | bigcode/self-oss-instruct-sc2-concepts |
def num_to_str(num):
# type: (None) -> str
"""Number to string without trailing zeros"""
s = str(num)
return '0' if s == '0' else s.rstrip('0').rstrip('.') | bigcode/self-oss-instruct-sc2-concepts |
def _get_last_cell(nb):
"""
Get last cell, ignores cells with empty source (unless the notebook only
has one cell and it's empty)
"""
# iterate in reverse order
for idx in range(-1, -len(nb.cells) - 1, -1):
cell = nb.cells[idx]
# only return it if it has some code
if cel... | bigcode/self-oss-instruct-sc2-concepts |
def data_for_ray_slice(radar, ray_sl, fieldnames=None):
""" Given a slice object ray_sl, return r,az,el,t,data
corresponding to the fieldnames. If fieldname is None,
no data will be returned. Fieldnames should be a sequence of field
names. A data dictionary is returned with a key for each of... | bigcode/self-oss-instruct-sc2-concepts |
def should_sync(data, last_sync):
"""
Determine if a data collection needs to be synced.
"""
# definitely sync if we haven't synced before
if not last_sync or not last_sync.date:
return True
# check if any items have been modified since last sync
for data_item in data:
# >=... | bigcode/self-oss-instruct-sc2-concepts |
def get_accuracy(y_bar, y_pred):
"""
Computes what percent of the total testing data the model classified correctly.
:param y_bar: List of ground truth classes for each example.
:param y_pred: List of model predicted class for each example.
:return: Returns a real number between 0 and 1 for the model accura... | bigcode/self-oss-instruct-sc2-concepts |
def shell_sort(arr):
"""
Fuction to sort using Shell Sort
<https://en.wikipedia.org/wiki/Shellsort>.
:param arr: A list of element to sort
"""
gap = int((len(arr)/2))
while gap > 0:
for i in range(gap, len(arr)):
temp = arr[i]
j = i
while j >=... | bigcode/self-oss-instruct-sc2-concepts |
def not_equals(x):
"""A functional !=.
>>> not_equals(2)(2)
False
>>> not_equals("David")("Michael")
True
"""
def not_equals(y):
return x != y
return not_equals | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def wrap_text(string: str, max_chars: int) -> List[str]:
"""A helper that will return a list of lines with word-break wrapping.
:param str string: The text to be wrapped.
:param int max_chars: The maximum number of characters on a line before wrapping.
:return: A list of strin... | bigcode/self-oss-instruct-sc2-concepts |
import math
def get_sqrt_shape(area):
"""
Returns a square shape, assuming the area provided can be square.
"""
height = int(math.sqrt(float(area)))
width = height
return width, height | bigcode/self-oss-instruct-sc2-concepts |
def interpret_origin(geom, origin, ndim):
"""Returns interpreted coordinate tuple for origin parameter.
This is a helper function for other transform functions.
The point of origin can be a keyword 'center' for the 2D bounding box
center, 'centroid' for the geometry's 2D centroid, a Point object or a
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def _clip_barycentric_coordinates(bary) -> torch.Tensor:
"""
Args:
bary: barycentric coordinates of shape (...., 3) where `...` represents
an arbitrary number of dimensions
Returns:
bary: Barycentric coordinates clipped (i.e any values < 0 are set to 0)
an... | bigcode/self-oss-instruct-sc2-concepts |
def normal_row_count(model_cls, db):
""" Uses a normal .count() to retrieve the row count for a model. """
return model_cls.select().count() | bigcode/self-oss-instruct-sc2-concepts |
def longestString(listOfStrings):
"""
return longest string from a non-empty list of strings, False otherwise
By "longest", we mean a value that is no shorter than any other value in the list
There may be more than one string that would qualify,
For example in the list ["dog","bear","wolf","cat"... | bigcode/self-oss-instruct-sc2-concepts |
import re
def make_scanner(regex):
"""
Make log scanner for scanning potential attack using regex rule.
:param regex: regex rule for detecting attack in the log line
:return: function that scan for the attack in log file using the regex
"""
def scanner(line):
return True if re.search(... | bigcode/self-oss-instruct-sc2-concepts |
def has_duplicates(t):
"""Checks whether any element appears more than once in a sequence.
Simple version using a for loop.
t: sequence
"""
d = {}
for x in t:
if x in d:
return True
d[x] = True
return False | bigcode/self-oss-instruct-sc2-concepts |
import collections
def _get_output_map_from_op(varmap, op):
"""Returns a dict from op output name to the vars in varmap."""
iomap = collections.OrderedDict()
for key in op.output_names:
vars = []
for varname in op.output(key):
vars.append(varmap[varname])
if len(vars) =... | bigcode/self-oss-instruct-sc2-concepts |
def wrap_text_begin_end(title, body):
"""Wrap a block of text with BEGIN and END for PEM formatting."""
return (
"-----BEGIN %s-----\n" % (title,)
+ body
+ "\n-----END %s-----\n" % (title,)
) | bigcode/self-oss-instruct-sc2-concepts |
import re
def extract_integers(string):
"""Extract all integers from the string into a list (used to parse the CMI gateway's cgi output)."""
return [int(t) for t in re.findall(r'\d+', string)] | bigcode/self-oss-instruct-sc2-concepts |
def full_name(family, style):
"""Build the full name of the font from ``family`` and ``style`` names.
Names are separated by a space. If the ``style`` is Regular, use only the ``family`` name.
"""
if style == 'Regular':
full_name = family
else:
full_name = family + ' ' + style
... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def get_signature(item):
"""
Returns the sha256 hash of a string
"""
hash_object = hashlib.sha256(item.encode())
return hash_object.hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def safe_pandas_length(o):
""" Return the length of a pandas Series and DataFrame as expected for WL serialization.
- The length of a Series is the only value of the tuple `shape`.
- The length of a dataframe is the number of columns. It's the second value of `shape`.
This function is safe, when the s... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Any
def is_int(value: Any) -> bool:
"""Checks if a value is an integer.
The type of the value is not important, it might be an int or a float."""
# noinspection PyBroadException
try:
return value == int(value)
except Exception:
return False | bigcode/self-oss-instruct-sc2-concepts |
def _res_heur(data, *args, **kwargs):
"""
Returns, for the given data, the heuristic determining the
resolution of the voxel grid and correspondingly, how many
points get hashed to the same value.
"""
return 3 * len(data) ** 0.33333333 | bigcode/self-oss-instruct-sc2-concepts |
def state_to_int(p, statelist):
"""
Converts array of fermion-configuration into integer
Args:
p - dictionary that contains the relevant system parameters
statelist - fermion configuration
Returns:
out - integer corresponding to state
"""
# construct unique integer for th... | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_latlong(instr):
"""check whether a string is a valid lat-long."""
return (re.match(r'^\s*[0-9.+-]+\s*,\s*[0-9.+-]+\s*$', instr) != None) | bigcode/self-oss-instruct-sc2-concepts |
def member_joined_organization_message(payload):
"""
Build a Slack message informing about a new member.
"""
member_name = payload['user']['name']
member_url = payload['user']['url']
org_name = payload['organization']['name']
org_url = payload['organization']['url']
message = 'Say hi! ... | bigcode/self-oss-instruct-sc2-concepts |
import yaml
def parse_file(path):
"""Super simple utility to parse a yaml file given a path"""
with open(path, 'r') as cfile:
text = cfile.read()
conf = yaml.load(text, Loader=yaml.CLoader)
return conf | bigcode/self-oss-instruct-sc2-concepts |
def load_dataset(filepath):
"""Loads a file on the CoNLL dataset.
:param filepath: Path to a text file on the CoNLL format.
:return (X, Y) lists of sentences and labels.
"""
X = list()
x = list()
Y = list()
y = list()
for line in open(filepath):
# blank lines sepa... | bigcode/self-oss-instruct-sc2-concepts |
def _func_overhead(q, p, n):
"""
Model function to calculate the overhead.
:param q: Actual overhead parameters values
:param p: Numbers of cores used on model data
:param n: Problems size used on model data
:return: calculated overhead value
"""
return q[0]+(q[1]*p)/pow(q[2], n) | bigcode/self-oss-instruct-sc2-concepts |
def _f1(precision: float, recall: float) -> float:
"""
Compute f1.
:param float precision
:param float recall
:return: f1
:rtype: float
"""
if precision == recall == 0:
return 0
return 2 * precision * recall / (precision + recall) | bigcode/self-oss-instruct-sc2-concepts |
def CleanIndent(text, prefix=''):
"""Remove extra indentation from comments or code.
This allows code to be written as triple-quoted strings with natural
indentation in the python file, and that indentation will be removed
and replaced with the provided prefix.
Args:
text: Input code
prefix: will be... | bigcode/self-oss-instruct-sc2-concepts |
def escape(v):
"""
Escapes values so they can be used as query parameters
:param v: The raw value. May be None.
:return: The escaped value.
"""
if v is None:
return None
elif isinstance(v, bool):
return str(v).lower()
else:
return str(v) | bigcode/self-oss-instruct-sc2-concepts |
def _css_select(soup, css_selector):
""" Returns the content of the element pointed by the CSS selector,
or an empty string if not found """
selection = soup.select(css_selector)
if len(selection) > 0:
if hasattr(selection[0], 'text'):
retour = selection[0].te... | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_compatible(source_version, compat_versions):
"""
Compare a source version string to a set of target version string specifications. Supports semantic versioning
comparison via setuptools version comparison logic (http://setuptools.readthedocs.io/en/latest/setuptools.html#id7).
:param ... | bigcode/self-oss-instruct-sc2-concepts |
def edge_color_weight(G,edgelist=None):
"""Automatically calculate a normalized reasonable color for
a weighted graph
Parameters:
-----------
G: A networkx Graph
edgelist: A list
Edges to calculate the weights for if None, uses all edges
Returns:
--------
weight_dict: A dictio... | bigcode/self-oss-instruct-sc2-concepts |
import csv
def env_reader(infile: str) -> list:
"""
Read environment list from infile.
Parameters
----------
infile : str
Name of the file containing the environment list.
Returns
-------
list
Nested (2D) list of the environment.
"""
with open(infile, 'r') as ... | bigcode/self-oss-instruct-sc2-concepts |
def axis_list(n_axes: int, reverse=False) -> str:
"""Returns a comma-separated list of axis TypeVar short names.
Args:
n_axes: Maximum number of axes to include in the list.
n_axes=1 -> 'A1', n_axes=2 -> 'A1, A2', etc.
reverse: If False, the returned list starts from A1 and counts up to An.
... | bigcode/self-oss-instruct-sc2-concepts |
def mult_saturate(a, b, upper_bound, lower_bound):
"""
Returns the saturated result of a multiplication of two values a and b
Parameters
----------
a : Integer
Multiplier
b : Integer
Multiplicand
upper_bound : Integer
Upper bound f... | bigcode/self-oss-instruct-sc2-concepts |
def _GetReleaseTracks(release_tracks):
"""Returns a string representation of release tracks.
Args:
release_tracks: API versions to generate release tracks for.
"""
release_tracks_normalized = '[{}]'.format(', '.join(
[track.upper() for track in sorted(release_tracks)]))
return release_tracks_normal... | bigcode/self-oss-instruct-sc2-concepts |
def get_wsgi_header(header):
"""Returns a WSGI compliant HTTP header.
See https://www.python.org/dev/peps/pep-3333/#environ-variables for
information from the spec.
"""
return 'HTTP_{}'.format(header.upper().replace('-', '_')) | bigcode/self-oss-instruct-sc2-concepts |
def proportion_of_traffic_from_top_users(tweets, users_with_freq, n):
"""
Return the percentage of the traffic that comes from the n most active accounts in a list of tweets.
:param tweets: the list of tweets, represented as dictionaries.
:param users_with_freq: a Counter of usernames with the num... | bigcode/self-oss-instruct-sc2-concepts |
def is_valid_lindblad_paramtype(typ):
"""
Whether `typ` is a recognized Lindblad-gate parameterization type.
A *Lindblad type* is comprised of a parameter specification followed
optionally by an evolution-type suffix. The parameter spec can be
"GLND" (general unconstrained Lindbladian), "CPTP" (cp... | bigcode/self-oss-instruct-sc2-concepts |
def make_GeoJson(geoms, attrs):
"""
Creates GeoJson structure with given geom and attribute lists; throws exception if both lists have different length
:param geoms: list of geometries (needs to be encoded as geojson features)
:param attrs: list of attributes
:return: dict in GeoJson structure
"... | bigcode/self-oss-instruct-sc2-concepts |
def combine_bytes(reorder):
"""Combine list of bytes into one binary sequence"""
o = b''
for r in reorder:
o += r
return o | bigcode/self-oss-instruct-sc2-concepts |
def adjust_error_on_warning_flag(flag, step, language):
"""
Adjust a given compiler flag according to whether this is for configure or make.
"""
assert language in ('c', 'c++')
assert step in ('configure', 'make')
if language == 'c' and flag in ('-Wreorder', '-Wnon-virtual-dtor'):
# Skip... | bigcode/self-oss-instruct-sc2-concepts |
def x_to_ab(x, p, q):
"""
Given some integer x mod pq, returns the CRT representation (x mod p, x mod q)
(CRT -> Chinese Remainder Theorem).
"""
return x % p, x % q | bigcode/self-oss-instruct-sc2-concepts |
def is_number(num):
"""Checks if num is a number"""
try:
float(num)
except ValueError:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
def ok_for_raw_triple_quoted_string(s, quote):
"""
Is this string representable inside a raw triple-quoted string?
Due to the fact that backslashes are always treated literally,
some strings are not representable.
>>> ok_for_raw_triple_quoted_string("blah", quote="'")
True
>>> ok_for_raw_tr... | bigcode/self-oss-instruct-sc2-concepts |
import json
def read_fps(json_file_path):
"""
Open json file, read the fps the data was recorded at.
input: json file path
output: int (fps)
"""
with open(json_file_path) as f:
data = json.load(f)
fps = data['fps'][0]
return fps | bigcode/self-oss-instruct-sc2-concepts |
def separate_artists_list_by_comparing_with_another(
another_artists_list, compared_artist_list
):
"""
Input: Two list of artists_id
Return two lists containing:
- Every artist in compared_artist_list that are in another_artists_list
- Every artist in compared_artist_list that are not in anothe... | bigcode/self-oss-instruct-sc2-concepts |
def _is_items(lst):
"""Is ``lst`` an items list?
"""
try:
return [(a, b) for a, b in lst]
except ValueError:
return False | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def get_drop_columns_binary(categoricals: List[str], columns: List[str]) -> List[str]:
"""
Selects the columns which can be dropped for one-hot-encoded dfs without drop_first.
Is mainly needed to transform into drop_first encoding
Parameters
----------
categoricals: n... | bigcode/self-oss-instruct-sc2-concepts |
def process_predictions(lengths, target, raw_predicted):
"""
Removes padded positions from the predicted/observed values and
calls inverse_transform if available.
Args:
lengths: Lengths of the entries in the dataset.
target: Target feature instance.
raw_predicted: Raw predicted/... | bigcode/self-oss-instruct-sc2-concepts |
def get_start_end_from_string(start_end):
""" 111.222 => 111, 222 """
start, end = start_end.split(".")
start = int(start)
end = int(end)
return(start, end) | bigcode/self-oss-instruct-sc2-concepts |
def get_weighted_mean(distribution: list, weights: list) -> float:
"""
:param distribution: list of int or float to calculate the weighted mean
:param weights: weights list
:return: the weighted mean of distribution list
"""
numerator = sum([distribution[i] * weights[i] for i in range(len(distri... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def cross_over(input_data: List, value: int):
"""return true if input_data crossed over value otherwise false"""
return input_data[-1] > value > input_data[-2] | bigcode/self-oss-instruct-sc2-concepts |
def prod_nadate_process(prod_df, prod_col_dict, pnadrop=False):
"""
Processes rows of production data frame for missing time-stamp
info (NAN).
Parameters
----------
prod_df: DataFrame
A data frame corresponding to production data.
prod_df_col_dict: dict of {str : str}
A d... | bigcode/self-oss-instruct-sc2-concepts |
def wrap_seq_string(seq_string, n=60):
"""Wrap nucleotide string (seq_string) so that each line of fasta has length n characters (default n=60)
Args:
seq_string (str): String of DNA/protein sequence
n (int): Maximum number of characters to display per line
Returns:
(str): String o... | bigcode/self-oss-instruct-sc2-concepts |
def jib(foot, height):
"""
jib(foot,height) -> area of given jib sail.
>>> jib(12,40)
240.0
"""
return (foot*height)/2 | bigcode/self-oss-instruct-sc2-concepts |
def _mac_to_oid(mac):
"""Converts a six-byte hex form MAC address to six-byte decimal form.
For example:
00:1A:2B:3C:4D:5E converts to 0.26.43.60.77.94
Returns:
str, six-byte decimal form used in SNMP OIDs.
"""
fields = mac.split(':')
oid_fields = [str(int(v, 16)) for v in fiel... | bigcode/self-oss-instruct-sc2-concepts |
def get_amr_line(input_f):
"""
Read the file containing AMRs. AMRs are separated by a blank line.
Each call of get_amr_line() returns the next available AMR (in one-line form).
Note: this function does not verify if the AMR is valid
"""
cur_amr = []
has_content = False
for line in input... | bigcode/self-oss-instruct-sc2-concepts |
def read_obs(obs_file):
"""
Function to read in observation data from text file
each line should be formatted as "T ill V J"
"""
f = open(obs_file, 'r' )
f.readline() # there's a header with column labels
obs_T, obs_ill, obs_V, obs_J = [], [], [], []
for line in f:
l=line.s... | bigcode/self-oss-instruct-sc2-concepts |
def fake_answer_questionnaire(input_str, answer_options, multiple_choice_questions):
"""Imitates the ability of a self-aware model to answer questions about itself, as in answer_questionnaire subtask
Args:
input_str: String. The model's input, containing a question about the model
answer_option... | bigcode/self-oss-instruct-sc2-concepts |
import math
def make_jc_matrix(t, a=1.):
"""
Returns Juke Cantor transition matrix
t -- time span
a -- mutation rate (sub/site/time)
"""
eat = math.exp(-4*a/3.*t)
r = .25 * (1 + 3*eat)
s = .25 * (1 - eat)
return [[r, s, s, s],
[s, r, s, s],
[s, s, r, s],... | 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.