Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Next line prediction: <|code_start|>
analytics = Blueprint('analytics', __name__)
@analytics.route('/analytics', methods=['GET'])
@login_required
def get_analytics():
if request.args.get("customer_id"):
customer_id = request.args["customer_id"]
else:
customer_id = None
if request.args.ge... | fig1_cracked_cnt = db.session.query(Hashes, HashfileHashes).join(HashfileHashes, Hashes.id==HashfileHashes.hash_id).filter(Hashes.cracked == '1').filter(HashfileHashes.hashfile_id==hashfile_id).count() |
Given the code snippet: <|code_start|>
# TODO
# This whole things is a mess
# Each graph should be its own route
analytics = Blueprint('analytics', __name__)
@analytics.route('/analytics', methods=['GET'])
@login_required
def get_analytics():
if request.args.get("customer_id"):
customer_id = request.ar... | results = db.session.query(Customers, Hashfiles).join(Hashfiles, Customers.id==Hashfiles.customer_id).order_by(Customers.name) |
Given snippet: <|code_start|>
# TODO
# This whole things is a mess
# Each graph should be its own route
analytics = Blueprint('analytics', __name__)
@analytics.route('/analytics', methods=['GET'])
@login_required
def get_analytics():
if request.args.get("customer_id"):
customer_id = request.args["custo... | results = db.session.query(Customers, Hashfiles).join(Hashfiles, Customers.id==Hashfiles.customer_id).order_by(Customers.name) |
Given the following code snippet before the placeholder: <|code_start|>
users = Blueprint('users', __name__)
@users.route("/login", methods=['GET', 'POST'])
def login():
<|code_end|>
, predict the next line using imports from the current file:
from flask import Blueprint, render_template, url_for, flash, abort, redi... | form = LoginForm() |
Predict the next line for this snippet: <|code_start|>@users.route("/login", methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = Users.query.filter_by(email_address=form.email.data).first()
if user and bcrypt.check_password_hash(user.password, form.pass... | form = UsersForm() |
Using the snippet: <|code_start|>@users.route("/profile", methods=['GET', 'POST'])
@login_required
def profile():
form = ProfileForm()
if form.validate_on_submit():
current_user.first_name = form.first_name.data
current_user.last_name = form.last_name.data
if form.pushover_user_key.data:... | form = RequestResetForm() |
Continue the code snippet: <|code_start|> flash('An email has been sent to '+ form.email.data, 'info')
return redirect(url_for('users.login'))
return render_template('reset_request.html', title='Reset Password', form=form)
@users.route("/admin_reset_password/<int:user_id>", methods=['GET', 'POST']... | form = ResetPasswordForm() |
Based on the snippet: <|code_start|> db.session.commit()
flash('Profile Updated!', 'success')
return redirect(url_for('users.profile'))
elif request.method == 'GET':
form.first_name.data = current_user.first_name
form.last_name.data = current_user.last_name
return render_t... | send_email(user, subject, message) |
Predict the next line after this snippet: <|code_start|> db.session.delete(user)
db.session.commit()
flash('User has been deleted!', 'success')
return redirect(url_for('users.users_list'))
else:
abort(403)
@users.route("/profile", methods=['GET', 'POST'])
@login_required
def ... | send_pushover(user, 'Test Message From Hashview', 'This is a test pushover message from hashview') |
Predict the next line after this snippet: <|code_start|>
users = Blueprint('users', __name__)
@users.route("/login", methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
<|code_end|>
using the current file's imports:
from flask import Blueprint, render_template, url_for, fl... | user = Users.query.filter_by(email_address=form.email.data).first() |
Predict the next line after this snippet: <|code_start|>
users = Blueprint('users', __name__)
@users.route("/login", methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = Users.query.filter_by(email_address=form.email.data).first()
<|code_end|>
using the curren... | if user and bcrypt.check_password_hash(user.password, form.password.data): |
Predict the next line for this snippet: <|code_start|> """
As :py:func:`E_MurnV` but input parameters are given as a single list
*a=[a0,a1,a2,a3]*.
"""
return a[0] - a[2]*a[1]/(a[3]-1.0) + V*a[2]/a[3]*( pow(a[1]/V,a[3])/(a[3]-1.0)+1.0 )
def P_Murn(V,a):
"""
As :py:func:`E_MurnV` but input p... | print ("# "+ylabel+"min= {:.10e} Ry".format(a[0])+"\t Vmin= {:.10e} a.u.^3".format(a[1])+"\t B0= {:.10e} kbar".format(a[2]*RY_KBAR) |
Based on the snippet: <|code_start|>def compute_alpha_gruneisen_loopparallel(it):
"""
This function implements the parallel loop where the alpha are computed. It
essentially calls the compute_alpha_grun function with the proper parameters
according to the selected option. "it" is a list with all funct... | S = S * RY_KBAR # convert elastic compliances in (Ryd/au)^-1 |
Using the snippet: <|code_start|>
################################################################################
#
# Try to import a c version (faster) of the function c_qv, if available
# You should install it with "sudo python3 setupmodule.py install" in your
# system before starting this program to make this mo... | return x2*K_BOLTZMANN_RY*expx/math.pow(expx-1.0,2) |
Continue the code snippet: <|code_start|>:py:func:`compute_alpha_gruneisein` is implemented with a simple parallelization
over the temperatures using the Python package :py:mod:`multiprocessing`.
"""
################################################################################
#
# Try to import a c version (fas... | x = omega * KB1 / T |
Using the snippet: <|code_start|> alpha = -alpha/V
return alpha
################################################################################
#
def compute_alpha_gruneisen_loopparallel(it):
"""
This function implements the parallel loop where the alpha are computed. It
essentia... | freq, grun = freqmingrun(it[10],it[11][i],it[12],it[13],it[9],it[14]) |
Given snippet: <|code_start|>
alpha = -alpha/V
return alpha
################################################################################
#
def compute_alpha_gruneisen_loopparallel(it):
"""
This function implements the parallel loop where the alpha are computed. It
essentially... | V=compute_volume(it[11][i],it[9]) |
Using the snippet: <|code_start|>
def compute_alpha_gruneisen_loopparallel(it):
"""
This function implements the parallel loop where the alpha are computed. It
essentially calls the compute_alpha_grun function with the proper parameters
according to the selected option. "it" is a list with all functio... | S = fS(it[15],it[11][i],it[16]) |
Given the code snippet: <|code_start|> for i in range(0,len(y[0,:])):
ax.plot(x, y[:,i], colors[i])
else:
try: # try if there are multiple data on x axis
for i in range(0,len(y[0,:])):
ax.plot(x[:,i], y[:,i], colors[i],label=labels[i])
except... | Vdense, Edensefitted = calculate_fitted_points(V,a) |
Using the snippet: <|code_start|>def compute_thermo_geo(fin,fout=None,ngeo=1,TT=np.array([1])):
"""
This function reads the input dos file(s) from *fin+i*, with *i* a number from
1 to *ngeo* + 1 and computes vibrational energy, Helmholtz energy, entropy and
heat capacity in the harmonic approximation. T... | T, Evib, Svib, Cvib, Fvib, ZPE, modes = compute_thermo(E/RY_TO_CMM1,dos*RY_TO_CMM1,TT) |
Predict the next line for this snippet: <|code_start|>
return h*somma*3.0/8.0;
def compute_thermo(E,dos,TT):
"""
This function computes the vibrational energy, Helmholtz energy, entropy and
heat capacity in the harmonic approximation from the input numpy arrays *E*
and *dos* containing th... | arg = K_BOLTZMANN_RY*TT[i] |
Next line prediction: <|code_start|>
def compute_thermo_geo(fin,fout=None,ngeo=1,TT=np.array([1])):
"""
This function reads the input dos file(s) from *fin+i*, with *i* a number from
1 to *ngeo* + 1 and computes vibrational energy, Helmholtz energy, entropy and
heat capacity in the harmonic approximatio... | E, dos = read_dos(fin+str(i+1)) |
Based on the snippet: <|code_start|> This function reads the input dos file(s) from *fin+i*, with *i* a number from
1 to *ngeo* + 1 and computes vibrational energy, Helmholtz energy, entropy and
heat capacity in the harmonic approximation. Then writes the output on file(s)
if fout!=None.
Output file(... | write_thermo(fout+str(i+1),T, Evib, Fvib, Svib, Cvib, ZPE, modes) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
class Project(object):
def __init__(self, filename):
self.filename = filename
self.dirname = os.path.dirname(filename)
self.entries = {}
tree = ElementTree()
tree.parse(filename)
elem = tree.getroot()
... | self.bssrdf = DiffuseBSSRDF.load(os.path.join(self.dirname, e.text)) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
class Project(object):
def __init__(self, filename):
self.filename = filename
self.dirname = os.path.dirname(filename)
self.entries = {}
tree = ElementTree()
tree.parse(filename)
elem = tree.getroot()... | self.render_params = RenderParameters(int(table['image-width']), |
Predict the next line after this snippet: <|code_start|> self.back_E = 0.0
class BSSRDFEstimator(object):
def __init__(self):
pass
def process(self, image, mask, depth, lights):
width = image.shape[1]
height = image.shape[0]
self.pixels = self.extract_pixel_constraints... | p_b = Vector3D(p_f.x, p_f.y, 0.0) |
Predict the next line after this snippet: <|code_start|> for j in range(num_lights):
light_dir = lights[j].direction()
angl = - light_dir.dot(f_normal)
if angl > 0.0:
f_E += Ft(eta, angl) * angl * light_E
self.pixels[i].front_E =... | self.bssrdf = DiffuseBSSRDF() |
Using the snippet: <|code_start|>#-*- coding: utf-8 -*-
class SolveUnc(object):
def __init__(self, A, b):
ATA = np.dot(A.T, A)
ATb = np.dot(A.T, b)
self.xx = np.zeros(ATb.shape)
for c in range(ATb.shape[1]):
self.xx[:,c] = sp.sparse.linalg.qmr(ATA, ATb[:,c])[0]
... | self.xx[:,c] = cubic_fitting(self.xx[:,c]) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
class DirectionalLight(object):
def __init__(self, phi, theta):
self.phi = phi
self.theta = theta
self.weight = 0.0
def direction(self):
x = math.cos(self.phi) * math.cos(self.theta)
y = math.sin(self.ph... | return Vector3D(x, y, z) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
class BSSRDFRenderThread(QThread):
def __init__(self, render_params, bssrdf):
super(BSSRDFRenderThread, self).__init__()
self.render_params = render_params
self.bssrdf = bssrdf
def run(sel... | class BSSRDFRenderWidget(ImageWidget): |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
def strwrite(fp, str):
fp.write(bytearray(str, 'ascii'))
def hdr_save(filename, hdr):
with open(filename, 'wb') as fp:
# Write header
ret = 0x0a
strwrite(fp, '#?RADIANCE%c' % ret)
s... | line[j] = HDRPixel(r, g, b) |
Here is a snippet: <|code_start|> * test_bar.py
* __init__.py
* test.conf
* ui/Ui_test.py
* ui/test.ui
---Config Values---
"name":"mock_test_extension",
"menu_item":"A Mock Testing Object",
"parent":"Testing",
"main":"main",
"settings":"main",
"toolbar":"test_bar",
"tests":"units"
"""
class Extension... | self.ext_mgr = extension_manager.ExtensionManager() |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Toolbar
The core toolbar object for commotion viewports.
The tool bar is an object that is created in the main viewport. This tool-bar has pre-built objects for common functions and an add-on sec... | def __init__(self, parent=None, extension_toolbar=None, viewport): |
Given the following code snippet before the placeholder: <|code_start|> elif name != None:
for conf in self.configs:
if conf["name"] and conf["name"] == name:
return conf
self.log.error(self.translate("logs", "No config of the chosed type named {0} foun... | for root, dirs, files in fs_utils.walklevel(path): |
Given the code snippet: <|code_start|> if len(str(name)) > 0:
_settings = self.user_settings
_settings.remove(str(name))
return True
else:
self.log.debug(self.translate("logs", "A zero length string was passed as the name of an extension to be removed. This... | config_validator = validate.ClientConfig(extension_config, extension_dir) |
Predict the next line for this snippet: <|code_start|>
"""
#Standard Library Imports
#PyQt imports
#Commotion Client Imports
class ExtensionManager(object):
def __init__(self):
self.log = logging.getLogger("commotion_client."+__name__)
self.translate = QtCore.QCoreApplication.translate
... | settings_manager = settings.UserSettingsManager() |
Given the following code snippet before the placeholder: <|code_start|> self.translate = QtCore.QCoreApplication.translate
self.status = status
self.controller = False
self.main = False
self.sys_tray = False
#initialize client (GUI, controller, etc) upon event loop start ... | self.logger = logger.LogHandler("commotion_client", level, logfile) |
Given the code snippet: <|code_start|> Function that handles command line arguments, translation, and creates the main application.
"""
args = get_args()
#Create Instance of Commotion Application
app = CommotionClientApplication(args, sys.argv)
#Enable Translations #TODO This code needs to be ev... | class HoldStateDuringRestart(thread.GenericThread): |
Given the code snippet: <|code_start|> else:
app.log.info(app.translate("logs", "application is already running. Application will be brought to foreground"))
app.send_message("showMain")
app.end("Only one instance of a commotion application may be running at any time.")
sys.e... | class CommotionClientApplication(single_application.SingleApplicationWithMessaging): |
Using the snippet: <|code_start|> QtCore.QTimer.singleShot(0, self.init_client)
#=================================================
# CLIENT LOGIC
#=================================================
def init_client(self):
"""
Start up client using current status to determine ru... | extensions = extension_manager.ExtensionManager() |
Given the following code snippet before the placeholder: <|code_start|> _restart.start()
try:
self.stop_client(force_close)
self.init_client()
except Exception as _excp:
if force_close:
_catch_all = self.translate("logs", "Client could not be re... | _main = main_window.MainWindow() |
Next line prediction: <|code_start|> self.end(_catch_all)
else:
self.log.error(self.translate("logs", "Could not cleanly close controller."))
self.log.info(self.translate("logs", "It is reccomended that you close the entire application."))
s... | tray = system_tray.TrayIcon() |
Predict the next line after this snippet: <|code_start|> error_report = QtCore.pyqtSignal(str)
clean_up = QtCore.pyqtSignal()
on_stop = QtCore.pyqtSignal()
def __init__(self, parent=None):
super().__init__()
self.log = logging.getLogger("commotion_client."+__name__)
self.translat... | class ToolBar(extension_toolbar.ExtensionToolBar): |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Toolbar
The core toolbar object for commotion viewports.
The tool bar is an object that is created in the main viewport. This tool-bar has pre-built objects for common functions and an add-on section that will allow a develop... | def __init__(self, viewport, parent=None, extension_toolbar=None): |
Continue the code snippet: <|code_start|>"""aiohttp plugin that reads app configuration and stores a
GitHubClient object on app['client'].
If using caching, the caching plugin MUST be set up before
setting up this plugin.
"""
CONFIG_KEY = 'GITHUB'
APP_CLIENT_KEY = 'github_client'
def setup(app):
config = app.get... | client = GitHubClient( |
Next line prediction: <|code_start|>"""aiohttp plugin that reads app configuration and stores a
GitHubClient object on app['client'].
If using caching, the caching plugin MUST be set up before
setting up this plugin.
"""
CONFIG_KEY = 'GITHUB'
APP_CLIENT_KEY = 'github_client'
def setup(app):
config = app.get(CONF... | cache = app.get(CACHE_APP_KEY) |
Given snippet: <|code_start|> })
if self.cache:
etag = (self.cache.get(cache_key) or {}).get('etag')
if etag:
kwargs['headers']['If-None-Match'] = etag
full_url = '{API_URL}/{url}'.format(API_URL=API_URL, url=url)
async with aiohttp.request(method... | cache_key = get_cache_key('user_repos', { |
Continue the code snippet: <|code_start|>
class MockGitHubClient(BaseMockGitHubClient):
async def repo_tags(self, *args, **kwargs):
return [
{'name': '1.2.3', 'commit': {'sha': '123abc'}},
{'name': '1.2.2', 'commit': {'sha': 'abc123'}},
]
async def compare(self, *args... | raise GitHubClientError({'error': 'Something went wrong'}, mock_resp) |
Predict the next line after this snippet: <|code_start|>
##### App factory #####
def create_app(settings_obj=None) -> web.Application:
"""App factory. Sets up routes and all plugins.
:param settings_obj: Object containing optional configuration overrides. May be
a Python module or class with uppercas... | config = Config() |
Predict the next line for this snippet: <|code_start|>
##### App factory #####
def create_app(settings_obj=None) -> web.Application:
"""App factory. Sets up routes and all plugins.
:param settings_obj: Object containing optional configuration overrides. May be
a Python module or class with uppercased... | github_plugin.setup(app) |
Using the snippet: <|code_start|>
HERE = os.path.dirname(os.path.abspath(__file__))
class MockGitHubClient(BaseMockGitHubClient):
def _response_from_file(self, json_file):
with open(os.path.join(HERE, 'responses', json_file)) as fp:
ret = json.load(fp)
return ret
async def repo_... | return process.RepoProcessor(client) |
Predict the next line after this snippet: <|code_start|>
HERE = os.path.dirname(os.path.abspath(__file__))
class MockGitHubClient(BaseMockGitHubClient):
def _response_from_file(self, json_file):
with open(os.path.join(HERE, 'responses', json_file)) as fp:
ret = json.load(fp)
return ret... | @async_test |
Using the snippet: <|code_start|>sys.path.insert(0, os.path.join(HERE, '..', '..'))
class TestConfig:
ENV = 'testing'
DEBUG = True
CACHE = {'STRATEGY': 'simple', 'PARAMS': {}}
class BaseMockGitHubClient(GitHubClient):
# Stub out request method
async def make_request(self, **kwargs):
pas... | app = create_app(TestConfig) |
Next line prediction: <|code_start|>"""Test utilities and pytest fixtures."""
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, '..', '..'))
class TestConfig:
ENV = 'testing'
DEBUG = True
CACHE = {'STRATEGY': 'simple', 'PARAMS': {}}
<|code_end|>
. Use current file... | class BaseMockGitHubClient(GitHubClient): |
Given the following code snippet before the placeholder: <|code_start|>
class TestConfig:
ENV = 'testing'
DEBUG = True
CACHE = {'STRATEGY': 'simple', 'PARAMS': {}}
class BaseMockGitHubClient(GitHubClient):
# Stub out request method
async def make_request(self, **kwargs):
pass
async d... | app[GITHUB_APP_KEY] = github or BaseMockGitHubClient('id', 'secret') |
Predict the next line after this snippet: <|code_start|>
async def index(request):
return Response({
'message': 'Welcome to the sir API',
'links': {
'should_i_release': request.app.router['should_i_release'].url(
parts=dict(username=':username', repo=':repo')
... | except GitHubClientError as err: |
Predict the next line for this snippet: <|code_start|>
async def index(request):
return Response({
'message': 'Welcome to the sir API',
'links': {
'should_i_release': request.app.router['should_i_release'].url(
parts=dict(username=':username', repo=':repo')
),... | processor = RepoProcessor(client) |
Given the code snippet: <|code_start|>from __future__ import absolute_import, division, print_function
class TestSample (unittest.TestCase):
def test_sample(self):
geojson_input = b'''{ "type": "FeatureCollection", "features": [
{ "type": "Feature", "geometry": {"type": "Poi... | geojson0 = json.loads(sample_geojson(BytesIO(geojson_input), max_features=0)) |
Based on the snippet: <|code_start|>
geojson4 = json.loads(sample_geojson(BytesIO(geojson_input), max_features=4))
self.assertEqual(len(geojson4['features']), 3)
self.assertEqual(geojson0['type'], 'FeatureCollection')
self.assertEqual(geojson1['features'][0]['type'], 'Feature')
... | features = stream_geojson(BytesIO(geojson_input)) |
Predict the next line for this snippet: <|code_start|> def __init__(self, json_blob):
blob_dict = dict(json_blob or {})
self.keys = blob_dict.keys()
self.run_id = blob_dict.get('run id')
self.source = blob_dict.get('source')
self.cache = blob_dict.get('cache')
self.sa... | self.source_problem = None if (raw_problem is None) else SourceProblem(raw_problem) |
Predict the next line for this snippet: <|code_start|> for f in filenames:
files.append(os.path.join(dirpath, f))
return files
def to_shapely_obj(data):
"""
Converts a fiona geometry to a shapely object.
"""
if 'geometry' in data and data['geometry']:
geom = shape(data[... | cleaned_json = conform_smash_case(source_json) |
Given the code snippet: <|code_start|> return files
def to_shapely_obj(data):
"""
Converts a fiona geometry to a shapely object.
"""
if 'geometry' in data and data['geometry']:
geom = shape(data['geometry'])
if config.clean_geom:
if not geom.is_valid: # sends warnings t... | metadata = row_transform_and_convert(cleaned_json, cleaned_prop) |
Predict the next line for this snippet: <|code_start|> """
Loads a python representation of the state file.
"""
state = []
with open(config.statefile_path, 'r') as statefile:
statereader = csv.reader(statefile, dialect='excel-tab')
for row in statereader:
state.append(row)... | setup_logger() |
Given the following code snippet before the placeholder: <|code_start|>
_L = logging.getLogger('openaddr.parcels')
csv.field_size_limit(sys.maxsize)
def parse_source(source, idx, header):
"""
Import data from a single source based on the data type.
"""
path = '{}/{}'.format(config.workspace_dir, idx... | fetch(cache_url, path + cache_filename) |
Given the following code snippet before the placeholder: <|code_start|>
_L = logging.getLogger('openaddr.parcels')
csv.field_size_limit(sys.maxsize)
def parse_source(source, idx, header):
"""
Import data from a single source based on the data type.
"""
path = '{}/{}'.format(config.workspace_dir, idx... | unzip(f, path) |
Based on the snippet: <|code_start|>
_L = logging.getLogger('openaddr.parcels')
csv.field_size_limit(sys.maxsize)
def parse_source(source, idx, header):
"""
Import data from a single source based on the data type.
"""
path = '{}/{}'.format(config.workspace_dir, idx)
if not os.path.exists(path):
... | files = rlistdir(path) |
Predict the next line for this snippet: <|code_start|> unzipped_base = os.path.join(workdir, UNZIPPED_DIRNAME)
unzipped_paths = dict([(os.path.relpath(source_path, unzipped_base), source_path)
for source_path in source_paths])
if conform['file'] not in unzipped_pat... | temp_file.write(sample_geojson(complete_layer, 10)) |
Here is a snippet: <|code_start|> out_fieldnames.append(X_FIELDNAME)
out_fieldnames.append(Y_FIELDNAME)
# Write the extracted CSV file
with open(dest_path, 'w', encoding='utf-8') as dest_fp:
writer = csv.DictWriter(dest_fp, out_fieldnames)
writer.writehead... | for (row_number, feature) in enumerate(stream_geojson(file)): |
Predict the next line after this snippet: <|code_start|> elif area == EUROPE:
left, top = -2700000, 8700000
right, bottom = 5800000, 3600000
else:
raise RuntimeError('Unknown area "{}"'.format(area))
aspect = (right - left) / (top - bottom)
hsize = int(resolution * width)
vs... | return {s['source']: RunPartial(objects.RunState(s)) |
Here is a snippet: <|code_start|># coding=ascii
from __future__ import absolute_import, division, print_function
class TestConformTransforms (unittest.TestCase):
"Test low level data transform functions"
def test_row_smash_case(self):
<|code_end|>
. Write the next line using the current file imports:
imp... | r = row_smash_case(None, {"UPPER": "foo", "lower": "bar", "miXeD": "mixed"}) |
Given snippet: <|code_start|> d = row_fxn_postfixed_street(c, d, "street", c["conform"]["street"])
self.assertEqual(e, d)
"no unit"
c = { "conform": {
"street": {
"function": "postfixed_street",
"field": "ADDRESS",
"may_contain_... | d = row_fxn_postfixed_unit(c, d, "unit", c["conform"]["unit"]) |
Predict the next line for this snippet: <|code_start|> d = row_fxn_postfixed_unit(c, d, "unit", c["conform"]["unit"])
self.assertEqual(e, d)
"postfixed_unit - no unit"
c = { "conform": {
"unit": {
"function": "postfixed_unit",
"field": "ADDRESS... | d = row_fxn_remove_prefix(c, d, "street", c["conform"]["street"]) |
Here is a snippet: <|code_start|> self.assertEqual(e, d)
"remove_prefix - field_to_remove value is empty string"
c = { "conform": {
"street": {
"function": "remove_prefix",
"field": "ADDRESS",
"field_to_remove": "PREFIX"
}
... | d = row_fxn_remove_postfix(c, d, "street", c["conform"]["street"]) |
Given the code snippet: <|code_start|>
d = copy.deepcopy(e)
d["a2"] = None
d["b3"] = None
d = row_fxn_format(c, d, "number", c["conform"]["number"])
d = row_fxn_format(c, d, "street", c["conform"]["street"])
self.assertEqual(d.get("OA:number", ""), "12-56")
self.a... | d = row_fxn_chain(c, d, "number", c["conform"]["number"]) |
Given the code snippet: <|code_start|> d = row_fxn_remove_postfix(c, d, "street", c["conform"]["street"])
self.assertEqual(e, d)
"remove_postfix - field_to_remove value is empty string"
c = { "conform": {
"street": {
"function": "remove_postfix",
... | d = row_fxn_first_non_empty(c, d, "street", c["conform"]["street"]) |
Given the following code snippet before the placeholder: <|code_start|> self.assertEqual(e, d)
"first_non_empty - all field values are trimmable to a 0-length string"
c = { "conform": {
"street": {
"function": "first_non_empty",
"fields": ["FIELD1", "F... | d = row_fxn_get_from_array_string(c, d, "region", c["conform"]["region"]) |
Given snippet: <|code_start|># coding=ascii
from __future__ import absolute_import, division, print_function
class TestConformTransforms (unittest.TestCase):
"Test low level data transform functions"
def test_row_smash_case(self):
r = row_smash_case(None, {"UPPER": "foo", "lower": "bar", "miXeD": ... | r = conform_smash_case(d) |
Predict the next line for this snippet: <|code_start|>
# TODO get rid of this datastore, use client-side request
try:
zircon_config = settings.ZIRCON_CONFIG
db_info = zircon_config.get('db_info', None)
db_name = zircon_config.get('db_name', None)
<|code_end|>
with the help of current file imports:
from ... | db = InfluxDatastore(db_info=db_info, db_name=db_name) |
Next line prediction: <|code_start|>"""
"""
reporter = Reporter(
transceiver=DummyMultipleTransceiver(
signals={
'IMU_X': lambda x: 1.0 * sin(2*pi*(x/3.0 + 1)) + gauss(0, 0.2),
'IMU_Y': lambda x: 1.5 * sin(2*pi*x/2.5) + gauss(0, 0.2),
'IMU_Z': lambda x: 1.3 * sin(2*pi... | publisher=ZMQPublisher() |
Continue the code snippet: <|code_start|>"""
"""
NAMESPACE_URL = '/data'
@namespace(NAMESPACE_URL)
class DataNamespace(BaseNamespace, RoomsMixin, BroadcastMixin):
try:
zircon_config = settings.ZIRCON_CONFIG
db_info = zircon_config.get('db_info', None)
db_name = zircon_config.get('db_... | db = InfluxDatastore(db_info=db_info, db_name=db_name) |
Predict the next line for this snippet: <|code_start|>"""
"""
# Generated signal
def sine_wave(t):
return sin(2*pi*t/3.0)
# Sampling frequency
freq = 1000
reporter = Reporter(
<|code_end|>
with the help of current file imports:
from zircon.transceivers.dummy import DummyTransceiver
from zircon.publishers.ze... | transceiver=DummyTransceiver( |
Predict the next line for this snippet: <|code_start|>"""
"""
# Generated signal
def sine_wave(t):
return sin(2*pi*t/3.0)
# Sampling frequency
freq = 1000
reporter = Reporter(
transceiver=DummyTransceiver(
signal_name='MY_SIGNAL',
data_gen=sine_wave,
dt=1.0/freq
),
transfor... | publisher=ZMQPublisher() |
Given snippet: <|code_start|>"""
"""
# Generated signal
def sine_wave(t):
return sin(2*pi*t/3.0)
# Sampling frequency
freq = 1000
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from zircon.transceivers.dummy import DummyTransceiver
from zircon.publishers.zeromq import ZMQ... | reporter = Reporter( |
Here is a snippet: <|code_start|> When creating a Reporter, you supply instances of a Transceiver,
one or more Transformers, and a Publisher. If not specified,
a pickling Transformer and the default Publisher are used.
**Usage**::
reporter = Reporter(
transceiver=MyTransceiver(),
... | self.transformers = [Pickler()] |
Continue the code snippet: <|code_start|>
reporter = Reporter(
transceiver=MyTransceiver(),
transformers=[MyDecoder(), MyCompressor(), ...],
publisher=MyPublisher()
)
A Reporter can be run as its own process::
reporter.run()
Or stepped through by an... | self.publisher = ZMQPublisher() |
Given the following code snippet before the placeholder: <|code_start|>
# Simple form:
# volumes:
# /foo: /host/foo
if isinstance(node, str):
return cls(
container_path = cpath,
host_path = _expand_path(node),
)
# Com... | return make_vol_opt(self.host_path, self.container_path, self.options) |
Based on the snippet: <|code_start|>#!/usr/bin/env python
class InTempDir:
def __init__(self, suffix='', prefix='tmp', delete=True):
self.delete = delete
self.temp_path = tempfile.mkdtemp(suffix=suffix, prefix=prefix)
def __enter__(self):
self.orig_path = os.getcwd()
os.chdir... | f.write('image: {}\n'.format(DOCKER_IMAGE)) |
Based on the snippet: <|code_start|> main.main(argv = args)
except SystemExit as sysexit:
retcode = sysexit.code
else:
retcode = 0
stdout.seek(0)
stderr.seek(0)
... | f.write('image: {}\n'.format(DOCKER_IMAGE)) |
Continue the code snippet: <|code_start|>
class TestScubaContext:
def test_process_command_image(self):
'''process_command returns the image and entrypoint'''
image_name = 'test_image'
entrypoint = 'test_entrypoint'
<|code_end|>
. Use current file imports:
import pytest
import shlex
from ... | cfg = ScubaConfig( |
Continue the code snippet: <|code_start|> )
assert result.environment == expected
def test_process_command_alias_extends_docker_args(self):
'''aliases can extend the docker_args'''
cfg = ScubaConfig(
image = 'default',
docker_args = '--privileged',
... | docker_args = OverrideStr('-v /tmp/:/tmp/'), |
Next line prediction: <|code_start|>
class TestScubaContext:
def test_process_command_image(self):
'''process_command returns the image and entrypoint'''
image_name = 'test_image'
entrypoint = 'test_entrypoint'
cfg = ScubaConfig(
image = image_name,
... | result = ScubaContext.process_command(cfg, []) |
Given snippet: <|code_start|>
for instance in unresolved_node_instances:
ctx.logger.debug("unresolved node instance:{}".format(instance.id))
intact_nodes = set(ctx.node_instances) - set(unresolved_node_instances)
for instance in intact_nodes:
ctx.logger.debug("intact node instance:{}".form... | utilitieslifecycle.rollback_node_instances( |
Given the code snippet: <|code_start|> first_key = 'some_key_1'
first_value = 'BlahBlah'
second_key = 'some_key_2'
second_value = 12
third_key = 'some_key_3'
third_value = False
fourth_key = 'some_key_4'
fourth_value = {
'test': {
... | sdk = SecretsSDK(mock.Mock(), self.rest_client_mock, **properties) |
Given the following code snippet before the placeholder: <|code_start|># http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either ex... | ctx.instance.runtime_properties[RESOURCES_LIST_PROPERTY] = resource_config |
Given the following code snippet before the placeholder: <|code_start|>#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific... | ctx.instance.runtime_properties[FREE_RESOURCES_LIST_PROPERTY] = \ |
Using the snippet: <|code_start|># distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def _refresh_source_and_target_runtim... | ctx.instance.runtime_properties[RESERVATIONS_PROPERTY] = {} |
Predict the next line for this snippet: <|code_start|>
def _refresh_source_and_target_runtime_props(ctx, **kwargs):
ctx.source.instance.refresh()
ctx.target.instance.refresh()
def _update_source_and_target_runtime_props(ctx, **kwargs):
ctx.source.instance.update()
ctx.target.instance.update()
@oper... | ctx.instance.runtime_properties[SINGLE_RESERVATION_PROPERTY] = '' |
Using the snippet: <|code_start|> ]
}
),
instance=MockNodeInstanceContext(
id='test_resources_123456',
runtime_properties={},
)
)
rel_ctx = MockRelationshipContext(
type='cloudify.relation... | tasks.create_list(ctx) |
Next line prediction: <|code_start|> id='test_resources_123456',
runtime_properties={},
)
)
rel_ctx = MockRelationshipContext(
type='cloudify.relationships.resources.reserve_list_item',
target=tar_rel_subject_ctx
)
# so... | RESOURCES_LIST_PROPERTY in ctx.instance.runtime_properties) |
Based on the snippet: <|code_start|> )
)
rel_ctx = MockRelationshipContext(
type='cloudify.relationships.resources.reserve_list_item',
target=tar_rel_subject_ctx
)
# source
src_ctx = MockCloudifyContext(
node_id='test_item_123456',... | FREE_RESOURCES_LIST_PROPERTY in ctx.instance.runtime_properties) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.