seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
import re
def isValidModelname(name):
"""Returns if a name contains characters other than alphanumeric, '_' and '-'.
Also, empyt strings are not valid model names.
Args:
name (str): potential name for a model
Returns:
bool -- True if the name is a valid model name according to conven... | bigcode/self-oss-instruct-sc2-concepts |
def Line2Float(line):
"""Convert a string into a list of Float"""
return map(float,line.split()) | bigcode/self-oss-instruct-sc2-concepts |
import socket
def get_current_hostname() -> str:
"""Returns the hostname of current machine
Returns:
str: current hostname
"""
return socket.gethostname() | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
from pathlib import Path
from typing import Optional
def searchcandidates(candidates: Iterable[Path]) -> Optional[Path]:
""" Searches for the first filename in `candidates` which exists. Returns `None` if none of the paths are valid.
Parameters
----------
candidates: List[Path]
T... | bigcode/self-oss-instruct-sc2-concepts |
def determine_color(number):
"""
In number ranges from 1 to 10 and 19 to 28, odd numbers are red and even are black.
In ranges from 11 to 18 and 29 to 36, odd numbers are black and even are red.
"""
if number >= 1 and number <= 10:
return "black" if number % 2 == 0 else "red"
elif number... | bigcode/self-oss-instruct-sc2-concepts |
def extract(query_dict, prefix=""):
"""
Extract the *order_by*, *per_page*, and *page* parameters from
`query_dict` (a Django QueryDict), and return a dict suitable for
instantiating a preconfigured Table object.
"""
strs = ['order_by']
ints = ['per_page', 'page']
extracted = { }
... | bigcode/self-oss-instruct-sc2-concepts |
def filterOdometry(solutions, odometry):
"""Filter the solutions by odometry.
Removes solutions from the list if there are not within range
of the odometry.
Args:
solutions: A set of points candidates to the final solution.
odometry: Odometry instance.
Returns:
A list of c... | bigcode/self-oss-instruct-sc2-concepts |
def mod_Goodman_Fos(sa, sm, Se, Sut):
"""
Computes the mod Goodman relation factor of safety
:param sa: alternating stress
:param sm: midrange stress
:param Se: Endurance strength
:param Sut: Ultimate tensile strength
:return: factor of safety
"""
n_inv = sa/Se + sm / Sut
retur... | bigcode/self-oss-instruct-sc2-concepts |
def flip_left_right(image):
"""Flips an image left and right.
# Arguments
image: Numpy array.
"""
return image[:, ::-1] | bigcode/self-oss-instruct-sc2-concepts |
def get_average_solution_length(population):
"""
Calculate the average distance of the instances within a population
Args:
population: list of indices with format {"feasible":[], "infeasible":[]}
Returns: avg distance of instances in the population
"""
sum_length = 0
nr_instances ... | bigcode/self-oss-instruct-sc2-concepts |
def updateAlias(old_alias: str, new_alias: str) -> str:
"""Return a query to update a character's alias."""
return (f"UPDATE alias "
f"SET aname='{new_alias}' "
f"WHERE aname='{old_alias}';"
) | bigcode/self-oss-instruct-sc2-concepts |
import json
def matdesc_to_unicode(matdesc):
"""Convert Material Descriptor to Unicode String."""
return str(
json.dumps(
{
"queryId": matdesc.query_id,
"smkId": str(matdesc.smk_id),
"keySize": str(matdesc.key_size),
},
... | bigcode/self-oss-instruct-sc2-concepts |
def bilinear_interp(x1, x2, y1, y2, x, y, q11, q12, q21, q22):
"""
Perform a bilinear interpolation at the point x,y from the rectangular grid
defined by x1,y1 and x2,y2 with values at the four corners equal to Q11, Q12,
Q21 and Q22.
"""
assert x1 <= x <= x2
assert y1 <= y <= y2
asser... | bigcode/self-oss-instruct-sc2-concepts |
def is_same_module_or_submodule(orig, incoming):
"""
Returns true if the incoming module is the same module as the original,
or is a submodule of the original module
"""
if incoming is None:
return False
if orig == incoming:
return True
if incoming.__name__.startswith(orig._... | bigcode/self-oss-instruct-sc2-concepts |
import re
def strip_internal_comments(text):
"""Removes internal comments from a string and normalizes whitespace
around them.
Comments are in the format [[comment]]. For example, the string 'Lorem
ispum [[dolor sit]] amet.' will be transformed to 'Lorem ipsum amet.'
Further examples: https://www... | bigcode/self-oss-instruct-sc2-concepts |
def count_in_layer(layer, number):
"""Count occurrences of number in layer."""
return sum(row.count(number) for row in layer) | bigcode/self-oss-instruct-sc2-concepts |
def shift_position(pos, x_shift, y_shift) -> dict:
"""
Moves nodes' position by (x_shift, y_shift)
"""
return {n: (x + x_shift, y + y_shift) for n, (x, y) in pos.items()} | bigcode/self-oss-instruct-sc2-concepts |
import re
def normalize(s):
"""
Normalizes a string:
- replaces any sequence of whitespace characters (including non-breaking space) with a single space character
"""
if s == None:
return None
else:
return re.sub(r'\s+', ' ', s) | bigcode/self-oss-instruct-sc2-concepts |
def remove_whitespace(string):
"""Remove whitespace from string"""
return "".join(string.split()) | bigcode/self-oss-instruct-sc2-concepts |
def reversed_enumerate(seq):
"""Like reversed(list(enumerate(seq))) without copying the whole seq."""
return zip(reversed(range(len(seq))), reversed(seq)) | bigcode/self-oss-instruct-sc2-concepts |
import re
def strip_prefix(line):
"""Remove the [filename:lineno] prefix in a Log line, if present."""
m = re.match(r"^(\[.+:\d+\]\s*)(.*)", line)
if m:
return m.group(2)
else:
return line | bigcode/self-oss-instruct-sc2-concepts |
def proper(s):
"""Strips then capitalizes each word in a string."""
s = s.replace("-", " ").title()
s = s.replace("_", " ").title()
return s | bigcode/self-oss-instruct-sc2-concepts |
def clip(input, conf):
"""
Clip the generating instance with each feature to make sure it is valid
:param input: generating instance
:param conf: the configuration of dataset
:return: a valid generating instance
"""
for i in range(len(input)):
input[i] = max(input[i], conf.input_boun... | bigcode/self-oss-instruct-sc2-concepts |
def check_models_have(models, key):
"""Check models have deserialized the provided key."""
n_err_models = 0
for m in models:
if not m.is_deserialized(key):
n_err_models += 1
if n_err_models:
return "errors: {}/{} models {} don't have key {}".format(
n_err_models, ... | bigcode/self-oss-instruct-sc2-concepts |
def _val2col(val):
"""
Helper function to convert input value into a red hue RGBA
"""
nonred = abs(0.5-val)*2.0
return (1.0,nonred,nonred,1.) | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_snake_case(id_name):
"""Check if id_name is written in snake case.
Actually, it is restricted to a certain subset of snake case, so that
we can guarantee camel->snake->camel roundtrip.
>>> is_snake_case('')
False
>>> is_snake_case('_')
False
>>> is_snake_case('h')
... | bigcode/self-oss-instruct-sc2-concepts |
from __main__ import gearsConfigGet as redisGearsConfigGet
def gearsConfigGet(key: str, default=None) -> str:
"""Fetches the current value of a RedisGears configuration option and returns a
default value if that key does not exist.
Args:
key (str):
The configuration option key.
... | bigcode/self-oss-instruct-sc2-concepts |
import random
def choose_from_string(string: str, n: int):
""" Choose a card from a string. Returns the choice and what remains after choosing. """
assert len(string) >= n
choices = []
for _ in range(n):
char = random.choice(string)
string = string.replace(char, '', 1)
choice... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def get_image() -> bytes:
"""Get a person that does not exist."""
data = requests.get(
"https://thispersondoesnotexist.com/image",
headers={"User-Agent": "My User Agent 1.0"},
).content
return data | bigcode/self-oss-instruct-sc2-concepts |
def potential(r, r_c, r_e, r_a):
"""Potential (Eq. 4)
Args:
r: distance between agent i and j
r_c: hard-core repulsion distance
r_e: equilibrium (preferred) distance
r_a: maximum interaction range
Returns:
potential: attractive/repulsive potential
"""
if r < r... | bigcode/self-oss-instruct-sc2-concepts |
def get_sender(tx: dict) -> str:
"""
Returns the tx sender's address
:param tx: transaction dictionary
:return: str
"""
return tx["events"][0]["sub"][0]["sender"][0]["account"]["id"] | bigcode/self-oss-instruct-sc2-concepts |
def next_power_of_two(x):
# type: (int) -> int
"""
Compute the next power of two that is greater than `x`:
>>> next_power_of_two(0)
1
>>> next_power_of_two(1)
2
>>> next_power_of_two(2)
4
>>> next_power_of_two(3)
4
>>> next_power_of_two... | bigcode/self-oss-instruct-sc2-concepts |
def harmonic_mean(series: list) -> float:
"""
return the harmonic mean of series
>>> harmonic_mean([1, 4, 4])
2.0
>>> harmonic_mean([3, 6, 9, 12])
5.759999999999999
>>> harmonic_mean(4)
Traceback (most recent call last):
...
ValueError: Input series is not valid, valid serie... | bigcode/self-oss-instruct-sc2-concepts |
def _weight(role):
"""Return an integer weight for the given role for sorting purposes."""
if role == "CEO":
return 0
return 100 | bigcode/self-oss-instruct-sc2-concepts |
def schedule_composition(row):
"""Takes in a series with $id and \*_ScheduleDay_Name values and return an
array of dict of the form {'$ref': ref}
Args:
row (pandas.Series): a row
Returns:
list: list of dicts
"""
# Assumes 7 days
day_schedules = []
days = [
"Mond... | bigcode/self-oss-instruct-sc2-concepts |
def faxen_factor(height, radius, lateral=True):
"""
Return the relative change of the stokes drag according to Faxen's law.
References
----------
Schäffer, E., et al.
Surface forces and drag coefficients of microspheres near a plane
surface measured with optical tweezers.
La... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
from typing import Callable
from typing import Any
def delegate_factory(cls: type, delegate_attrs: Iterable[str]) -> Callable[[Any], Any]:
"""
Create factory function that searches object `o` for `delegate_attrs`
and check is any of these attributes have `cls` type. If no such
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Optional
def column_name_to_metric_target(col_name: str) -> tuple[str, Optional[str]]:
"""
Return (metric_name, column_name) from column name that build by this class.
"""
parts = col_name.split("__")
if parts[0] == "table_metric":
return parts[1], None
if parts[0] =... | bigcode/self-oss-instruct-sc2-concepts |
def lookup_dict_from_url_params(url_params):
"""Convert a url_params dict in a mapping suitable for ORM querying."""
lookup_dict = {}
for k, v in url_params.items():
values = v.split(",")
if len(values) > 1:
lookup_dict[k] = values
else:
lookup_dict[k] = v
... | bigcode/self-oss-instruct-sc2-concepts |
import functools
def classdecorator(func):
"""Class decorator that can be used with or without parameters."""
@functools.wraps(func)
def wrapper(cls=None, **kwargs):
def wrap(klass):
return func(klass, **kwargs)
# Check if called as @decorator or @decorator(...).
if cl... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def cast_trailing_nulls(series: List) -> List:
"""
Cast trailing None's in a list series to 0's
"""
for i, x in reversed(list(enumerate(series))):
if x is None:
series[i] = 0
else:
return series
return series | bigcode/self-oss-instruct-sc2-concepts |
def _is_multiple_records(mem_addr, num_recs):
"""Return true if we are searching for multiple records."""
return (mem_addr == 0x00 and num_recs == 0) or num_recs > 1 | bigcode/self-oss-instruct-sc2-concepts |
def _encode_structure_parts(local_target):
"""
Encodes the design task, to distinguish between struture and wequence domains.
Args:
A sequence that may contain structure or sequence parts.
Returns:
A list representation of the sequence with all structure sites and None else.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
import hmac
def is_valid_digest(hash_a: str, hash_b: str) -> bool:
"""Compares two hashes using `hmac.compare_digest`."""
return hmac.compare_digest(hash_a, hash_b) | bigcode/self-oss-instruct-sc2-concepts |
def all_visible_subclasses(klass):
"""
Returns all reachable subclasses of the supplied class, presumably a BaseModel subclass.
"""
def helper(klas, result):
subklases = klas.__subclasses__()
if len(subklases) > 0:
result.update(subklases)
for subklas in subklase... | bigcode/self-oss-instruct-sc2-concepts |
def binomial_coeff(n, k):
"""Compute the binomial coefficient "n choose k".
n: number of trials
k: number of successes
returns: int
"""
# Just put all three return possibilities into one statement. Could use parentheses if it
# seems clearer.
return 1 if k==0 else 0 if n==0 else binomi... | bigcode/self-oss-instruct-sc2-concepts |
def to_camel_case(source: str) -> str:
"""Converts the specified source string from snake_case to camelCase."""
parts = source.split("_")
prefix = parts.pop(0)
suffix = "".join([p.capitalize() for p in parts])
return f"{prefix}{suffix}" | bigcode/self-oss-instruct-sc2-concepts |
def cast(x, dtype=None):
"""
Casts a tensor to a new type.
Parameters
----------
x : tensor
A Tensor or SparseTensor or IndexedSlices of numeric type.
It could be uint8, uint16, uint32, uint64, int8, int16, int32, int64, float16, float32, float64.
dtype : dtpye
The dest... | bigcode/self-oss-instruct-sc2-concepts |
def fullscan_policy(obs):
"""
A policy function that generates only fullscan data.
"""
valid_actions = obs['valid_actions']
ms1_action = len(valid_actions) - 1 # last index is always the action for MS1 scan
return ms1_action | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
import shlex
def split_run_args(command: str) -> List[str]:
"""Splits a shell command string into arguments."""
return shlex.split(command) | bigcode/self-oss-instruct-sc2-concepts |
import six
def _cell(item, column, key, fmt):
"""Constructs a value in table cell."""
if key is None:
key = column
if isinstance(key, six.string_types):
keys = [key]
else:
keys = key
raw_value = None
for k in keys:
if k in item and item[k] is not None:
... | bigcode/self-oss-instruct-sc2-concepts |
def file_key(entry):
"""
For a PlaylistEntry, return a path.
"""
if entry.remote:
return entry.remote.path
return entry.path | bigcode/self-oss-instruct-sc2-concepts |
import pathlib
import yaml
def read_yaml_data(data_filename: str, names=None) -> dict:
"""Read in a YAML data file as a dictionary"""
data_path = pathlib.Path(data_filename)
try:
with data_path.open('r', encoding='utf-8') as fp:
yaml_data = yaml.safe_load(fp)
except FileNotFoundErr... | bigcode/self-oss-instruct-sc2-concepts |
import math
def prime_check(num):
"""
Checks if a single number is prime.
A simple function, not a speedy solution.
"""
if num == 1:
return False
upper_bound = int(math.sqrt(num) + 1)
for n in range(2, upper_bound):
if num % n == 0:
return False
return True | bigcode/self-oss-instruct-sc2-concepts |
import re
def filter_subs(subs, pattern):
"""Returns a list of subtitles who's text contains the given regex pattern"""
ret = []
for sub in subs:
if re.search(pattern, sub.text, re.MULTILINE):
ret.append(sub)
return ret | bigcode/self-oss-instruct-sc2-concepts |
def get_ids_from_individual(individual):
"""Gets the ids from a given individual
Args:
individual (CPPN): The individual to get the ids from.
Returns:
tuple: (inputs, outputs, connections) the ids of the CPPN's nodes
"""
inputs = [n.id for n in individual.input_nodes()]
outputs... | bigcode/self-oss-instruct-sc2-concepts |
def _get_conv_shape_1axis(
image_shape, kernel_shape, border_mode, subsample, dilation=1
):
"""This function compute the output shape of convolution operation.
Copied and simplified from theano (2020/11/08):
https://github.com/Theano/Theano/blob/master/theano/tensor/nnet/abstract_conv.py
Parameters
... | bigcode/self-oss-instruct-sc2-concepts |
def get_gaze_point_mm(limbus):
""" Returns intersection with z-plane of optical axis vector (mm)
"""
# Ray-plane intersection
x0, y0, z0 = limbus.center_mm
dx, dy, dz = limbus.normal
t = -z0 / dz
x_screen_mm, y_screen_mm = x0 + dx * t, y0 + dy * t
return x_screen_mm, y_screen... | bigcode/self-oss-instruct-sc2-concepts |
def get_input_from_kvp(datainputs):
"""Get execute DataInputs from URL (key-value-pairs) encoding
"""
inputs = {}
if datainputs:
for inpt in datainputs.split(";"):
(identifier, val) = inpt.split("=")
# add input to Inputs
inputs[identifier] = val
retur... | bigcode/self-oss-instruct-sc2-concepts |
def end_of_string_doc(editor, start_line):
""" Find where a docstring ends, beginning with `start_line` and working forward """
for i in range(start_line, len(editor.lines)):
if editor.lines[i].endswith(('"""', "'''")):
return i
return None | bigcode/self-oss-instruct-sc2-concepts |
def oppgaver_med_feil(data):
"""Sammenligner avgitt svar med riktig svar returnerer liste med indeksene til svarene som er feil.
Parameters
----------
data : list
En list med dictionarys
Returns
-------
list
En list med indeksene til de spørsmålene som er besvart feil.
... | bigcode/self-oss-instruct-sc2-concepts |
def dict_to_str(d, val_sep=' ', item_sep=' '):
"""Convert dict to string"""
str_list = [f'{k}{val_sep}{v}' for k, v in d.items()]
s = item_sep.join(str_list)
return s | bigcode/self-oss-instruct-sc2-concepts |
def identity(x):
"""Identity function: return the given argument unchanged"""
return x | bigcode/self-oss-instruct-sc2-concepts |
def comment_prep(content):
"""
Prepares the comment so we can have sme basic context.
"""
# same comment structure, so we'll just do it in a function
text = "Imgur link: " + content
text += "\n\n\n------\n"
text += "This action was performed by a bot. Message +/u/arrivance for further deta... | bigcode/self-oss-instruct-sc2-concepts |
def _normalize_integer_rgb(value):
"""
Normalize ``value`` for use in an integer ``rgb()`` triplet, as follows:
* If ``value`` is less than 0, convert to 0.
* If ``value`` is greater than 255, convert to 255.
Examples:
>>> _normalize_integer_rgb(0)
0
>>> _normalize_integer_rg... | bigcode/self-oss-instruct-sc2-concepts |
async def leave_comment(gh, issue_comment_url: str, message: str, token: str):
"""
Leave comment in issue or pull request
:param gh: object with actions
:param issue_comment_url: api string
:param message: comment
:param token: GitHub token
:return: response
"""
data = {'body': messa... | bigcode/self-oss-instruct-sc2-concepts |
def get_partial_index(df, start=None, end=None):
"""Get partial time index according to start and end
Parameters
----------
df: pd.DatFrame or pd.Series
start: str, optional, e.g., '2000-01-01'
end: str, optional, e.g., '2017-08-31'
Returns
-------
pd.DatetimeIndex
"""
if s... | bigcode/self-oss-instruct-sc2-concepts |
import string
def remove_punct(user_input):
"""The remove_punct function gets rid of all punctuation from the string.
Parameters
----------
user_input : string
Input received from user
Returns
-------
output_list : string
User's input with removed punctuation
"... | bigcode/self-oss-instruct-sc2-concepts |
import math
def primes_list(lower, upper):
"""Problem 39: A list of prime numbers
Parameters
----------
lower : int
The lower bound of the prime numbers to return
upper : int
The upper bound of the prime numbers ro return
Returns
-------
list of int
A list of ... | bigcode/self-oss-instruct-sc2-concepts |
def describe_nunique(df):
"""
describe method including nunique for numeric descriptions
"""
df_described = df.describe(include='number').T
df_described['unique'] = df.select_dtypes(include='number').nunique()
return df_described[['count', 'unique', 'mean', 'std', 'min', 'max', '25%', '50%', '75... | bigcode/self-oss-instruct-sc2-concepts |
import re
def clean_html(text):
"""
Remove html tags from text and convert a small set of html-encoded symbols
:param text: string with html markup
:return: text without html markup
"""
if text:
clean_text = re.sub('<[^<]+?>', ' ', text)
clean_text = clean_text.strip()
... | bigcode/self-oss-instruct-sc2-concepts |
def get_surrounding_text(text, sub_start, sub_end=None, distance=25):
"""
Looks for the substrings, 'sub_start' and 'sub_end' variables in 'text' and return a new substring
with a number equal to 'distance' characters in the left of 'sub_start' position and in the right of
'sub_end' position if they exi... | bigcode/self-oss-instruct-sc2-concepts |
def drop_systematics(blocks, systematics):
"""Drop a systematic from a set of blocks.
Parameters
----------
blocks : list(str)
All TRExFitter blocks.
systematics : list(str)
Name of the systematic to drop.
Returns
-------
list(str)
Blocks without desired systema... | bigcode/self-oss-instruct-sc2-concepts |
def pg_version(conn):
"""
Returns the PostgreSQL server version as numeric and full version.
"""
num_version = conn.get_pg_version()
conn.execute("SELECT version()")
full_version = list(conn.get_rows())[0]['version']
return dict(numeric=num_version, full=full_version) | bigcode/self-oss-instruct-sc2-concepts |
def iseven(x):
"""is the number x an even number?"""
return x%2 == 0 | bigcode/self-oss-instruct-sc2-concepts |
def getValueTryRemoveTailZero(float_num):
"""
try to remove .0 from an float number, 2.00 -> 2
keep other float as it was, 2.02 -> 2.02
:param float float_num
:return float/int
"""
int_num = int(float_num)
if int_num == float_num:
return int_num
return float_... | bigcode/self-oss-instruct-sc2-concepts |
def merge_value_range_fields(nmdc_objs: list, tx_attributes: list, **kwargs) -> list:
"""
Takes each nmdc object (either a dict or class instance) and merges two
attributues into a single attribute separated by a "-".
Additionaly, the has_minuimum_numeric_value and has_maximum_numeric_value
attrubut... | bigcode/self-oss-instruct-sc2-concepts |
def nan2zero(data):
""" Replace NaNs and negative values by zeros
"""
return [val if val>0 else 0 for val in data] | bigcode/self-oss-instruct-sc2-concepts |
def to_dojo_data(items, identifier='id', num_rows=None):
"""Return the data as the dojo.data API defines.
The dojo.data API expects the data like so:
{identifier:"whatever",
items: [
{name:"Lenin", id:3, ....},
]
}
The identifier is optional.
"""
ret = {'items':items}
... | bigcode/self-oss-instruct-sc2-concepts |
from collections import defaultdict
def convert_tab_to_dict(response):
"""Convert tab response to dictionary.\n
Response is a string made of rows with two tab separated columns."""
if not type(response) == type("hola"):
print("The argument is not a string.")
return {}
result = default... | bigcode/self-oss-instruct-sc2-concepts |
def _get_member_groups(get_member_group_func, identifier, security_enabled_only):
"""Call 'directoryObject: getMemberGroups' API with specified get_member_group_func.
https://docs.microsoft.com/en-us/graph/api/directoryobject-getmembergroups
"""
body = {
"securityEnabledOnly": security_enabled_o... | bigcode/self-oss-instruct-sc2-concepts |
def model_to_dict(instance, fields=None, exclude=None):
"""
Return a dict containing the data in instance.
This differs from django.forms.model_to_dict by containing non-editable
fields and relation values being the related objects instead of pk of those
objects.
:param instance: Model instanc... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def key_to_md5(key):
"""
convert bibtex-key to shortened md5-sum to avoid special characters in the keys
:param key: bibtex-key of an article
:return: converted key, first six characters of the key md5-sum
"""
m = hashlib.md5()
m.update(key.encode('utf-8'))
hd = m.hexdig... | bigcode/self-oss-instruct-sc2-concepts |
import random
def generate_shuffle(dic):
"""
Given a dictionary, shuffle the keys
"""
keys = list(dic.keys())
return (random.sample(keys, len(keys))) | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Optional
def local_paths_from_manifest_item(
item: Dict,
imgs_s3key_prefix: str,
textract_s3key_prefix: Optional[str] = None,
imgs_local_prefix=None,
textract_local_prefix=None,
) -> Dict:
"""Translate Textract+image manifest S3 URIs to local paths
... | bigcode/self-oss-instruct-sc2-concepts |
def url(host, port):
"""
Return the URL where the server can be reached.
"""
return 'wss://{}:{}'.format(host, port) | bigcode/self-oss-instruct-sc2-concepts |
def extract_argument(arguments, prefix, remove=True):
"""Extract argument from arguments."""
for argument in arguments[:]:
if argument.startswith(prefix):
if remove:
arguments.remove(argument)
return argument[len(prefix):]
return None | bigcode/self-oss-instruct-sc2-concepts |
def get_error_messages( response ):
"""
Builds a string based on the error messages in the payload
Args:
response: The response to print
Returns:
The string containing error messages
"""
# Pull out the error payload and the messages
out_string = response.dict["error"]["mes... | bigcode/self-oss-instruct-sc2-concepts |
def centerpoint(geolocations):
"""
:param geolocations: array of arrays in the form of [[longitude, latitude],[longitude,latitude]]
:return: average latitude and longitude in the form [latitude, longitude]
"""
lats = []
lngs = []
for lon, lat in geolocations:
lats.append(lat)
... | bigcode/self-oss-instruct-sc2-concepts |
def _check_lesson_is_empty(parsed_lesson):
"""
Checking lesson for being empty
Args:
parsed_lesson (dict): Parsed lesson
Return:
bool: True if parsed_lesson['info'] have any content except whitespaces, else False
"""
return not parsed_lesson['info'].strip() | bigcode/self-oss-instruct-sc2-concepts |
import logging
import csv
def read_header(filepath):
"""Read header line of CSV file.
INPUT:
filepath: Full pathname of CSV file
OUTPUT:
i: First row of CSV file
"""
logging.info("Reading header for {0}".format(filepath))
with open(filepath, "r") as f:
reader = csv.re... | bigcode/self-oss-instruct-sc2-concepts |
def get_revoke_key(revoke_statement):
"""
Create the key from the revoke statement.
The key will be used as the dictionnary key.
:param revoke_statement: The revoke statement
:return: The key
"""
splitted_statement = revoke_statement.split()
revoke_privilege = splitted_statement[1]
... | bigcode/self-oss-instruct-sc2-concepts |
import csv
def read_connections_file(infile):
"""
Reads a two-column CSV file of integers into a list of tuples
corresponding to indices of connected concepts.
:param str infile: Path to the CSV file.
:returns: List of int tuples of connections.
:rtype: list
"""
connections = []
w... | bigcode/self-oss-instruct-sc2-concepts |
def do_enable_unwinder1(unwinders, name_re, flag):
"""Enable/disable unwinders whose names match given regex.
Arguments:
unwinders: The list of unwinders.
name_re: Unwinder name filter.
flag: Enable/disable.
Returns:
The number of unwinders affected.
"""
total = 0
... | bigcode/self-oss-instruct-sc2-concepts |
def leapfrog(theta, r, grad, epsilon, f):
""" Perfom a leapfrog jump in the Hamiltonian space
INPUTS
------
theta: ndarray[float, ndim=1]
initial parameter position
r: ndarray[float, ndim=1]
initial momentum
grad: float
initial gradient value
epsilon: float
... | bigcode/self-oss-instruct-sc2-concepts |
import random
def _apply_func_with_prob(func, image, args, prob):
"""Apply `func` to image w/ `args` as input with probability `prob`."""
# Apply the function with probability `prob`.
should_apply_op = random.random() + prob
if should_apply_op >= 1.0:
augmented_image = func(image, *args)
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
import re
def get_formatter(env_var_name: str) -> Callable[[str], str]:
"""
Returns a formatter function for given environment variablel.
:param env_var_name: name of environment variable
:return: formatting function
"""
if env_var_name.endswith("PATH"):
r... | bigcode/self-oss-instruct-sc2-concepts |
from bs4 import BeautifulSoup
def get_soup_from_static_html(html):
"""
Parameters
----------------
html: str/path obj
the path to the html file
Returns
-----------------
soup: bs4 Soup obj
"""
with open(html, 'r') as fh:
soup = BeautifulSoup(fh, 'html.parser')
... | bigcode/self-oss-instruct-sc2-concepts |
def form_yes_or_no(QUESTION: str, DEFAULT_NO: bool = True) -> bool:
"""
Single yes or no question without recursion.
Credit:
Inspired from
@icamys commented on 29 Nov 2020 on Github,
https://gist.github.com/garrettdreyfus/8153571
"""
CHOICES = " [y/N]: " if DEFAULT_NO else "... | bigcode/self-oss-instruct-sc2-concepts |
def valid_priority_len(priority):
"""Checks for values with exactly one significant digit
:param float priority:
:return boolean:
"""
result = len(str(priority).rsplit('.')[-1]) == 1
return result | 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.