seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def project_nonneg(values, imag_eps=1e-10, real_eps=1e-10, real_trunc=0.0):
"""Check that values are real and non-negative
:param np.ndarray values: An ndarray of complex or real values (or
a single value). `values` is modified in-place unless `values`
is complex. A single value is also accepte... | bigcode/self-oss-instruct-sc2-concepts |
def get_leaves_with_labels(tree):
"""
Return leaves in the tree, as well as their labels
>>> from ptb import parse
>>> t = parse("(4 (4 (2 A) (4 (3 (3 warm) (2 ,)) (3 funny))) (3 (2 ,) (3 (4 (4 engaging) (2 film)) (2 .))))")
>>> get_leaves_with_labels(t)
[('A', 2), ('warm', 3), (',', 2), ('... | bigcode/self-oss-instruct-sc2-concepts |
def as_dictionary_of_dictionaries(labels, means, cov_diags):
""" Dictionary storing one dictionary of parameters per category. """
assert len(labels) == len(means) == len(cov_diags)
all_params = dict()
for label, mean, cov_diag in zip(labels, means, cov_diags):
category_params = dict()
... | bigcode/self-oss-instruct-sc2-concepts |
import requests
def request_api_key(username: str, email:str, description:str="I'd like to try it out.", referral_code: str="github_referred"):
"""
Request an api key
Make sure to save the api key somewhere safe. If you have a valid referral code, you can recieve the api key more quickly.
... | bigcode/self-oss-instruct-sc2-concepts |
def check_true(answer, label):
"""
Check if a given answer matches the label
:param answer: the probability output from the network
:type answer: float
:param label: the label integer as either a 1 or a 0
:type label: float
:return: 1 if classification is correct, 0 if incorrect
:rtype: ... | bigcode/self-oss-instruct-sc2-concepts |
def get_snapshots_from_text(query_output):
""" Translate expanded snapshots from `cali-query -e` output into list of dicts
Takes input in the form
attr1=x,attr2=y
attr1=z
...
and converts it to `[ { 'attr1' : 'x', 'attr2' : 'y' }, { 'attr1' : 'z' } ]`
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def is_palindrome(s):
""" (str) -> boolean
Returns true if the argument is a palindrome else false
>>> is_palindrome("noon")
True
>>> is_palindrome("later")
False
>>> is_palindrome("radar")
True
"""
# converts (s) to lower case and assigns it to the variable word
word = s.low... | bigcode/self-oss-instruct-sc2-concepts |
def xor(bytes1, bytes2):
"""
Xor two input bytes and return
Input: `bytes1`, `bytes2`: bytes need to xor.
Output: xor result
"""
return bytes([a ^ b for a, b in zip(bytes1, bytes2)]) | bigcode/self-oss-instruct-sc2-concepts |
import random
def get_random_filename(file_list):
"""
Gets a random filename from inside the ZipFile object,
with the selected file extension
:return: arbitrary filename of selected type (extension)
"""
file_extension = '.xml'
filename_list = [x.filename for x in file_list if x.filename.en... | bigcode/self-oss-instruct-sc2-concepts |
def deplen(deps):
"""Compute dependency length from result of ``dependencies()``.
:returns: tuple ``(totaldeplen, numdeps)``."""
total = sum(abs(a - b) for a, label, b in deps
if label != 'ROOT')
return (total, float(len(deps) - 1)) | bigcode/self-oss-instruct-sc2-concepts |
import re
def _set_value(str_text, str_line, val):
"""
This function search for str_line in str_text and overwrites the whole
matching line with <str_line> str(val)
"""
str_text = re.sub('\n' + str_line + '.*',
'\n' + str_line + str(val),
str_text)
r... | bigcode/self-oss-instruct-sc2-concepts |
def get_iam_service_account_email(project_id, account_id):
"""
Return the service account email given the id and project id
Args:
project_id (str): Project Identifier where service account lives
account_id (str): The account id originally provided during creation
Returns:
str: ... | bigcode/self-oss-instruct-sc2-concepts |
def maximo(numero1, numero2):
"""Devolve o maior número"""
if numero1 >= numero2:
return numero1
else:
return numero2 | bigcode/self-oss-instruct-sc2-concepts |
def mayan_tzolkin_date(number, name):
"""Return a Tzolkin Mayan date data structure."""
return [number, name] | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def dollar_str_formatting(val: Union[int, float]) -> str:
"""
Format dollar figures into $val trillion, $val billion, etc.
Parameters
----------
val: float
revenue amount
Returns
-------
str
formatted dollar figure
"""
val = abs(val)
... | bigcode/self-oss-instruct-sc2-concepts |
def key( *args ):
"""
join the arguments in the format of donkey
Arguments
---------
args: list of string
Examples
--------
>>>key( 'a', 'b', 'c' )
'a__b__c'
"""
return '__'.join( args ) | bigcode/self-oss-instruct-sc2-concepts |
import string
import secrets
def new_salt(n=12):
"""Generate a new salt."""
salt_chars = string.ascii_letters + string.digits
salt = [secrets.choice(salt_chars) for _ in range(n)]
return "".join(salt) | bigcode/self-oss-instruct-sc2-concepts |
def obtain_reverse_codes(mapped, dst):
"""
Given the list of desired dst codes and an extensive map src -> dst,
obtain the list of src codes
:param mapped: Correspondence between src codes and dst codes [{"o", "to": [{"d", "e"}]}]
:param dst: Iterable of destination codes
:return: List of origi... | bigcode/self-oss-instruct-sc2-concepts |
def leniter(iterator):
"""leniter(iterator): return the length of an iterator, consuming it."""
if hasattr(iterator, "__len__"):
return len(iterator)
nelements = 0
for _ in iterator:
nelements += 1
return nelements | bigcode/self-oss-instruct-sc2-concepts |
def calc_center_pos(city, nodelist):
"""
Calculates center position for nodes in nodelist
Parameters
----------
city : object
city object of pycity_calc
nodelist : list (of ints)
List of node ids
Returns
-------
pos : tuple
Position tuple (x, y)
"""
... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def trilinear_composition(h_s, h_t, x, einsum=True):
"""
Trilinear composition as described in:
STAMP: Short-Term Attention/Memory Priority Model forSession-based Recommendation
Shapes:
b: batch
e: embedding
l: longest sequence length
v: vocabulary size
Parameters
... | bigcode/self-oss-instruct-sc2-concepts |
def is_getter(attribute):
"""
Test if a method is a getter.
It can be `get` or `get_*`.
"""
return attribute.startswith('get') | bigcode/self-oss-instruct-sc2-concepts |
import functools
def _memo(fn):
"""Helper decorator memoizes the given zero-argument function.
Really helpful for memoizing properties so they don't have to be recomputed
dozens of times.
"""
@functools.wraps(fn)
def memofn(self, *args, **kwargs):
if id(fn) not in self._cache:
... | bigcode/self-oss-instruct-sc2-concepts |
def verify_keyid_is_v4(signing_key_fingerprint):
"""Verify that the keyid is a v4 fingerprint with at least 160bit"""
return len(signing_key_fingerprint) >= 160/8 | bigcode/self-oss-instruct-sc2-concepts |
def update_parameters_with_momentum(parameters, grads, v, beta, learning_rate):
"""
Update parameters using Momentum
-Because mini-batch gradient descent makes a parameter update after seeing just a subset of examples,
the direction of the update has some variance, and so the path taken by mini-batch gradient desc... | bigcode/self-oss-instruct-sc2-concepts |
def get_queuelisting_perspective(display):
"""Retrieve the QueueListing perspective.
Args:
display: the display containing the loaded perspective
Returns:
QueueListing: the loaded QueueListing perspective
"""
display._active_perspective = 2
return display.perspectives[2] | bigcode/self-oss-instruct-sc2-concepts |
def __html__(self):
"""
Returns the html representation of a string.
Allows interoperability with other template engines.
"""
return self | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
def prep_sequence(value: str) -> Iterable[str]:
"""Split a sequence string into its component items.
Flex `notes` attribute is semicolon-delimited; other sequences use commas.
Empty string input interpreted as null data; returns empty list.
"""
sep = ";" if ";" in val... | bigcode/self-oss-instruct-sc2-concepts |
def get_expression(text, begin, separator):
"""Find the end of a expression or statement
An expression or statement ends at a new-line or at the separator,
unless the new-line or separator is encountered inside a string-literal or
inside matching bracket pairs.
@param text The total text being pars... | bigcode/self-oss-instruct-sc2-concepts |
import json
def json_for(data):
"""
Serialize data to JSON.
"""
return json.dumps(data, indent=4, sort_keys=True) | bigcode/self-oss-instruct-sc2-concepts |
def create_fifo_queue(
env,
queue_name,
content_based_deduplication=False,
message_retention_period=None,
visibility_timeout=None,
redrive_policy=None,
):
"""
Create a new FIFO queue. Note that queue name has to end with ".fifo"
- "content_based_deduplication" turns on automatic con... | bigcode/self-oss-instruct-sc2-concepts |
def popget(d, key, default=None):
"""
Get the key from the dict, returning the default if not found.
Parameters
----------
d : dict
Dictionary to get key from.
key : object
Key to get from the dictionary.
default : object
Default to return if key is not found in dict... | bigcode/self-oss-instruct-sc2-concepts |
def is_even(x):
"""
takes an integer input
outputs true if int is even
else outputs false
"""
return x%2==0 | bigcode/self-oss-instruct-sc2-concepts |
def get_ui_confirmation(message: str):
"""
Get user confirmation to a message
:param message: Message displayed to the user
:type message: ``str``
:return: User answer: (True: yes False: no)
:rtype: :``bool``
"""
print(message + " y/n")
while 1:
answer = input()
if ... | bigcode/self-oss-instruct-sc2-concepts |
async def index():
""" returns index page """
return "see /docs for the api" | bigcode/self-oss-instruct-sc2-concepts |
from functools import reduce
import operator
def sum_seq(seq, fn=None):
"""Sum the elements seq[i], or fn(seq[i]) if fn is given.
Ex: sum_seq([1, 2, 3]) ==> 6; sum_seq(range(8), lambda x: 2**x) ==> 255"""
if fn:
seq = map(fn, seq)
return reduce(operator.add, seq, 0) | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def is_hat_shaped(learning_rates: List[float]):
"""
Check if the list of learning rates is "hat" shaped, i.e.,
increases then decreases
"""
# sufficient conditions:
# has both an increasing and decreasing segment
# decrease segment occurs after increasing segmen... | bigcode/self-oss-instruct-sc2-concepts |
def isdivisor(number: int, divisor: int) -> bool:
"""
判断一个数是否为约数
:param number: 被求数
:param divisor: 约数
"""
return (number % divisor) == 0 | bigcode/self-oss-instruct-sc2-concepts |
def is_subclass(obj, superclass):
"""Safely check if obj is a subclass of superclass."""
try:
return issubclass(obj, superclass)
except Exception:
return False | bigcode/self-oss-instruct-sc2-concepts |
def is_contributor(user):
"""Return whether the user is in the 'Registered as contributor' group."""
return (
user.is_authenticated and user.groups.filter(name="Registered as contributor").count() > 0
) | bigcode/self-oss-instruct-sc2-concepts |
def find_count_to_turn_out_to_all_zero_or_all_one(string):
"""
:param string: 0과 1을 포함하는 문자열
:return: 모든 1 또는 모든 0이 되기 위한 최소 변환 횟수
"""
count_to_zeros = 0
count_to_ones = 0
if string[0] == '0':
count_to_ones += 1
else:
count_to_zeros += 1
for i in range(len(string) ... | bigcode/self-oss-instruct-sc2-concepts |
def extract_initials(*forenames):
"""Return a list of initials for each name in the given forenames.
"""
initials = []
# To handle varargs
for forename in forenames:
# Allow polymorphism: forenames can be str or sequence of str
try:
names = forename.split()
except... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def join(row: List[List[str]]) -> List[str]:
"""Join together a row of puzzle pieces into a complete list of lines"""
res = []
for i in range(len(row[0])):
res.append('│')
for piece in row:
res[i] += piece[i]
return res | bigcode/self-oss-instruct-sc2-concepts |
def inv_to_dict(inventory):
"""Convert an inventory to a simple cost->number dict."""
return {pos.units.currency: pos.units.number for pos in inventory} | bigcode/self-oss-instruct-sc2-concepts |
def format_as_vars_file_param(pathname):
"""Accepts a pathname and returns a string formatted as a valid terraform var-file include argument"""
return "-var-file={pn}".format(pn=pathname) | bigcode/self-oss-instruct-sc2-concepts |
def word_capitalize(word: str) -> str:
"""Capitalize the first letter of every word within a sentence."""
return ' '.join(map(str.capitalize, word.split())) | bigcode/self-oss-instruct-sc2-concepts |
def make_line(move):
"""(str) -> str
Determines the line between two dots specified in the string <move>
The <move> parameter is one of '01', '12', '03' etc. representing a line
connecting the dots in the pattern;
0---1---2
| | |
3---4---5
| | |
6---7---8
... | bigcode/self-oss-instruct-sc2-concepts |
def get_entity_name(battle, entity):
"""
Determine the identifying string name of the given entity in the battle.
Arguments
---------
battle : Battle
The Battle instance representing the battle.
entity : CombatEntity, Player
The entity to determine the name of.
... | bigcode/self-oss-instruct-sc2-concepts |
import uuid
def get_random_id() -> str:
"""
Generate a random ID string. The random ID will start with the '_'
character.
"""
# It is very important that these random IDs NOT start with a number.
random_id = '_' + uuid.uuid4().hex
return random_id | bigcode/self-oss-instruct-sc2-concepts |
def encode_date(o):
""" Encodes a Python datetime.date object as an ECMA-262 compliant
date string."""
return o.isoformat() | bigcode/self-oss-instruct-sc2-concepts |
def format_discord_link(link: str, guild_id: int):
"""
Format a discord link to a channel or message
"""
link = link.lstrip("<").rstrip(">").rstrip("/")
for prefix in (
f"https://discord.com/channels/{guild_id}/",
f"https://www.discord.com/channels/{guild_id}/",
):
if li... | bigcode/self-oss-instruct-sc2-concepts |
def get_species(df):
"""Return species of top hit from input DataFrame
of Mash results."""
try:
species = df.sort_values("Mash-distance").loc[0, "species"]
return species
except KeyError:
print("Can't find the species in the input mash_dict!") | bigcode/self-oss-instruct-sc2-concepts |
def locus_tag(ncrna):
"""
Get the locus tag of the gene, if present.
"""
return ncrna.get("gene", {}).get("locusTag", None) | bigcode/self-oss-instruct-sc2-concepts |
import math
def printXYZDegrees(self):
"""Print X, Y, and Z components in degrees."""
return ("[%f, %f, %f]" % (math.degrees(self.x), math.degrees(self.y), math.degrees(self.z))) | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def fast_filter(msgs):
"""
Grabs an arbitrary subset of 100 messages from the stream.
Convenient for fast testing.
"""
return itertools.islice(msgs, 100, 1100, 10) | bigcode/self-oss-instruct-sc2-concepts |
def suspend_ha(fw_conn):
"""Suspend HA
Args:
fw_conn (PanDevice): A panos object for device
Returns:
results (Element): XML results from firewall
"""
command = ('<request><high-availability><state><suspend>'
'</suspend></state></high-availability></request>')
res... | bigcode/self-oss-instruct-sc2-concepts |
def round_half_integer(x):
""" Rounds number to nearest floating point half integer.
Args:
x (number): quantity to be rounded
Returns:
float: number rounded to (generally exact) integer or half integer
"""
return round(2*float(x))/2 | bigcode/self-oss-instruct-sc2-concepts |
def _temp_analyze_files(tmpdir):
"""Generate temporary analyze file pair."""
orig_img = tmpdir.join("orig.img")
orig_hdr = tmpdir.join("orig.hdr")
orig_img.open('w+').close()
orig_hdr.open('w+').close()
return str(orig_img), str(orig_hdr) | bigcode/self-oss-instruct-sc2-concepts |
def is_all_upper(s):
"""Returns True if the whole of the string s is upper case."""
return sum(c.isupper() for c in s) == len(s) | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def hash_password_hashlib(password: str) -> str:
"""encrypt user password using hashlib
Args:
password (str): user password
Returns:
str: password encrypted
"""
return hashlib.md5(password.encode('utf-8')).hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
def approx_eq(x, y, tolerance=1e-15):
"""Whether x is within tolerance of y."""
return abs(x - y) < tolerance | bigcode/self-oss-instruct-sc2-concepts |
import typing
def transform_any_str_list(data: typing.Any) -> typing.List[str]:
"""
Helper function for transforming any type to an list of strings split by "\n"
:param data: the data to transform
:return: the transformed data
"""
if type(data) == str:
return data.split("\n")
if ty... | bigcode/self-oss-instruct-sc2-concepts |
def node2feature(node_idx, data_shape):
"""Convert node index from CNN activation vector into 3 features including
index of channel, row and column position of the filter.
Return a tuple of (channel index, row index, column index).
"""
#data_size = {'conv1': [96, 55, 55],
# 'conv2': ... | bigcode/self-oss-instruct-sc2-concepts |
import itertools
def feature_engineering(df, cat_cols):
"""
This function is used for feature engineering
:param df: the pandas dataframe with train/test data
:param cat_cols: list of categorical columns
:return: dataframe with new features
"""
# this will create all 2-combinations of valu... | bigcode/self-oss-instruct-sc2-concepts |
def parabola_1D(xdata, a, b, c):
"""
Calculates a parabola of the form: a*(x-b)**2 + c
"""
return a*(xdata-b)**2 + c | bigcode/self-oss-instruct-sc2-concepts |
def remove_file_extension(file_name):
"""e.g.: remove_file_extension("hi.jpg") == "hi"
It does not mutate file_name (str is immutable anyway)
:param file_name: <str>
:return: it returns the file_name without the extension
"""
return file_name[:file_name.rindex('.')] | bigcode/self-oss-instruct-sc2-concepts |
import re
def get_assembly_line_pattern(stripped):
"""
Return regexp pattern used for matching regular assembly lines in the file.
Support for stripped and non-stripped versions.
Need to match non-stripped lines:
'0x00007ffff7fbf158 <+120>: and $0xfffffffffffffff8,%r12'
and stripped lines:
... | bigcode/self-oss-instruct-sc2-concepts |
def active_view(request, view_name):
"""
Sets an HTML class attribute depending on the selection.
:param request: HttpRequest
:param view_name: (str)
:return: (str) HTML class attribute
"""
resolve_view_name = getattr(request.resolver_match, 'view_name', None)
if resolve_view_name is ... | bigcode/self-oss-instruct-sc2-concepts |
def iso_format(datetime):
"""
Generates an ISO formatted datetime based on what the LaunchKey API expects.
This is a standard ISO datetime without microseconds.
:param datetime: datetime.datetime object
:return: ISO formatted string IE: 2017-10-03T22:50:15Z
"""
return datetime.strftime("%Y-%... | bigcode/self-oss-instruct-sc2-concepts |
import time
def epoch_milliseconds(d):
"""Convert a datetime to a number of milliseconds since the epoch."""
return time.mktime(d.timetuple()) * 1000 | bigcode/self-oss-instruct-sc2-concepts |
def get_number_alien_rows(game_settings, starship_height, alien_height):
"""Returns the number of alien rows."""
available_space_y = game_settings.screen_height - (3 * alien_height) - 3 * starship_height
number_alien_rows = int(available_space_y / (2 * alien_height))
return number_alien_rows | bigcode/self-oss-instruct-sc2-concepts |
def confirm_delete(profile):
"""Prompt user to enter Y or N (case-insensitive) to continue."""
answer = ""
while answer not in ["y", "n"]:
answer = input("Delete PROFILE '%s' [Y/N]? " % profile).lower()
return answer == "y" | bigcode/self-oss-instruct-sc2-concepts |
def TourTypeDayShift_idx_rule(M):
"""
Index is (start window, tour type, shift length, day, week)
:param M: Model
:return: Constraint index (list of tuples)
"""
return [(i, t, k, j, w) for i in M.WINDOWS
for t in M.activeTT
for k in M.tt_length_x[t]
for j in... | bigcode/self-oss-instruct-sc2-concepts |
def Mc_eta_m1_m2(m1, m2):
"""
Computes the symmetric mass-ratio (eta)
and chirp mass (Mc) from the component masses
input: m1, m2
output: Mc, eta
"""
Mc = (m1*m2)**(3./5.)/(m1+m2)**(1./5.)
eta = m1*m2/(m1+m2)**2
return Mc, eta | bigcode/self-oss-instruct-sc2-concepts |
def is_native(s):
"""Return True for native strings, i.e. for str on Py2 and Py3."""
return isinstance(s, str) | bigcode/self-oss-instruct-sc2-concepts |
import json
def example_json41(example_json_file41):
"""Load the DataCite v4.1 full example into a dict."""
return json.loads(example_json_file41) | bigcode/self-oss-instruct-sc2-concepts |
def add_depend_on(status, name):
"""
Add the names of the packages that depend on the current package.
Parameters
status : dict, main package contents
name : str, current package name
"""
# list for those that dependends on this package
depon = []
for key in status:
# try bl... | bigcode/self-oss-instruct-sc2-concepts |
def MakeGray(rgbTuple, factor, maskColour):
"""
Make a pixel grayed-out. If the pixel matches the `maskColour`, it won't be
changed.
:param `rgbTuple`: a tuple representing a pixel colour;
:param `factor`: a graying-out factor;
:param `maskColour`: a colour mask.
"""
if rgbTuple != mas... | bigcode/self-oss-instruct-sc2-concepts |
async def async_api_reportstate(hass, config, directive, context):
"""Process a ReportState request."""
return directive.response(name="StateReport") | bigcode/self-oss-instruct-sc2-concepts |
def rotate_axes(xs, ys, zs, zdir):
"""
Reorder coordinates so that the axes are rotated with zdir along
the original z axis. Prepending the axis with a '-' does the
inverse transform, so zdir can be x, -x, y, -y, z or -z
"""
if zdir == 'x':
return ys, zs, xs
elif zdir == '-x':
... | bigcode/self-oss-instruct-sc2-concepts |
def CubicIn(start=0.0, finish=1.0):
"""
Cubically increasing, starts very slow : f(x) = x^3
"""
def cubic_in_easing(sprite, delta):
return start + (delta * delta * delta) * (finish - start)
return cubic_in_easing | bigcode/self-oss-instruct-sc2-concepts |
def get_message(tweet):
"""
Get the message attribute on a Tweet object.
The attribute available depends on the parameters on the query to Twitter.
"""
try:
message = tweet.full_text
except AttributeError:
message = tweet.text
return message | bigcode/self-oss-instruct-sc2-concepts |
import math
def magnitude(v):
"""
Get the magnitude of a vector.
"""
return math.sqrt(sum(v[i] * v[i] for i in range(len(v)))) | bigcode/self-oss-instruct-sc2-concepts |
def pathFromFileSystem(fspath):
"""
Turn a local filesystem path into a package file path.
(Inside the package metadata, we always store paths in unix format)
"""
return fspath.replace("\\", "/") | bigcode/self-oss-instruct-sc2-concepts |
def dropLabels(collection, feature_type):
"""
Drop labels and return features + labels separately
--args
collection (pandas DF): dataset containing features + labels
feature_type (str): determines which labels to drop
--returns
labels (pandas series): series containing all label names
collection_features (pan... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
from pathlib import Path
import yaml
def load_config(*args: Union[str, Path]) -> dict:
"""
Load config yaml files from path.
:param args: path(s) of the file(s) containing configuration parameters
"""
config = {}
for filepath in args:
with open(filepath) as fil... | bigcode/self-oss-instruct-sc2-concepts |
import collections
import json
def seq_length_to_json(df):
"""Convert sequence length distribution to JSON object.
Args:
df: DataFrame containing a subset of sequence length.
Returns:
String: A JSON-formatted string for visualization of sequence length distribution.
"""
json... | bigcode/self-oss-instruct-sc2-concepts |
import platform
import unittest
def _requires_unix_version(sysname, min_version):
"""Decorator raising SkipTest if the OS is `sysname` and the version is less
than `min_version`.
For example, @_requires_unix_version('FreeBSD', (7, 2)) raises SkipTest if
the FreeBSD version is less than 7.2.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def indentation(level, word):
"""
Returns a string formed by word repeated n times.
"""
return ''.join([level * word]) | bigcode/self-oss-instruct-sc2-concepts |
def find_elements_that_sum_to_2020(input: list[int]) -> tuple[int, int]:
"""Find elements of the input that sum to 2020."""
for value in input:
remainder = 2020 - value
if remainder in input:
return value, remainder
raise ValueError("unable to find 2 elements that sum to 202... | bigcode/self-oss-instruct-sc2-concepts |
def validate_strings(*args):
"""
Checks that all given arguments have a string type (e.g. str, basestring,
unicode etc)
Args:
*args: values to be validated.
Returns:
bool: True if all arguments are of a string type. False otherwise.
"""
for arg in args:
if not isins... | bigcode/self-oss-instruct-sc2-concepts |
def forceIterable(x):
"""Forces a non iterable object into a list, otherwise returns itself
:param list x: the object
:return: object as a list
:rtype: list"""
if not getattr(x, '__iter__', False):
return list([x])
else:
return x | bigcode/self-oss-instruct-sc2-concepts |
def strip_html(response):
"""
Strips HTML header/footer from a response.
This is useful when trying to embed HTML into
an existing page through use of an external API.
"""
return (
response.content.decode("utf-8")
.replace("<!DOCTYPE html>\n\n<html>", "")
.replace("</html... | bigcode/self-oss-instruct-sc2-concepts |
import torch
def scatter(tensor, devices, chunk_sizes=None, dim=0, streams=None):
"""Scatters tensor across multiple GPUs.
Arguments:
tensor (Tensor): tensor to scatter.
devices (Iterable[int]): iterable of ints, specifying among which
devices the tensor should be scattered.
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Tuple
def calculate_unmatched_exposure(ub: list, ul: list) -> Tuple:
"""Calculates worse-case exposure based on list
of (price, size)
returns the tuple (profit_if_win, profit_if_lose)
The worst case profit_if_win arises if all lay bets are matched and the selection wins.
The wo... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def alternative_hash(value):
"""Quick way of doing a hash.
This used to be hash(), but in Python 3 it is seeded and returns
different values.
Security is not an issue here so md5 is used as its cheap.
"""
return hashlib.md5(repr(value).encode('utf-8')).hexdigest() | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
import click
def base_vwq_url_option(command: Callable[..., None]) -> Callable[..., None]:
"""
An option decorator for choosing the base VWQ URL.
"""
click_option_function = click.option(
'--base-vwq-url',
type=click.STRING,
default='https://cloudrec... | bigcode/self-oss-instruct-sc2-concepts |
import getpass
def handle_credentials(email,password,prompt="Password: "):
"""
Sort out email and password for accessing Galaxy
Arguments:
email (str): Galaxy e-mail address corresponding to the user
password (str): password of Galaxy account corresponding to
email address; if None th... | bigcode/self-oss-instruct-sc2-concepts |
import smtplib
def get_server_reference(
username, smtp_password, aws_smtp_endpoint, aws_smtp_port, **kwargs):
"""
Returns smtplib.smtp reference using the specified parameters.
Call sendmail on the returned reference to send emails.
See the example configuration file for explanations on wher... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Iterable
from typing import AnyStr
from typing import Set
def prepare_selected_fields(fields: Iterable[AnyStr], default: Set[AnyStr]) -> Set[AnyStr]:
"""Check for selected fields of the query.
:param fields: Iterable object with all field names that should be selected by the query
:par... | 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.