Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given snippet: <|code_start|>
async def run_regularly(ctx):
print('run foo job at 9.12am, 12.12pm and 6.12pm')
class WorkerSettings:
cron_jobs = [
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from arq import cron
and context:
# Path: arq/cron.py
# def cron(
# corou... | cron(run_regularly, hour={9, 12, 18}, minute=12) |
Given the code snippet: <|code_start|>
async def the_task(ctx):
print('this is the tasks, delay since enqueueing:', datetime.now() - ctx['enqueue_time'])
async def main():
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
from datetime import datetime, timedelta
from arq import... | redis = await create_pool(RedisSettings()) |
Next line prediction: <|code_start|>
async def the_task(ctx):
print('this is the tasks, delay since enqueueing:', datetime.now() - ctx['enqueue_time'])
async def main():
<|code_end|>
. Use current file imports:
(import asyncio
from datetime import datetime, timedelta
from arq import create_pool
from arq.connecti... | redis = await create_pool(RedisSettings()) |
Based on the snippet: <|code_start|>
async def download_content(ctx, url):
session: ClientSession = ctx['session']
async with session.get(url) as response:
content = await response.text()
print(f'{url}: {content:.80}...')
return len(content)
async def startup(ctx):
ctx['session'] = Clie... | redis = await create_pool(RedisSettings()) |
Given the code snippet: <|code_start|>
async def download_content(ctx, url):
session: ClientSession = ctx['session']
async with session.get(url) as response:
content = await response.text()
print(f'{url}: {content:.80}...')
return len(content)
async def startup(ctx):
ctx['session'] = Cl... | redis = await create_pool(RedisSettings()) |
Given snippet: <|code_start|>
# requires `pip install devtools`, used for pretty printing of job info
async def the_task(ctx):
print('running the task')
return 42
async def main():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
from arq import create_pool
f... | redis = await create_pool(RedisSettings()) |
Given snippet: <|code_start|>
# requires `pip install devtools`, used for pretty printing of job info
async def the_task(ctx):
print('running the task')
return 42
async def main():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
from arq import create_pool
f... | redis = await create_pool(RedisSettings()) |
Given the following code snippet before the placeholder: <|code_start|>
async def the_task(ctx):
print('running the task with id', ctx['job_id'])
async def main():
<|code_end|>
, predict the next line using imports from the current file:
import asyncio
from arq import create_pool
from arq.connections import Redi... | redis = await create_pool(RedisSettings()) |
Here is a snippet: <|code_start|>
async def the_task(ctx):
print('running the task with id', ctx['job_id'])
async def main():
<|code_end|>
. Write the next line using the current file imports:
import asyncio
from arq import create_pool
from arq.connections import RedisSettings
and context from other files:
# P... | redis = await create_pool(RedisSettings()) |
Continue the code snippet: <|code_start|>
num_topics : int
The number of latent spaces to learn
alpha_zh : float
The value of the alpha_zh hyperparameter
beta_zs : float
The value of the beta_zs (beta) hyperaparameter
kernel : Kernel object
The kernel to use
resid... | dataio.initialize_trace(trace_fpath, num_topics, num_iter, \ |
Predict the next line after this snippet: <|code_start|>#-*- coding: utf8
'''
Unit tests for the dynamic learning model.
'''
from __future__ import division, print_function
def test_correlate_all():
tstamps, Trace, previous_stamps, Count_zh, Count_sz, count_h, count_z, \
prob_topics_aux, Theta_zh,... | dataio.initialize_trace(files.SIZE10, 2, 10) |
Given the following code snippet before the placeholder: <|code_start|>#-*- coding: utf8
'''
Unit tests for the dynamic learning model.
'''
from __future__ import division, print_function
def test_correlate_all():
tstamps, Trace, previous_stamps, Count_zh, Count_sz, count_h, count_z, \
prob_topics... | C = dynamic.correlate_counts(Count_zh, Count_sz, count_h, count_z, .1, \ |
Based on the snippet: <|code_start|>#-*- coding: utf8
'''
Unit tests for the main sherlock model.
'''
from __future__ import division, print_function
def test_full_learn_null():
kernel = NoopKernel()
kernel.build(1, 20, np.zeros(0, dtype='d'))
<|code_end|>
, predict the immediate next line with the help of... | rv = learn.fit(files.SIZE1K, 20, .1, .1, kernel, \ |
Given snippet: <|code_start|>#-*- coding: utf8
'''
Unit tests for the main sherlock model.
'''
from __future__ import division, print_function
def test_initialize():
tstamps, Trace, previous_stamps, Count_zh, Count_oz, count_h, count_z, \
prob_topics_aux, Theta_zh, Psi_oz, hyper2id, obj2id = \
<|cod... | dataio.initialize_trace(files.SIZE10, 2, 10) |
Here is a snippet: <|code_start|>
router = routers.SimpleRouter(trailing_slash=False)
router.register(
r'account/credit-cards',
CreditCardViewSet,
basename='billing_creditcard'
)
urlpatterns = router.urls + [
<|code_end|>
. Write the next line using the current file imports:
from django.urls import path... | path('account', AccountView.as_view(), name='billing_account'), |
Given the following code snippet before the placeholder: <|code_start|>
router = routers.SimpleRouter(trailing_slash=False)
router.register(
r'account/credit-cards',
<|code_end|>
, predict the next line using imports from the current file:
from django.urls import path
from rest_framework import routers
from .vie... | CreditCardViewSet, |
Given the following code snippet before the placeholder: <|code_start|>
router = routers.SimpleRouter(trailing_slash=False)
router.register(
r'account/credit-cards',
CreditCardViewSet,
basename='billing_creditcard'
)
urlpatterns = router.urls + [
path('account', AccountView.as_view(), name='billing_a... | pay_open_invoices_with_registered_credit_cards, |
Given the following code snippet before the placeholder: <|code_start|>
class PSPTest(TestCase):
def setUp(self):
register(MyPSP())
self.psp_credit_card = MyPSPCreditCard.objects.create(token='atoken')
self.psp_payment = MyPSPPayment.objects.create(payment_ref='apaymentref')
def tearD... | with raises(PreconditionError, match='Can only charge positive amounts'): |
Given the following code snippet before the placeholder: <|code_start|>
class PSPTest(TestCase):
def setUp(self):
register(MyPSP())
self.psp_credit_card = MyPSPCreditCard.objects.create(token='atoken')
self.psp_payment = MyPSPPayment.objects.create(payment_ref='apaymentref')
def tearD... | success, payment_psp_object = charge_credit_card(self.psp_credit_card, Money(10, 'CHF'), 'a charge') |
Predict the next line after this snippet: <|code_start|>
class PSPTest(TestCase):
def setUp(self):
register(MyPSP())
self.psp_credit_card = MyPSPCreditCard.objects.create(token='atoken')
self.psp_payment = MyPSPPayment.objects.create(payment_ref='apaymentref')
def tearDown(self):
... | success, refund_psp_object = refund_payment(self.psp_payment, Money(3, 'CHF'), 'a refund') |
Predict the next line after this snippet: <|code_start|>
class PSPTest(TestCase):
def setUp(self):
register(MyPSP())
self.psp_credit_card = MyPSPCreditCard.objects.create(token='atoken')
self.psp_payment = MyPSPPayment.objects.create(payment_ref='apaymentref')
def tearDown(self):
<|co... | unregister(MyPSP()) |
Using the snippet: <|code_start|>
class PSPTest(TestCase):
def setUp(self):
register(MyPSP())
<|code_end|>
, determine the next line of code. You have imports:
from django.test import TestCase
from moneyed import Money
from pytest import raises
from billing.psp import PreconditionError, charge_credit_car... | self.psp_credit_card = MyPSPCreditCard.objects.create(token='atoken') |
Predict the next line after this snippet: <|code_start|>
class PSPTest(TestCase):
def setUp(self):
register(MyPSP())
self.psp_credit_card = MyPSPCreditCard.objects.create(token='atoken')
<|code_end|>
using the current file's imports:
from django.test import TestCase
from moneyed import Money
fro... | self.psp_payment = MyPSPPayment.objects.create(payment_ref='apaymentref') |
Using the snippet: <|code_start|>
def set_debug(logger_name):
logger = logging.getLogger(logger_name)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
logger = structlog.get_logger()
class Command(BaseCommand):
help = """Displays all paid and cancelled invoices where due ... | audit_closed_invoices() |
Continue the code snippet: <|code_start|>class ChargeAlreadyCancelledError(Exception):
pass
def cancel_charge(charge_id: str) -> None:
"""
Cancels an existing charge.
If the charge was already cancelled then an Exception is raised.
If it is not in an invoice then the charge is deleted,
other... | add_charge( |
Predict the next line after this snippet: <|code_start|>
logger = get_logger()
REVERSAL_PRODUCT_CODE = 'REVERSAL'
class ChargeAlreadyCancelledError(Exception):
pass
def cancel_charge(charge_id: str) -> None:
"""
Cancels an existing charge.
If the charge was already cancelled then an Exception is ... | charge = Charge.all_charges.get(pk=charge_id) |
Next line prediction: <|code_start|>
logger = get_logger()
def deactivate(credit_card_id: str) -> None:
"""
Deactivates a credit card.
"""
logger.info('deactivating-credit-card', credit_card_id=credit_card_id)
with transaction.atomic():
<|code_end|>
. Use current file imports:
(from django.db im... | cc = CreditCard.objects.get(pk=credit_card_id) |
Predict the next line for this snippet: <|code_start|>
class TotalTest(TestCase):
def test_unique_currency(self):
with raises(ValueError):
<|code_end|>
with the help of current file imports:
from unittest import TestCase
from moneyed import Money
from pytest import raises
from billing.total import Tota... | Total([Money(0, 'USD'), Money(0, 'USD')]) |
Next line prediction: <|code_start|> help = """For all accounts with pending invoices: tries to match unassigned funds to invoices.
Pass -v 2 to see sql queries.
"""
def add_arguments(self, parser):
parser.add_argument('--dry-run', action='store_true',
... | paid_invoices = assign_funds_to_account_pending_invoices(account_id=account.id) |
Using the snippet: <|code_start|>
def set_debug(logger_name):
logger = logging.getLogger(logger_name)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
logger = structlog.get_logger()
class Command(BaseCommand):
help = """For all accounts with pending invoices: tries to ma... | accounts = Account.objects.open().with_pending_invoices().only('id') |
Given the following code snippet before the placeholder: <|code_start|>
class MyPSP(PSP):
"""
Always succeeds, and remembers how it was invoked (like a mock)
"""
def __init__(self):
self.charges = []
self.refunds = []
def model_classes(self):
<|code_end|>
, predict the next line ... | return [MyPSPPayment, MyPSPCreditCard] |
Given snippet: <|code_start|>
class MyPSP(PSP):
"""
Always succeeds, and remembers how it was invoked (like a mock)
"""
def __init__(self):
self.charges = []
self.refunds = []
def model_classes(self):
<|code_end|>
, continue by predicting the next line. Consider current file impo... | return [MyPSPPayment, MyPSPCreditCard] |
Continue the code snippet: <|code_start|>
class MyPSP(PSP):
"""
Always succeeds, and remembers how it was invoked (like a mock)
"""
def __init__(self):
self.charges = []
self.refunds = []
def model_classes(self):
return [MyPSPPayment, MyPSPCreditCard]
def charge_cred... | refund = MyPSPRefund.objects.create(refund_ref='refund_12345') |
Using the snippet: <|code_start|>#!/usr/bin/env python
from __future__ import division
try:
MATPLOTLIB_LOADED = True
matplotlib.use('Agg')
except ImportError:
MATPLOTLIB_LOADED = False
def compute_largest_radius_distance(X, rad, adjacency_method, adjacency_kwds):
print('computing distance matrix...'... | dists = compute_adjacency_matrix(X,adjacency_method,**adjacency_kwds) |
Continue the code snippet: <|code_start|> calculated_DL_list.append(rr.compute_gradient())
for idx,grad in enumerate(var.grad_list):
rr.grad = grad
rr.Y = np.copy(var.Y_list[idx])
rr.loss = var.loss_list[idx]
if if_epsilon:
... | return gen_data('eps_halfdome','whole_eps') |
Predict the next line after this snippet: <|code_start|>
def _regression_test(if_epsilon):
def _test_deco(func):
@wraps(func)
def wrapper():
test_dict = func()
<|code_end|>
using the current file's imports:
from megaman.relaxation import *
from functools import wraps
from .utils impo... | var = Bunch(test_dict) |
Given the code snippet: <|code_start|>
def test_pairs(self):
np.testing.assert_array_equal(
self.pairs, self.correct_pairs,
err_msg='Sorted pairs should be the same.'
)
def test_A(self):
testing_S = self.A.dot(self.Y)
np.testing.assert_allclose(
... | return generate_toy_laplacian(n=200) |
Using the snippet: <|code_start|># Author: Yu-Chia Chen <yuchaz@uw.edu>
# LICENSE: Simplified BSD https://github.com/mmp2/megaman/blob/master/LICENSE
@_check_backend('plotly')
def plot_with_plotly( embedding, rieman_metric, nstd=2,
color_by_ratio=True, if_ellipse=False ):
sigma_norms = get_t... | scatter_pt = scatter_plot3d_plotly(embedding, coloring=sigma_norms, |
Given the following code snippet before the placeholder: <|code_start|># Author: Yu-Chia Chen <yuchaz@uw.edu>
# LICENSE: Simplified BSD https://github.com/mmp2/megaman/blob/master/LICENSE
@_check_backend('plotly')
def plot_with_plotly( embedding, rieman_metric, nstd=2,
color_by_ratio=True, if_el... | ellipses_pt = covar_plotter3d_plotly(embedding, |
Here is a snippet: <|code_start|> nbrs = list()
for ii in range(len(sample)):
w = np.array(A[sample[ii],:].todense()).flatten()
p = w / np.sum(w)
nbrs.append(np.where(p > 0)[0])
Ps.append(p[nbrs[ii]])
return Ps, nbrs
def project_tangent(X, p, nbr, d):
Z = (X[nbr, :] - np.... | H = riemann_metric_lazy(X_tangent, sample, L, d)[0] |
Given the following code snippet before the placeholder: <|code_start|> dist = 0.0
nsum = n
for i in range(n):
p = PS[i]
nbr = nbrs[i]
if len(nbr) > 1:
X_t = project_tangent(X, p, nbr, d)
X_tangent = X.copy()
X_tangent = X_tangent[:, :d]
... | A = compute_affinity_matrix(D, 'gaussian', radius=h) |
Predict the next line for this snippet: <|code_start|> for i in range(n):
p = PS[i]
nbr = nbrs[i]
if len(nbr) > 1:
X_t = project_tangent(X, p, nbr, d)
X_tangent = X.copy()
X_tangent = X_tangent[:, :d]
X_tangent[nbr, :] = X_t # rmetric only depen... | L = compute_laplacian_matrix(A, method='geometric', scaling_epps=h) |
Continue the code snippet: <|code_start|># Author: Yu-Chia Chen <yuchaz@uw.edu>
#
#
# Transformed 2D patches to 3D after:
# Till Hoffmann <t.hoffmann13@imperial.ac.uk>
# https://stackoverflow.com/questions/18228966/how-can-matplotlib-2d-patches-be-transformed-to-3d-with-arbitrary-normals
# LICENSE: Simp... | @_check_backend('matplotlib') |
Predict the next line after this snippet: <|code_start|> assert np.all(if_symmetric), 'One or more Lk is not symmetric'
def _test_other_zeros(self):
pass
# You do not need this since if nonzero terms is 3n-2 and Lk row Lk col Lk diag are close.
# Then this is automatically become tru... | return generate_toy_laplacian() |
Based on the snippet: <|code_start|> return dumper.represent_scalar(YAML_STRING_ID, data, style='>')
def literal_unicode_representer(dumper, data):
return dumper.represent_scalar(YAML_STRING_ID, data, style='|')
def double_quoted_unicode_representer(dumper, data):
tag = getattr(data, 'tag', YAML_STRING_I... | return dumper.represent_mapping(YAML_DICT_ID, six.iteritems(data), |
Continue the code snippet: <|code_start|>
"""
YAML representers
"""
def unicode_representer(dumper, data):
tag = getattr(data, 'tag', YAML_STRING_ID)
return yaml.ScalarNode(tag=tag, value=data)
def folded_unicode_representer(dumper, data):
return dumper.represent_scalar(YAML_STRING_ID, data, style='>')
... | return dumper.represent_sequence(YAML_LIST_ID, data, flow_style=False) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
from __future__ import absolute_import
"""
YAML representers
"""
def unicode_representer(dumper, data):
<|code_end|>
, determine the next line of code. You have imports:
import six
import yaml
from openformats.formats.yaml.constants import (YAML_DICT_ID, Y... | tag = getattr(data, 'tag', YAML_STRING_ID) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
"""
Wrapper classes to represent various styled objects
in a dictionary for generating YAML content
"""
class plain_unicode(six.text_type): # noqa: N801
def __new__(self, value, tag=None):
self = super(plain_unicode, self).__new__(self, val... | self.tag = tag or YAML_STRING_ID |
Given the code snippet: <|code_start|> ptr: ^
destination: ['<string name="foo">', 'ee8cc2abd5abd5a87cd784be_tr']
>>> transcriber.copy_until(source.index("</string>") +
... len("</string>"))
source:... | self.newline_type = find_newline_type(self.source) |
Given snippet: <|code_start|>
>>> transcriber.copy_until(source.index("</string>") +
... len("</string>"))
source: <string name="foo">hello world</string>
ptr: ^
destination: ['<string... | self.source = force_newline_type(self.source, 'UNIX') |
Predict the next line for this snippet: <|code_start|> _RULES_ATOI = {
'zero': 0,
'one': 1,
'two': 2,
'few': 3,
'many': 4,
'other': 5
}
EXTRACTS_RAW = True
# Use this flag for handlers whose the content should be processed as
# binary and not be conve... | raise RuleError(msg) |
Next line prediction: <|code_start|>
urlpatterns = [
url(r'^$', MainView.as_view(), name="testbed_home"),
url(r'^(?P<payload_hash>\w{32})$', MainView.as_view(),
name="testbed_main"),
<|code_end|>
. Use current file imports:
(from django.conf.urls import url
from django.views.decorators.csrf import cs... | url(r'^api/$', csrf_exempt(ApiView.as_view()), name="testbed_api"), |
Given the following code snippet before the placeholder: <|code_start|>
urlpatterns = [
url(r'^$', MainView.as_view(), name="testbed_home"),
url(r'^(?P<payload_hash>\w{32})$', MainView.as_view(),
name="testbed_main"),
url(r'^api/$', csrf_exempt(ApiView.as_view()), name="testbed_api"),
<|code_end|>... | url(r'^save/$', SaveView.as_view(), name="testbed_save") |
Continue the code snippet: <|code_start|>
return icu_string
def _validate_plural_content_format(self, key, serialized_strings, all_matches):
"""
Make sure the serialized content is properly formatted
as one or more pluralized strings.
:param key: the string key
{... | raise ParseError( |
Given snippet: <|code_start|> is False, a ParseError will be raised on parse()
"""
self.allow_numeric_plural_values = allow_numeric_plural_values
def parse(self, key, value):
"""
Parse a string that follows a subset of the the ICU message format
and return an ICUS... | ensure_unicode( |
Given the code snippet: <|code_start|> node.start_mark.index = node.end_mark.index - len(anchor_value) \
+ leading_spaces
return node
def _is_custom_tag(self, tag):
"""
Check whether a value is tagged with a custom type.
Detect custom tags, like:
... | raise ParseError( |
Given the code snippet: <|code_start|>yaml.add_representer(six.text_type, unicode_representer)
yaml.add_representer(plain_unicode, unicode_representer)
yaml.add_representer(six.binary_type, unicode_representer)
yaml.add_representer(folded_unicode, folded_unicode_representer)
yaml.add_representer(literal_unicode, litera... | ensure_unicode(r'(?:#.*\r?\n\s*)+$') |
Predict the next line after this snippet: <|code_start|> Check whether a value is tagged with a custom type.
Detect custom tags, like:
`foo: !bar test`
`foo: !xml "<bar>Bar</bar>"`
Built-in types, indicated by a `!!` prefix, will not be matched. We
can't preserve ... | if value_node.tag == YAML_BINARY_ID: |
Here is a snippet: <|code_start|>yaml.add_representer(BlockStyleOrderedDict,
block_style_ordered_dict_representer)
yaml.add_representer(FlowStyleOrderedDict,
flow_style_ordered_dict_representer)
Node = namedtuple("Node", ['value', 'start', 'end', 'style', 'tag'])
class TxYa... | YAML_STRING_ID, u'', event.start_mark, event.end_mark |
Given snippet: <|code_start|>from __future__ import absolute_import
yaml.add_representer(six.text_type, unicode_representer)
yaml.add_representer(plain_unicode, unicode_representer)
yaml.add_representer(six.binary_type, unicode_representer)
yaml.add_representer(folded_unicode, folded_unicode_representer)
yaml.add_... | yaml.add_representer(BlockList, block_list_representer) |
Using the snippet: <|code_start|>from __future__ import absolute_import
yaml.add_representer(six.text_type, unicode_representer)
yaml.add_representer(plain_unicode, unicode_representer)
yaml.add_representer(six.binary_type, unicode_representer)
yaml.add_representer(folded_unicode, folded_unicode_representer)
yaml.... | yaml.add_representer(BlockStyleOrderedDict, |
Given the code snippet: <|code_start|>from __future__ import absolute_import
yaml.add_representer(six.text_type, unicode_representer)
yaml.add_representer(plain_unicode, unicode_representer)
yaml.add_representer(six.binary_type, unicode_representer)
yaml.add_representer(folded_unicode, folded_unicode_representer)
... | yaml.add_representer(FlowList, flow_list_representer) |
Next line prediction: <|code_start|>from __future__ import absolute_import
yaml.add_representer(six.text_type, unicode_representer)
yaml.add_representer(plain_unicode, unicode_representer)
yaml.add_representer(six.binary_type, unicode_representer)
yaml.add_representer(folded_unicode, folded_unicode_representer)
ya... | yaml.add_representer(FlowStyleOrderedDict, |
Given snippet: <|code_start|>from __future__ import absolute_import
yaml.add_representer(six.text_type, unicode_representer)
yaml.add_representer(plain_unicode, unicode_representer)
yaml.add_representer(six.binary_type, unicode_representer)
yaml.add_representer(folded_unicode, folded_unicode_representer)
yaml.add_... | yaml.add_representer(double_quoted_unicode, |
Using the snippet: <|code_start|>from __future__ import absolute_import
yaml.add_representer(six.text_type, unicode_representer)
yaml.add_representer(plain_unicode, unicode_representer)
yaml.add_representer(six.binary_type, unicode_representer)
<|code_end|>
, determine the next line of code. You have imports:
imp... | yaml.add_representer(folded_unicode, folded_unicode_representer) |
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import
yaml.add_representer(six.text_type, unicode_representer)
yaml.add_representer(plain_unicode, unicode_representer)
yaml.add_representer(six.binary_type, unicode_representer)
yaml.add_representer(folded_unicode, folded_unico... | yaml.add_representer(literal_unicode, literal_unicode_representer) |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import absolute_import
yaml.add_representer(six.text_type, unicode_representer)
yaml.add_representer(plain_unicode, unicode_representer)
yaml.add_representer(six.binary_type, unicode_representer)
yaml.add_representer(folded_unic... | yaml.add_representer(single_quoted_unicode, |
Here is a snippet: <|code_start|>from __future__ import absolute_import
yaml.add_representer(six.text_type, unicode_representer)
yaml.add_representer(plain_unicode, unicode_representer)
yaml.add_representer(six.binary_type, unicode_representer)
yaml.add_representer(folded_unicode, folded_unicode_representer)
yaml.... | yaml.add_representer(BlockList, block_list_representer) |
Predict the next line for this snippet: <|code_start|>from __future__ import absolute_import
yaml.add_representer(six.text_type, unicode_representer)
yaml.add_representer(plain_unicode, unicode_representer)
yaml.add_representer(six.binary_type, unicode_representer)
yaml.add_representer(folded_unicode, folded_unico... | block_style_ordered_dict_representer) |
Given snippet: <|code_start|>from __future__ import absolute_import
yaml.add_representer(six.text_type, unicode_representer)
yaml.add_representer(plain_unicode, unicode_representer)
yaml.add_representer(six.binary_type, unicode_representer)
yaml.add_representer(folded_unicode, folded_unicode_representer)
yaml.add_... | double_quoted_unicode_representer) |
Predict the next line after this snippet: <|code_start|>from __future__ import absolute_import
yaml.add_representer(six.text_type, unicode_representer)
yaml.add_representer(plain_unicode, unicode_representer)
yaml.add_representer(six.binary_type, unicode_representer)
yaml.add_representer(folded_unicode, folded_uni... | yaml.add_representer(FlowList, flow_list_representer) |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import absolute_import
yaml.add_representer(six.text_type, unicode_representer)
yaml.add_representer(plain_unicode, unicode_representer)
yaml.add_representer(six.binary_type, unicode_representer)
yaml.add_representer(folded_unic... | flow_style_ordered_dict_representer) |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import absolute_import
yaml.add_representer(six.text_type, unicode_representer)
yaml.add_representer(plain_unicode, unicode_representer)
yaml.add_representer(six.binary_type, unicode_representer)
<|code_end|>
, predict the next ... | yaml.add_representer(folded_unicode, folded_unicode_representer) |
Given snippet: <|code_start|>from __future__ import absolute_import
yaml.add_representer(six.text_type, unicode_representer)
yaml.add_representer(plain_unicode, unicode_representer)
yaml.add_representer(six.binary_type, unicode_representer)
yaml.add_representer(folded_unicode, folded_unicode_representer)
<|code_en... | yaml.add_representer(literal_unicode, literal_unicode_representer) |
Continue the code snippet: <|code_start|>from __future__ import absolute_import
yaml.add_representer(six.text_type, unicode_representer)
yaml.add_representer(plain_unicode, unicode_representer)
yaml.add_representer(six.binary_type, unicode_representer)
yaml.add_representer(folded_unicode, folded_unicode_represente... | yaml.add_representer(OrderedDict, ordered_dict_representer) |
Continue the code snippet: <|code_start|>from __future__ import absolute_import
yaml.add_representer(six.text_type, unicode_representer)
yaml.add_representer(plain_unicode, unicode_representer)
yaml.add_representer(six.binary_type, unicode_representer)
yaml.add_representer(folded_unicode, folded_unicode_represente... | single_quoted_unicode_representer) |
Continue the code snippet: <|code_start|> self.handler = Handler()
def tearDown(self):
self.handler = None
def test_get_rule_number_returns(self):
rules = {
'zero': 0,
'one': 1,
'two': 2,
'few': 3,
'many': 4,
'other... | self.assertRaises(RuleError, self.handler.get_rule_string, 50) |
Given the following code snippet before the placeholder: <|code_start|>
class OpenStringTestCase(TestCase):
def test_singular_string_is_non_plural(self):
random_string = generate_random_string()
<|code_end|>
, predict the next line using imports from the current file:
from hashlib import md5
from random... | open_string = OpenString('test', random_string) |
Using the snippet: <|code_start|> replace(u"<", "<").\
replace(u"__TX__OPENING__TAG__", u"<tx").\
replace(u"__TX__CLOSING__TAG__", u"</tx>")
@classmethod
def parse_paragraph(cls, paragraph, rels_soup):
paragraph_text = []
text_elements = paragraph.find_all(... | except MissingParentError: |
Predict the next line after this snippet: <|code_start|> # open an a tag
text = u'<tx href="{}">{}'.format(
hyperlink_url, text
)
open_hyperlink = hyperlink_url
if not hyperlink_url and open_hyperlink:
# clos... | open_string = OpenString( |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
"""
This file contains the SpacewalkAPIClient and
depending exception classes
"""
try:
except ImportError:
<|code_end|>
, generate the next line using the imports in this file:
import logging
from .base import BaseConnector
from ..exceptions import (AP... | class SpacewalkAPIClient(BaseConnector): |
Given the following code snippet before the placeholder: <|code_start|> def _connect(self):
"""
This function establishes a connection to Spacewalk.
"""
#set api session and key
try:
self._session = Server(self.url)
self.api_key = self._session.auth.log... | raise APILevelNotSupportedException( |
Predict the next line for this snippet: <|code_start|> #set connection information
self.hostname = hostname
self.LOGGER.debug("Set hostname to '%s'", self.hostname)
self.url = "https://{0}/rpc/api".format(self.hostname)
#start session and check API version if Spacewalk API
... | raise InvalidCredentialsException( |
Given snippet: <|code_start|>
#start session and check API version if Spacewalk API
self.api_key = None
super().__init__(username, password)
self.validate_api_support()
def __exit__(self, exc_type, exc_value, traceback):
"""
Destructor
"""
self.api_... | raise SessionException( |
Next line prediction: <|code_start|> """
return self.__api_request("delete", sub_url, payload)
def api_put(self, sub_url, payload):
"""
Sends a PUT request to the Foreman API. This function requires a
sub-URL (such as /hosts/3) and payload data.
:param sub_url: relat... | raise APILevelNotSupportedException( |
Given the following code snippet before the placeholder: <|code_start|> my_headers["Content-Type"] = "application/json"
my_headers["Accept"] = "application/json,version=2"
#send request
if method.lower() == "put":
#PUT
result = self... | raise InvalidCredentialsException("Unable to authenticate") |
Next line prediction: <|code_start|> def __api_request(self, method, sub_url, payload="", hits=1337, page=1):
"""
Sends a HTTP request to the Foreman API. This function requires
a valid HTTP method and a sub-URL (such as /hosts). Optionally,
you can also specify payload (for POST, DEL... | raise SessionException("Illegal method '{}' specified".format(method)) |
Next line prediction: <|code_start|> LibvirtClient.LibvirtClient(
logging.ERROR,
config["config"]["uri"],
"giertz", "paulapinkepank"
)
# TODO: make a call?
# api_dummy.get_vm_ips
def test_create_snapshot_fail(virtClient, nonexisting_vm, snapshot_name... | with pytest.raises(EmptySetException): |
Predict the next line for this snippet: <|code_start|>"""
from __future__ import absolute_import, print_function
@pytest.fixture(scope="session")
def config():
return load_config("libvirt_config.json")
@pytest.fixture
def client(config):
LibvirtClient = pytest.importorskip("katprep.clients.LibvirtClient"... | with pytest.raises(InvalidCredentialsException): |
Given the code snippet: <|code_start|>
return LibvirtClient.LibvirtClient(
logging.ERROR,
config["config"]["uri"],
config["config"]["api_user"],
config["config"]["api_pass"]
)
def test_invalid_login(config):
"""
Ensure exceptions on invalid logins
"""
LibvirtCli... | with pytest.raises(SessionException): |
Using the snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Unit tests for Libvirt integration
"""
from __future__ import absolute_import, print_function
@pytest.fixture(scope="session")
def config():
<|code_end|>
, determine the next line of code. You have imports:
import logging
import py... | return load_config("libvirt_config.json") |
Given snippet: <|code_start|> :param address: IP address
:type address: str
"""
# Friendly inspired by: https://stackoverflow.com/questions/319279/
# how-to-validate-ip-address-in-python
try:
socket.inet_pton(socket.AF_INET6, address)
except socket.error:
return False
retu... | raise InvalidHostnameFormatException( |
Based on the snippet: <|code_start|>
:param uri: a libvirt URI
:type uri: str
"""
prefixes = {
"lxc", "qemu", "xen", "hyperv", "vbox", "openvz", "uml", "phyp",
"vz", "bhyve", "esx", "vpx", "vmwareplayer", "vmwarews",
"vmwarefusion"
}
#c... | raise InvalidCredentialsException("Invalid credentials") |
Given the following code snippet before the placeholder: <|code_start|>.. class:: LibvirtClient
"""
LOGGER = logging.getLogger('LibvirtClient')
"""
logging: Logger instance
"""
def __init__(self, log_level, uri, username, password):
"""
Constructor, creating the class. It requir... | raise SessionException("Invalid URI string specified!") |
Continue the code snippet: <|code_start|> else:
self.LOGGER.error("Unable to determine snapshot: '{}'".format(err))
raise SessionException(err)
def get_vm_ips(self):
"""
Returns a list of VMs and their IPs available through the current
connection... | raise UnsupportedRequestException(err) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Unit tests for Spacewalk API integration
"""
from __future__ import absolute_import
@pytest.fixture(scope='session')
def config():
return load_config("spw_config.json")
@pytest.fixture
def client(config):
... | SpacewalkAPIClient( |
Predict the next line for this snippet: <|code_start|> return load_config("spw_config.json")
@pytest.fixture
def client(config):
# TODO: Instance client
pytest.skip('Diggi, bau mich ein!')
def test_invalid_login(config):
"""
Ensure exceptions on invalid logins
"""
with pytest.raises(Inval... | with pytest.raises(APILevelNotSupportedException): |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Unit tests for Spacewalk API integration
"""
from __future__ import absolute_import
@pytest.fixture(scope='session')
def config():
return load_config("spw_config.json")
@pytest.fixture
def client(config):
# TODO: Inst... | with pytest.raises(InvalidCredentialsException): |
Continue the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Unit tests for Spacewalk API integration
"""
from __future__ import absolute_import
@pytest.fixture(scope='session')
def config():
<|code_end|>
. Use current file imports:
import logging
import mock
import pytest
import ssl... | return load_config("spw_config.json") |
Predict the next line after this snippet: <|code_start|>
@pytest.fixture
def nonexisting_vm():
return "giertz.pinkepank.loc"
@pytest.fixture
def snapshot_name(virtualisation):
if virtualisation == 'libvirt':
return "LibvirtClientTest"
elif virtualisation == 'pyvmomi':
return "PyvmomiClien... | return load_config(virtConfigFile) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.