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.get("hashfile_id"):
hashfile_id = request.args["hashfile_id"]
else:
hashfile_id = None
hashfiles, customers = [], []
results = db.session.query(Customers, Hashfiles).join(Hashfiles, Customers.id==Hashfiles.customer_id).order_by(Customers.name)
#Put all hashes in a list (hashfiles) and pull out all unique customers into a separate list (customers)
for rows in results:
customers.append(rows.Customers) if rows.Customers not in customers else customers
hashfiles.append(rows.Hashfiles)
# Figure 1 (Cracked vs uncracked)
if customer_id:
# we have a customer
if hashfile_id: # with a hashfile
<|code_end|>
. Use current file imports:
(from flask import Blueprint, jsonify, render_template, request, redirect, send_from_directory
from flask_login import login_required
from hashview.models import Customers, HashfileHashes, Hashes, Hashfiles
from hashview import db
import re
import operator)
and context including class names, function names, or small code snippets from other files:
# Path: hashview/models.py
# class Customers(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# name = db.Column(db.String(40), nullable=False)
#
# class HashfileHashes(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# hash_id = db.Column(db.Integer, nullable=False, index=True)
# username = db.Column(db.String(256), nullable=True, default=None, index=True)
# hashfile_id = db.Column(db.Integer, nullable=False)
#
# class Hashes(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# sub_ciphertext = db.Column(db.String(32), nullable=False, index=True)
# ciphertext = db.Column(db.String(16383), nullable=False) # Setting this to max value for now. If we run into this being a limitation in the future we can revisit changing thist to TEXT or BLOB. https://sheeri.org/max-varchar-size/
# hash_type = db.Column(db.Integer, nullable=False, index=True)
# cracked = db.Column(db.Boolean, nullable=False)
# plaintext = db.Column(db.String(256), index=True)
#
# class Hashfiles(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# name = db.Column(db.String(256), nullable=False) # can probably be reduced
# uploaded_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
# runtime = db.Column(db.Integer, default=0)
# customer_id = db.Column(db.Integer, nullable=False)
# owner_id = db.Column(db.Integer, nullable=False)
#
# Path: hashview.py
# def data_retention_cleanup():
. Output only the next line. | 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.args["customer_id"]
else:
customer_id = None
if request.args.get("hashfile_id"):
hashfile_id = request.args["hashfile_id"]
else:
hashfile_id = None
hashfiles, customers = [], []
<|code_end|>
, generate the next line using the imports in this file:
from flask import Blueprint, jsonify, render_template, request, redirect, send_from_directory
from flask_login import login_required
from hashview.models import Customers, HashfileHashes, Hashes, Hashfiles
from hashview import db
import re
import operator
and context (functions, classes, or occasionally code) from other files:
# Path: hashview/models.py
# class Customers(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# name = db.Column(db.String(40), nullable=False)
#
# class HashfileHashes(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# hash_id = db.Column(db.Integer, nullable=False, index=True)
# username = db.Column(db.String(256), nullable=True, default=None, index=True)
# hashfile_id = db.Column(db.Integer, nullable=False)
#
# class Hashes(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# sub_ciphertext = db.Column(db.String(32), nullable=False, index=True)
# ciphertext = db.Column(db.String(16383), nullable=False) # Setting this to max value for now. If we run into this being a limitation in the future we can revisit changing thist to TEXT or BLOB. https://sheeri.org/max-varchar-size/
# hash_type = db.Column(db.Integer, nullable=False, index=True)
# cracked = db.Column(db.Boolean, nullable=False)
# plaintext = db.Column(db.String(256), index=True)
#
# class Hashfiles(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# name = db.Column(db.String(256), nullable=False) # can probably be reduced
# uploaded_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
# runtime = db.Column(db.Integer, default=0)
# customer_id = db.Column(db.Integer, nullable=False)
# owner_id = db.Column(db.Integer, nullable=False)
#
# Path: hashview.py
# def data_retention_cleanup():
. Output only the next line. | 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["customer_id"]
else:
customer_id = None
if request.args.get("hashfile_id"):
hashfile_id = request.args["hashfile_id"]
else:
hashfile_id = None
hashfiles, customers = [], []
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from flask import Blueprint, jsonify, render_template, request, redirect, send_from_directory
from flask_login import login_required
from hashview.models import Customers, HashfileHashes, Hashes, Hashfiles
from hashview import db
import re
import operator
and context:
# Path: hashview/models.py
# class Customers(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# name = db.Column(db.String(40), nullable=False)
#
# class HashfileHashes(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# hash_id = db.Column(db.Integer, nullable=False, index=True)
# username = db.Column(db.String(256), nullable=True, default=None, index=True)
# hashfile_id = db.Column(db.Integer, nullable=False)
#
# class Hashes(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# sub_ciphertext = db.Column(db.String(32), nullable=False, index=True)
# ciphertext = db.Column(db.String(16383), nullable=False) # Setting this to max value for now. If we run into this being a limitation in the future we can revisit changing thist to TEXT or BLOB. https://sheeri.org/max-varchar-size/
# hash_type = db.Column(db.Integer, nullable=False, index=True)
# cracked = db.Column(db.Boolean, nullable=False)
# plaintext = db.Column(db.String(256), index=True)
#
# class Hashfiles(db.Model):
# id = db.Column(db.Integer, primary_key=True)
# name = db.Column(db.String(256), nullable=False) # can probably be reduced
# uploaded_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
# runtime = db.Column(db.Integer, default=0)
# customer_id = db.Column(db.Integer, nullable=False)
# owner_id = db.Column(db.Integer, nullable=False)
#
# Path: hashview.py
# def data_retention_cleanup():
which might include code, classes, or functions. Output only the next line. | 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, redirect, request
from flask_login import login_required, logout_user, current_user, login_user
from hashview.users.forms import LoginForm, UsersForm, ProfileForm, RequestResetForm, ResetPasswordForm
from hashview.utils.utils import send_email, send_pushover
from hashview.models import Users
from hashview import db, bcrypt
and context including class names, function names, and sometimes code from other files:
# Path: hashview/users/forms.py
# class LoginForm(FlaskForm):
# email = StringField('Email', validators=[DataRequired(), Email()])
# password = PasswordField('Password', validators=[DataRequired()])
# remember = BooleanField('Remember Me')
# submit = SubmitField('Login')
#
# class UsersForm(FlaskForm):
# first_name = StringField('First Name', validators=[DataRequired(), Length(min=1, max=20)])
# last_name = StringField('Last Name', validators=[DataRequired(), Length(min=1, max=20)])
# email = StringField('Email', validators=[DataRequired(), Email()])
# is_admin = BooleanField('Is Admin')
# password = PasswordField('Password', validators=[DataRequired(), Length(min=14)])
# confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
# pushover_app_id = StringField('Pushover App Token (optional)')
# pushover_user_key = StringField('Pushover User Key (optional)')
# submit = SubmitField('Register')
#
# def validate_email(self, email):
# user = Users.query.filter_by(email_address = email.data).first()
# if user:
# raise ValidationError('That email address is taken. Please choose a different one.')
#
# def validate_pushover(self, pushover_app_id, pushover_user_key):
# if len(pushover_app_id.data) > 0 and len(pushover_user_key.data) == 0:
# raise ValidationError('You must supply both options to use.')
# if len(pushover_app_id.data) == 0 and len(pushover_user_key.data) > 0:
# raise ValidationError('You must supply both options to use.')
#
# class ProfileForm(FlaskForm):
# first_name = StringField('First Name', validators=[DataRequired(), Length(min=1, max=20)])
# last_name = StringField('Last Name', validators=[DataRequired(), Length(min=1, max=20)])
# pushover_user_key = StringField('Pushover User Key (optional)')
# pushover_app_id = StringField('Pushover App Id (optional)')
# submit = SubmitField('Update')
#
# class RequestResetForm(FlaskForm):
# email = StringField('Email', validators=[DataRequired(), Email()])
# submit = SubmitField('Request Password Reset')
#
# class ResetPasswordForm(FlaskForm):
# password = PasswordField('Password', validators=[DataRequired(), Length(min=14)])
# confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
# submit = SubmitField('Reset Password')
#
# Path: hashview/utils/utils.py
# def send_email(user, subject, message):
# msg = Message(subject, recipients=[user.email_address])
# msg.body = message
# mail.send(msg)
#
# def send_pushover(user, subject, message):
# if user.pushover_user_key and user.pushover_app_id:
# client = Client(user.pushover_user_key, api_token=user.pushover_app_id)
# try:
# client.send_message(message, title=subject)
# except:
# send_email(user, "Error Sending Push Notification", "Check your Pushover API keys in your profile. Original Message: " + message)
#
# Path: hashview/models.py
# class Users(db.Model, UserMixin):
# id = db.Column(db.Integer, primary_key=True)
# first_name = db.Column(db.String(20), nullable=False)
# last_name = db.Column(db.String(20), nullable=False)
# email_address = db.Column(db.String(50), unique=True, nullable=False)
# password = db.Column(db.String(60), nullable=False)
# admin = db.Column(db.Boolean, nullable=False, default=False)
# pushover_app_id = db.Column(db.String(50), nullable=True)
# pushover_user_key = db.Column(db.String(50), nullable=True)
# wordlists = db.relationship('Wordlists', backref='tbd', lazy=True)
# rules = db.relationship('Rules', backref='owner', lazy=True)
# jobs = db.relationship('Jobs', backref='owner', lazy=True)
# tasks = db.relationship('Tasks', backref='owner', lazy=True)
# taskgroups = db.relationship('TaskGroups', backref='owner', lazy=True)
#
# def get_reset_token(self, expires_sec=1800):
# s = Serializer(Config.SECRET_KEY, expires_sec)
# return s.dumps({'user_id': self.id}).decode('utf-8')
#
# @staticmethod
# def verify_reset_token(token):
# s = Serializer(Config.SECRET_KEY)
# try:
# user_id = s.loads(token)['user_id']
# except:
# return None
# return Users.query.get(user_id)
#
# Path: hashview.py
# def data_retention_cleanup():
. Output only the next line. | 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.password.data):
login_user(user, remember=form.remember.data)
if request.args.get("next"):
return redirect(request.args.get("next"))
else:
return redirect(url_for('main.home'))
else:
flash('Login Unsuccessful. Please check email and password', 'danger')
return render_template('login.html', title='Login', form=form)
@users.route("/logout")
def logout():
logout_user()
return redirect(url_for('main.home'))
@users.route("/users", methods=['GET', 'POST'])
@login_required
def users_list():
users = Users.query.all()
return render_template('users.html', title='Users', users=users)
@users.route("/users/add", methods=['GET', 'POST'])
@login_required
def users_add():
if current_user.admin:
<|code_end|>
with the help of current file imports:
from flask import Blueprint, render_template, url_for, flash, abort, redirect, request
from flask_login import login_required, logout_user, current_user, login_user
from hashview.users.forms import LoginForm, UsersForm, ProfileForm, RequestResetForm, ResetPasswordForm
from hashview.utils.utils import send_email, send_pushover
from hashview.models import Users
from hashview import db, bcrypt
and context from other files:
# Path: hashview/users/forms.py
# class LoginForm(FlaskForm):
# email = StringField('Email', validators=[DataRequired(), Email()])
# password = PasswordField('Password', validators=[DataRequired()])
# remember = BooleanField('Remember Me')
# submit = SubmitField('Login')
#
# class UsersForm(FlaskForm):
# first_name = StringField('First Name', validators=[DataRequired(), Length(min=1, max=20)])
# last_name = StringField('Last Name', validators=[DataRequired(), Length(min=1, max=20)])
# email = StringField('Email', validators=[DataRequired(), Email()])
# is_admin = BooleanField('Is Admin')
# password = PasswordField('Password', validators=[DataRequired(), Length(min=14)])
# confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
# pushover_app_id = StringField('Pushover App Token (optional)')
# pushover_user_key = StringField('Pushover User Key (optional)')
# submit = SubmitField('Register')
#
# def validate_email(self, email):
# user = Users.query.filter_by(email_address = email.data).first()
# if user:
# raise ValidationError('That email address is taken. Please choose a different one.')
#
# def validate_pushover(self, pushover_app_id, pushover_user_key):
# if len(pushover_app_id.data) > 0 and len(pushover_user_key.data) == 0:
# raise ValidationError('You must supply both options to use.')
# if len(pushover_app_id.data) == 0 and len(pushover_user_key.data) > 0:
# raise ValidationError('You must supply both options to use.')
#
# class ProfileForm(FlaskForm):
# first_name = StringField('First Name', validators=[DataRequired(), Length(min=1, max=20)])
# last_name = StringField('Last Name', validators=[DataRequired(), Length(min=1, max=20)])
# pushover_user_key = StringField('Pushover User Key (optional)')
# pushover_app_id = StringField('Pushover App Id (optional)')
# submit = SubmitField('Update')
#
# class RequestResetForm(FlaskForm):
# email = StringField('Email', validators=[DataRequired(), Email()])
# submit = SubmitField('Request Password Reset')
#
# class ResetPasswordForm(FlaskForm):
# password = PasswordField('Password', validators=[DataRequired(), Length(min=14)])
# confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
# submit = SubmitField('Reset Password')
#
# Path: hashview/utils/utils.py
# def send_email(user, subject, message):
# msg = Message(subject, recipients=[user.email_address])
# msg.body = message
# mail.send(msg)
#
# def send_pushover(user, subject, message):
# if user.pushover_user_key and user.pushover_app_id:
# client = Client(user.pushover_user_key, api_token=user.pushover_app_id)
# try:
# client.send_message(message, title=subject)
# except:
# send_email(user, "Error Sending Push Notification", "Check your Pushover API keys in your profile. Original Message: " + message)
#
# Path: hashview/models.py
# class Users(db.Model, UserMixin):
# id = db.Column(db.Integer, primary_key=True)
# first_name = db.Column(db.String(20), nullable=False)
# last_name = db.Column(db.String(20), nullable=False)
# email_address = db.Column(db.String(50), unique=True, nullable=False)
# password = db.Column(db.String(60), nullable=False)
# admin = db.Column(db.Boolean, nullable=False, default=False)
# pushover_app_id = db.Column(db.String(50), nullable=True)
# pushover_user_key = db.Column(db.String(50), nullable=True)
# wordlists = db.relationship('Wordlists', backref='tbd', lazy=True)
# rules = db.relationship('Rules', backref='owner', lazy=True)
# jobs = db.relationship('Jobs', backref='owner', lazy=True)
# tasks = db.relationship('Tasks', backref='owner', lazy=True)
# taskgroups = db.relationship('TaskGroups', backref='owner', lazy=True)
#
# def get_reset_token(self, expires_sec=1800):
# s = Serializer(Config.SECRET_KEY, expires_sec)
# return s.dumps({'user_id': self.id}).decode('utf-8')
#
# @staticmethod
# def verify_reset_token(token):
# s = Serializer(Config.SECRET_KEY)
# try:
# user_id = s.loads(token)['user_id']
# except:
# return None
# return Users.query.get(user_id)
#
# Path: hashview.py
# def data_retention_cleanup():
, which may contain function names, class names, or code. Output only the next line. | 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:
current_user.pushover_user_key = form.pushover_user_key.data
if form.pushover_app_id.data:
current_user.pushover_app_id = form.pushover_app_id.data
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_template('profile.html', title='Profile', form=form, current_user=current_user)
@users.route("/profile/send_test_pushover", methods=['GET'])
@login_required
def send_test_pushover():
user = Users.query.get(current_user.id)
send_pushover(user, 'Test Message From Hashview', 'This is a test pushover message from hashview')
flash('Pushover Sent', 'success')
return redirect(url_for('users.profile'))
@users.route("/reset_password", methods=['GET', 'POST'])
def reset_request():
<|code_end|>
, determine the next line of code. You have imports:
from flask import Blueprint, render_template, url_for, flash, abort, redirect, request
from flask_login import login_required, logout_user, current_user, login_user
from hashview.users.forms import LoginForm, UsersForm, ProfileForm, RequestResetForm, ResetPasswordForm
from hashview.utils.utils import send_email, send_pushover
from hashview.models import Users
from hashview import db, bcrypt
and context (class names, function names, or code) available:
# Path: hashview/users/forms.py
# class LoginForm(FlaskForm):
# email = StringField('Email', validators=[DataRequired(), Email()])
# password = PasswordField('Password', validators=[DataRequired()])
# remember = BooleanField('Remember Me')
# submit = SubmitField('Login')
#
# class UsersForm(FlaskForm):
# first_name = StringField('First Name', validators=[DataRequired(), Length(min=1, max=20)])
# last_name = StringField('Last Name', validators=[DataRequired(), Length(min=1, max=20)])
# email = StringField('Email', validators=[DataRequired(), Email()])
# is_admin = BooleanField('Is Admin')
# password = PasswordField('Password', validators=[DataRequired(), Length(min=14)])
# confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
# pushover_app_id = StringField('Pushover App Token (optional)')
# pushover_user_key = StringField('Pushover User Key (optional)')
# submit = SubmitField('Register')
#
# def validate_email(self, email):
# user = Users.query.filter_by(email_address = email.data).first()
# if user:
# raise ValidationError('That email address is taken. Please choose a different one.')
#
# def validate_pushover(self, pushover_app_id, pushover_user_key):
# if len(pushover_app_id.data) > 0 and len(pushover_user_key.data) == 0:
# raise ValidationError('You must supply both options to use.')
# if len(pushover_app_id.data) == 0 and len(pushover_user_key.data) > 0:
# raise ValidationError('You must supply both options to use.')
#
# class ProfileForm(FlaskForm):
# first_name = StringField('First Name', validators=[DataRequired(), Length(min=1, max=20)])
# last_name = StringField('Last Name', validators=[DataRequired(), Length(min=1, max=20)])
# pushover_user_key = StringField('Pushover User Key (optional)')
# pushover_app_id = StringField('Pushover App Id (optional)')
# submit = SubmitField('Update')
#
# class RequestResetForm(FlaskForm):
# email = StringField('Email', validators=[DataRequired(), Email()])
# submit = SubmitField('Request Password Reset')
#
# class ResetPasswordForm(FlaskForm):
# password = PasswordField('Password', validators=[DataRequired(), Length(min=14)])
# confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
# submit = SubmitField('Reset Password')
#
# Path: hashview/utils/utils.py
# def send_email(user, subject, message):
# msg = Message(subject, recipients=[user.email_address])
# msg.body = message
# mail.send(msg)
#
# def send_pushover(user, subject, message):
# if user.pushover_user_key and user.pushover_app_id:
# client = Client(user.pushover_user_key, api_token=user.pushover_app_id)
# try:
# client.send_message(message, title=subject)
# except:
# send_email(user, "Error Sending Push Notification", "Check your Pushover API keys in your profile. Original Message: " + message)
#
# Path: hashview/models.py
# class Users(db.Model, UserMixin):
# id = db.Column(db.Integer, primary_key=True)
# first_name = db.Column(db.String(20), nullable=False)
# last_name = db.Column(db.String(20), nullable=False)
# email_address = db.Column(db.String(50), unique=True, nullable=False)
# password = db.Column(db.String(60), nullable=False)
# admin = db.Column(db.Boolean, nullable=False, default=False)
# pushover_app_id = db.Column(db.String(50), nullable=True)
# pushover_user_key = db.Column(db.String(50), nullable=True)
# wordlists = db.relationship('Wordlists', backref='tbd', lazy=True)
# rules = db.relationship('Rules', backref='owner', lazy=True)
# jobs = db.relationship('Jobs', backref='owner', lazy=True)
# tasks = db.relationship('Tasks', backref='owner', lazy=True)
# taskgroups = db.relationship('TaskGroups', backref='owner', lazy=True)
#
# def get_reset_token(self, expires_sec=1800):
# s = Serializer(Config.SECRET_KEY, expires_sec)
# return s.dumps({'user_id': self.id}).decode('utf-8')
#
# @staticmethod
# def verify_reset_token(token):
# s = Serializer(Config.SECRET_KEY)
# try:
# user_id = s.loads(token)['user_id']
# except:
# return None
# return Users.query.get(user_id)
#
# Path: hashview.py
# def data_retention_cleanup():
. Output only the next line. | 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'])
@login_required
def admin_reset(user_id):
if current_user.admin:
user = Users.query.get(user_id)
token = user.get_reset_token()
subject = 'Password Reset Request.'
message = f'''To reset your password, vist the following link:
{url_for('users.reset_token', token=token, _external=True)}
If you did not make this request... then something phishy is going on.
'''
send_email(user, subject, message)
flash('An email has been sent to '+ user.email_address, 'info')
return redirect(url_for('users.users_list'))
else:
flash('Unauthorized to reset users account.', 'danger')
return redirect(url_for('users.users_list'))
@users.route("/reset_password/<token>", methods=['GET', 'POST'])
def reset_token(token):
user = Users.verify_reset_token(token)
if user is None:
flash('Invalid or Expired Token!', 'warning')
return redirect(url_for('main.home'))
<|code_end|>
. Use current file imports:
from flask import Blueprint, render_template, url_for, flash, abort, redirect, request
from flask_login import login_required, logout_user, current_user, login_user
from hashview.users.forms import LoginForm, UsersForm, ProfileForm, RequestResetForm, ResetPasswordForm
from hashview.utils.utils import send_email, send_pushover
from hashview.models import Users
from hashview import db, bcrypt
and context (classes, functions, or code) from other files:
# Path: hashview/users/forms.py
# class LoginForm(FlaskForm):
# email = StringField('Email', validators=[DataRequired(), Email()])
# password = PasswordField('Password', validators=[DataRequired()])
# remember = BooleanField('Remember Me')
# submit = SubmitField('Login')
#
# class UsersForm(FlaskForm):
# first_name = StringField('First Name', validators=[DataRequired(), Length(min=1, max=20)])
# last_name = StringField('Last Name', validators=[DataRequired(), Length(min=1, max=20)])
# email = StringField('Email', validators=[DataRequired(), Email()])
# is_admin = BooleanField('Is Admin')
# password = PasswordField('Password', validators=[DataRequired(), Length(min=14)])
# confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
# pushover_app_id = StringField('Pushover App Token (optional)')
# pushover_user_key = StringField('Pushover User Key (optional)')
# submit = SubmitField('Register')
#
# def validate_email(self, email):
# user = Users.query.filter_by(email_address = email.data).first()
# if user:
# raise ValidationError('That email address is taken. Please choose a different one.')
#
# def validate_pushover(self, pushover_app_id, pushover_user_key):
# if len(pushover_app_id.data) > 0 and len(pushover_user_key.data) == 0:
# raise ValidationError('You must supply both options to use.')
# if len(pushover_app_id.data) == 0 and len(pushover_user_key.data) > 0:
# raise ValidationError('You must supply both options to use.')
#
# class ProfileForm(FlaskForm):
# first_name = StringField('First Name', validators=[DataRequired(), Length(min=1, max=20)])
# last_name = StringField('Last Name', validators=[DataRequired(), Length(min=1, max=20)])
# pushover_user_key = StringField('Pushover User Key (optional)')
# pushover_app_id = StringField('Pushover App Id (optional)')
# submit = SubmitField('Update')
#
# class RequestResetForm(FlaskForm):
# email = StringField('Email', validators=[DataRequired(), Email()])
# submit = SubmitField('Request Password Reset')
#
# class ResetPasswordForm(FlaskForm):
# password = PasswordField('Password', validators=[DataRequired(), Length(min=14)])
# confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
# submit = SubmitField('Reset Password')
#
# Path: hashview/utils/utils.py
# def send_email(user, subject, message):
# msg = Message(subject, recipients=[user.email_address])
# msg.body = message
# mail.send(msg)
#
# def send_pushover(user, subject, message):
# if user.pushover_user_key and user.pushover_app_id:
# client = Client(user.pushover_user_key, api_token=user.pushover_app_id)
# try:
# client.send_message(message, title=subject)
# except:
# send_email(user, "Error Sending Push Notification", "Check your Pushover API keys in your profile. Original Message: " + message)
#
# Path: hashview/models.py
# class Users(db.Model, UserMixin):
# id = db.Column(db.Integer, primary_key=True)
# first_name = db.Column(db.String(20), nullable=False)
# last_name = db.Column(db.String(20), nullable=False)
# email_address = db.Column(db.String(50), unique=True, nullable=False)
# password = db.Column(db.String(60), nullable=False)
# admin = db.Column(db.Boolean, nullable=False, default=False)
# pushover_app_id = db.Column(db.String(50), nullable=True)
# pushover_user_key = db.Column(db.String(50), nullable=True)
# wordlists = db.relationship('Wordlists', backref='tbd', lazy=True)
# rules = db.relationship('Rules', backref='owner', lazy=True)
# jobs = db.relationship('Jobs', backref='owner', lazy=True)
# tasks = db.relationship('Tasks', backref='owner', lazy=True)
# taskgroups = db.relationship('TaskGroups', backref='owner', lazy=True)
#
# def get_reset_token(self, expires_sec=1800):
# s = Serializer(Config.SECRET_KEY, expires_sec)
# return s.dumps({'user_id': self.id}).decode('utf-8')
#
# @staticmethod
# def verify_reset_token(token):
# s = Serializer(Config.SECRET_KEY)
# try:
# user_id = s.loads(token)['user_id']
# except:
# return None
# return Users.query.get(user_id)
#
# Path: hashview.py
# def data_retention_cleanup():
. Output only the next line. | 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_template('profile.html', title='Profile', form=form, current_user=current_user)
@users.route("/profile/send_test_pushover", methods=['GET'])
@login_required
def send_test_pushover():
user = Users.query.get(current_user.id)
send_pushover(user, 'Test Message From Hashview', 'This is a test pushover message from hashview')
flash('Pushover Sent', 'success')
return redirect(url_for('users.profile'))
@users.route("/reset_password", methods=['GET', 'POST'])
def reset_request():
form = RequestResetForm()
if form.validate_on_submit():
user = Users.query.filter_by(email_address=form.email.data).first()
if user:
token = user.get_reset_token()
subject = 'Password Reset Request.'
message = f'''To reset your password, vist the following link:
{url_for('users.reset_token', token=token, _external=True)}
If you did not make this request... then something phishy is going on.
'''
<|code_end|>
, predict the immediate next line with the help of imports:
from flask import Blueprint, render_template, url_for, flash, abort, redirect, request
from flask_login import login_required, logout_user, current_user, login_user
from hashview.users.forms import LoginForm, UsersForm, ProfileForm, RequestResetForm, ResetPasswordForm
from hashview.utils.utils import send_email, send_pushover
from hashview.models import Users
from hashview import db, bcrypt
and context (classes, functions, sometimes code) from other files:
# Path: hashview/users/forms.py
# class LoginForm(FlaskForm):
# email = StringField('Email', validators=[DataRequired(), Email()])
# password = PasswordField('Password', validators=[DataRequired()])
# remember = BooleanField('Remember Me')
# submit = SubmitField('Login')
#
# class UsersForm(FlaskForm):
# first_name = StringField('First Name', validators=[DataRequired(), Length(min=1, max=20)])
# last_name = StringField('Last Name', validators=[DataRequired(), Length(min=1, max=20)])
# email = StringField('Email', validators=[DataRequired(), Email()])
# is_admin = BooleanField('Is Admin')
# password = PasswordField('Password', validators=[DataRequired(), Length(min=14)])
# confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
# pushover_app_id = StringField('Pushover App Token (optional)')
# pushover_user_key = StringField('Pushover User Key (optional)')
# submit = SubmitField('Register')
#
# def validate_email(self, email):
# user = Users.query.filter_by(email_address = email.data).first()
# if user:
# raise ValidationError('That email address is taken. Please choose a different one.')
#
# def validate_pushover(self, pushover_app_id, pushover_user_key):
# if len(pushover_app_id.data) > 0 and len(pushover_user_key.data) == 0:
# raise ValidationError('You must supply both options to use.')
# if len(pushover_app_id.data) == 0 and len(pushover_user_key.data) > 0:
# raise ValidationError('You must supply both options to use.')
#
# class ProfileForm(FlaskForm):
# first_name = StringField('First Name', validators=[DataRequired(), Length(min=1, max=20)])
# last_name = StringField('Last Name', validators=[DataRequired(), Length(min=1, max=20)])
# pushover_user_key = StringField('Pushover User Key (optional)')
# pushover_app_id = StringField('Pushover App Id (optional)')
# submit = SubmitField('Update')
#
# class RequestResetForm(FlaskForm):
# email = StringField('Email', validators=[DataRequired(), Email()])
# submit = SubmitField('Request Password Reset')
#
# class ResetPasswordForm(FlaskForm):
# password = PasswordField('Password', validators=[DataRequired(), Length(min=14)])
# confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
# submit = SubmitField('Reset Password')
#
# Path: hashview/utils/utils.py
# def send_email(user, subject, message):
# msg = Message(subject, recipients=[user.email_address])
# msg.body = message
# mail.send(msg)
#
# def send_pushover(user, subject, message):
# if user.pushover_user_key and user.pushover_app_id:
# client = Client(user.pushover_user_key, api_token=user.pushover_app_id)
# try:
# client.send_message(message, title=subject)
# except:
# send_email(user, "Error Sending Push Notification", "Check your Pushover API keys in your profile. Original Message: " + message)
#
# Path: hashview/models.py
# class Users(db.Model, UserMixin):
# id = db.Column(db.Integer, primary_key=True)
# first_name = db.Column(db.String(20), nullable=False)
# last_name = db.Column(db.String(20), nullable=False)
# email_address = db.Column(db.String(50), unique=True, nullable=False)
# password = db.Column(db.String(60), nullable=False)
# admin = db.Column(db.Boolean, nullable=False, default=False)
# pushover_app_id = db.Column(db.String(50), nullable=True)
# pushover_user_key = db.Column(db.String(50), nullable=True)
# wordlists = db.relationship('Wordlists', backref='tbd', lazy=True)
# rules = db.relationship('Rules', backref='owner', lazy=True)
# jobs = db.relationship('Jobs', backref='owner', lazy=True)
# tasks = db.relationship('Tasks', backref='owner', lazy=True)
# taskgroups = db.relationship('TaskGroups', backref='owner', lazy=True)
#
# def get_reset_token(self, expires_sec=1800):
# s = Serializer(Config.SECRET_KEY, expires_sec)
# return s.dumps({'user_id': self.id}).decode('utf-8')
#
# @staticmethod
# def verify_reset_token(token):
# s = Serializer(Config.SECRET_KEY)
# try:
# user_id = s.loads(token)['user_id']
# except:
# return None
# return Users.query.get(user_id)
#
# Path: hashview.py
# def data_retention_cleanup():
. Output only the next line. | 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 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:
current_user.pushover_user_key = form.pushover_user_key.data
if form.pushover_app_id.data:
current_user.pushover_app_id = form.pushover_app_id.data
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_template('profile.html', title='Profile', form=form, current_user=current_user)
@users.route("/profile/send_test_pushover", methods=['GET'])
@login_required
def send_test_pushover():
user = Users.query.get(current_user.id)
<|code_end|>
using the current file's imports:
from flask import Blueprint, render_template, url_for, flash, abort, redirect, request
from flask_login import login_required, logout_user, current_user, login_user
from hashview.users.forms import LoginForm, UsersForm, ProfileForm, RequestResetForm, ResetPasswordForm
from hashview.utils.utils import send_email, send_pushover
from hashview.models import Users
from hashview import db, bcrypt
and any relevant context from other files:
# Path: hashview/users/forms.py
# class LoginForm(FlaskForm):
# email = StringField('Email', validators=[DataRequired(), Email()])
# password = PasswordField('Password', validators=[DataRequired()])
# remember = BooleanField('Remember Me')
# submit = SubmitField('Login')
#
# class UsersForm(FlaskForm):
# first_name = StringField('First Name', validators=[DataRequired(), Length(min=1, max=20)])
# last_name = StringField('Last Name', validators=[DataRequired(), Length(min=1, max=20)])
# email = StringField('Email', validators=[DataRequired(), Email()])
# is_admin = BooleanField('Is Admin')
# password = PasswordField('Password', validators=[DataRequired(), Length(min=14)])
# confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
# pushover_app_id = StringField('Pushover App Token (optional)')
# pushover_user_key = StringField('Pushover User Key (optional)')
# submit = SubmitField('Register')
#
# def validate_email(self, email):
# user = Users.query.filter_by(email_address = email.data).first()
# if user:
# raise ValidationError('That email address is taken. Please choose a different one.')
#
# def validate_pushover(self, pushover_app_id, pushover_user_key):
# if len(pushover_app_id.data) > 0 and len(pushover_user_key.data) == 0:
# raise ValidationError('You must supply both options to use.')
# if len(pushover_app_id.data) == 0 and len(pushover_user_key.data) > 0:
# raise ValidationError('You must supply both options to use.')
#
# class ProfileForm(FlaskForm):
# first_name = StringField('First Name', validators=[DataRequired(), Length(min=1, max=20)])
# last_name = StringField('Last Name', validators=[DataRequired(), Length(min=1, max=20)])
# pushover_user_key = StringField('Pushover User Key (optional)')
# pushover_app_id = StringField('Pushover App Id (optional)')
# submit = SubmitField('Update')
#
# class RequestResetForm(FlaskForm):
# email = StringField('Email', validators=[DataRequired(), Email()])
# submit = SubmitField('Request Password Reset')
#
# class ResetPasswordForm(FlaskForm):
# password = PasswordField('Password', validators=[DataRequired(), Length(min=14)])
# confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
# submit = SubmitField('Reset Password')
#
# Path: hashview/utils/utils.py
# def send_email(user, subject, message):
# msg = Message(subject, recipients=[user.email_address])
# msg.body = message
# mail.send(msg)
#
# def send_pushover(user, subject, message):
# if user.pushover_user_key and user.pushover_app_id:
# client = Client(user.pushover_user_key, api_token=user.pushover_app_id)
# try:
# client.send_message(message, title=subject)
# except:
# send_email(user, "Error Sending Push Notification", "Check your Pushover API keys in your profile. Original Message: " + message)
#
# Path: hashview/models.py
# class Users(db.Model, UserMixin):
# id = db.Column(db.Integer, primary_key=True)
# first_name = db.Column(db.String(20), nullable=False)
# last_name = db.Column(db.String(20), nullable=False)
# email_address = db.Column(db.String(50), unique=True, nullable=False)
# password = db.Column(db.String(60), nullable=False)
# admin = db.Column(db.Boolean, nullable=False, default=False)
# pushover_app_id = db.Column(db.String(50), nullable=True)
# pushover_user_key = db.Column(db.String(50), nullable=True)
# wordlists = db.relationship('Wordlists', backref='tbd', lazy=True)
# rules = db.relationship('Rules', backref='owner', lazy=True)
# jobs = db.relationship('Jobs', backref='owner', lazy=True)
# tasks = db.relationship('Tasks', backref='owner', lazy=True)
# taskgroups = db.relationship('TaskGroups', backref='owner', lazy=True)
#
# def get_reset_token(self, expires_sec=1800):
# s = Serializer(Config.SECRET_KEY, expires_sec)
# return s.dumps({'user_id': self.id}).decode('utf-8')
#
# @staticmethod
# def verify_reset_token(token):
# s = Serializer(Config.SECRET_KEY)
# try:
# user_id = s.loads(token)['user_id']
# except:
# return None
# return Users.query.get(user_id)
#
# Path: hashview.py
# def data_retention_cleanup():
. Output only the next line. | 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, flash, abort, redirect, request
from flask_login import login_required, logout_user, current_user, login_user
from hashview.users.forms import LoginForm, UsersForm, ProfileForm, RequestResetForm, ResetPasswordForm
from hashview.utils.utils import send_email, send_pushover
from hashview.models import Users
from hashview import db, bcrypt
and any relevant context from other files:
# Path: hashview/users/forms.py
# class LoginForm(FlaskForm):
# email = StringField('Email', validators=[DataRequired(), Email()])
# password = PasswordField('Password', validators=[DataRequired()])
# remember = BooleanField('Remember Me')
# submit = SubmitField('Login')
#
# class UsersForm(FlaskForm):
# first_name = StringField('First Name', validators=[DataRequired(), Length(min=1, max=20)])
# last_name = StringField('Last Name', validators=[DataRequired(), Length(min=1, max=20)])
# email = StringField('Email', validators=[DataRequired(), Email()])
# is_admin = BooleanField('Is Admin')
# password = PasswordField('Password', validators=[DataRequired(), Length(min=14)])
# confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
# pushover_app_id = StringField('Pushover App Token (optional)')
# pushover_user_key = StringField('Pushover User Key (optional)')
# submit = SubmitField('Register')
#
# def validate_email(self, email):
# user = Users.query.filter_by(email_address = email.data).first()
# if user:
# raise ValidationError('That email address is taken. Please choose a different one.')
#
# def validate_pushover(self, pushover_app_id, pushover_user_key):
# if len(pushover_app_id.data) > 0 and len(pushover_user_key.data) == 0:
# raise ValidationError('You must supply both options to use.')
# if len(pushover_app_id.data) == 0 and len(pushover_user_key.data) > 0:
# raise ValidationError('You must supply both options to use.')
#
# class ProfileForm(FlaskForm):
# first_name = StringField('First Name', validators=[DataRequired(), Length(min=1, max=20)])
# last_name = StringField('Last Name', validators=[DataRequired(), Length(min=1, max=20)])
# pushover_user_key = StringField('Pushover User Key (optional)')
# pushover_app_id = StringField('Pushover App Id (optional)')
# submit = SubmitField('Update')
#
# class RequestResetForm(FlaskForm):
# email = StringField('Email', validators=[DataRequired(), Email()])
# submit = SubmitField('Request Password Reset')
#
# class ResetPasswordForm(FlaskForm):
# password = PasswordField('Password', validators=[DataRequired(), Length(min=14)])
# confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
# submit = SubmitField('Reset Password')
#
# Path: hashview/utils/utils.py
# def send_email(user, subject, message):
# msg = Message(subject, recipients=[user.email_address])
# msg.body = message
# mail.send(msg)
#
# def send_pushover(user, subject, message):
# if user.pushover_user_key and user.pushover_app_id:
# client = Client(user.pushover_user_key, api_token=user.pushover_app_id)
# try:
# client.send_message(message, title=subject)
# except:
# send_email(user, "Error Sending Push Notification", "Check your Pushover API keys in your profile. Original Message: " + message)
#
# Path: hashview/models.py
# class Users(db.Model, UserMixin):
# id = db.Column(db.Integer, primary_key=True)
# first_name = db.Column(db.String(20), nullable=False)
# last_name = db.Column(db.String(20), nullable=False)
# email_address = db.Column(db.String(50), unique=True, nullable=False)
# password = db.Column(db.String(60), nullable=False)
# admin = db.Column(db.Boolean, nullable=False, default=False)
# pushover_app_id = db.Column(db.String(50), nullable=True)
# pushover_user_key = db.Column(db.String(50), nullable=True)
# wordlists = db.relationship('Wordlists', backref='tbd', lazy=True)
# rules = db.relationship('Rules', backref='owner', lazy=True)
# jobs = db.relationship('Jobs', backref='owner', lazy=True)
# tasks = db.relationship('Tasks', backref='owner', lazy=True)
# taskgroups = db.relationship('TaskGroups', backref='owner', lazy=True)
#
# def get_reset_token(self, expires_sec=1800):
# s = Serializer(Config.SECRET_KEY, expires_sec)
# return s.dumps({'user_id': self.id}).decode('utf-8')
#
# @staticmethod
# def verify_reset_token(token):
# s = Serializer(Config.SECRET_KEY)
# try:
# user_id = s.loads(token)['user_id']
# except:
# return None
# return Users.query.get(user_id)
#
# Path: hashview.py
# def data_retention_cleanup():
. Output only the next line. | 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 current file's imports:
from flask import Blueprint, render_template, url_for, flash, abort, redirect, request
from flask_login import login_required, logout_user, current_user, login_user
from hashview.users.forms import LoginForm, UsersForm, ProfileForm, RequestResetForm, ResetPasswordForm
from hashview.utils.utils import send_email, send_pushover
from hashview.models import Users
from hashview import db, bcrypt
and any relevant context from other files:
# Path: hashview/users/forms.py
# class LoginForm(FlaskForm):
# email = StringField('Email', validators=[DataRequired(), Email()])
# password = PasswordField('Password', validators=[DataRequired()])
# remember = BooleanField('Remember Me')
# submit = SubmitField('Login')
#
# class UsersForm(FlaskForm):
# first_name = StringField('First Name', validators=[DataRequired(), Length(min=1, max=20)])
# last_name = StringField('Last Name', validators=[DataRequired(), Length(min=1, max=20)])
# email = StringField('Email', validators=[DataRequired(), Email()])
# is_admin = BooleanField('Is Admin')
# password = PasswordField('Password', validators=[DataRequired(), Length(min=14)])
# confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
# pushover_app_id = StringField('Pushover App Token (optional)')
# pushover_user_key = StringField('Pushover User Key (optional)')
# submit = SubmitField('Register')
#
# def validate_email(self, email):
# user = Users.query.filter_by(email_address = email.data).first()
# if user:
# raise ValidationError('That email address is taken. Please choose a different one.')
#
# def validate_pushover(self, pushover_app_id, pushover_user_key):
# if len(pushover_app_id.data) > 0 and len(pushover_user_key.data) == 0:
# raise ValidationError('You must supply both options to use.')
# if len(pushover_app_id.data) == 0 and len(pushover_user_key.data) > 0:
# raise ValidationError('You must supply both options to use.')
#
# class ProfileForm(FlaskForm):
# first_name = StringField('First Name', validators=[DataRequired(), Length(min=1, max=20)])
# last_name = StringField('Last Name', validators=[DataRequired(), Length(min=1, max=20)])
# pushover_user_key = StringField('Pushover User Key (optional)')
# pushover_app_id = StringField('Pushover App Id (optional)')
# submit = SubmitField('Update')
#
# class RequestResetForm(FlaskForm):
# email = StringField('Email', validators=[DataRequired(), Email()])
# submit = SubmitField('Request Password Reset')
#
# class ResetPasswordForm(FlaskForm):
# password = PasswordField('Password', validators=[DataRequired(), Length(min=14)])
# confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
# submit = SubmitField('Reset Password')
#
# Path: hashview/utils/utils.py
# def send_email(user, subject, message):
# msg = Message(subject, recipients=[user.email_address])
# msg.body = message
# mail.send(msg)
#
# def send_pushover(user, subject, message):
# if user.pushover_user_key and user.pushover_app_id:
# client = Client(user.pushover_user_key, api_token=user.pushover_app_id)
# try:
# client.send_message(message, title=subject)
# except:
# send_email(user, "Error Sending Push Notification", "Check your Pushover API keys in your profile. Original Message: " + message)
#
# Path: hashview/models.py
# class Users(db.Model, UserMixin):
# id = db.Column(db.Integer, primary_key=True)
# first_name = db.Column(db.String(20), nullable=False)
# last_name = db.Column(db.String(20), nullable=False)
# email_address = db.Column(db.String(50), unique=True, nullable=False)
# password = db.Column(db.String(60), nullable=False)
# admin = db.Column(db.Boolean, nullable=False, default=False)
# pushover_app_id = db.Column(db.String(50), nullable=True)
# pushover_user_key = db.Column(db.String(50), nullable=True)
# wordlists = db.relationship('Wordlists', backref='tbd', lazy=True)
# rules = db.relationship('Rules', backref='owner', lazy=True)
# jobs = db.relationship('Jobs', backref='owner', lazy=True)
# tasks = db.relationship('Tasks', backref='owner', lazy=True)
# taskgroups = db.relationship('TaskGroups', backref='owner', lazy=True)
#
# def get_reset_token(self, expires_sec=1800):
# s = Serializer(Config.SECRET_KEY, expires_sec)
# return s.dumps({'user_id': self.id}).decode('utf-8')
#
# @staticmethod
# def verify_reset_token(token):
# s = Serializer(Config.SECRET_KEY)
# try:
# user_id = s.loads(token)['user_id']
# except:
# return None
# return Users.query.get(user_id)
#
# Path: hashview.py
# def data_retention_cleanup():
. Output only the next line. | 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 parameters are given as a single list
*a=[a0,a1,a2,a3]* and it returns the pressure not the energy from the EOS.
"""
return a[2]/a[3]*(pow(a[1]/V,a[3])-1.0)
def H_Murn(V,a):
"""
As :py:func:`E_MurnV` but input parameters are given as a single list
*a=[a0,a1,a2,a3]* and it returns the enthalpy not the energy from the EOS.
"""
return E_Murn(V,a)+P_Murn(V,a)*V
################################################################################
def print_eos_data(x,y,a,chi,ylabel="Etot"):
"""
Print the data and the fitted results using the Murnaghan EOS. It can be used for
different fitted quantities using the proper ylabel. ylabel can be "Etot",
"Fvib", etc.
"""
print ("# Murnaghan EOS \t\t chi squared= {:.10e}".format(chi))
<|code_end|>
with the help of current file imports:
from .constants import RY_KBAR
from math import pow
from scipy.optimize import curve_fit
from scipy import interpolate
import numpy as np
and context from other files:
# Path: pyqha/constants.py
# RY_KBAR = 10.0 * AU_GPA / 2.0
, which may contain function names, class names, or code. Output only the next line. | 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 function parameters
for the call in pool.map
it[0]== 0 -> use V, S, average frequencies and gruneisen parameters at 0 K
it[0]== 1 -> use S at 0 K, calculate V, average frequencies and gruneisen parameters at each T
it[0]== 2 -> calculate S, V, average frequencies and gruneisen parameters at each T
"""
alphaT = []
if (it[0]==0): # use V, S, average frequencies and gruneisen parameters at 0 K
for i in range(it[1],it[2]+1):
alpha = compute_alpha_grun(it[3][i],it[4],it[5],it[6],it[7],it[8],it[9])
print ("T= "+str(it[3][i])+"\nalpha = ", alpha)
alphaT.append(alpha)
elif (it[0]==1): # use S at 0 K, calculate V, average frequencies and gruneisen parameters at each T
for i in range(it[1],it[2]+1):
V=compute_volume(it[11][i],it[9])
freq, grun = freqmingrun(it[10],it[11][i],it[12],it[13],it[9],it[14])
alpha = compute_alpha_grun(it[3][i],V,it[5],it[6],freq,grun,it[9])
print ("V = ",str(V),"\nT= "+str(it[3][i])+"\nalpha = ", alpha)
alphaT.append(alpha)
elif (it[0]==2): # calculate V, average frequencies, gruneisen parameters ans S at each T
for i in range(it[1],it[2]+1):
V=compute_volume(it[11][i],it[9])
S = fS(it[15],it[11][i],it[16])
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
import math
from .constants import RY_KBAR, K_BOLTZMANN_RY, KB1
from .fitfreqgrun import freqmingrun
from .properties_anis import compute_volume
from .fitC import fS
from multiprocessing import Pool
from grunc import c_qvc # This is the same routine c_qv implemented in C to speed it up
and context (classes, functions, sometimes code) from other files:
# Path: pyqha/constants.py
# RY_KBAR = 10.0 * AU_GPA / 2.0
#
# K_BOLTZMANN_RY = K_BOLTZMANN_SI / RYDBERG_SI
#
# KB1=1.0/K_BOLTZMANN_RY/RY_TO_CMM1 # inverse Boltzmann constant in cm^{-1}/K
#
# Path: pyqha/fitfreqgrun.py
# def freqmingrun(afreq, min0, nq, modes, ibrav, typefreq):
# """
# This function calculates the frequencies and the Gruneisen parameters
# from the fitted polynomials coeffients (one
# for each q point and mode) at the minimun point *min0* given in input.
# *afreq* is a :math:`nq*modes` numpy matrix containing the fitted polynomial coefficients.
# It can be obtained from :py:func:`fitfreqxx`.
#
# It returns a :math:`nq*modes` matrix, each element [i,j] being the fitted frequency
# In addition, it returns a :math:`nq*modes*6` with the Gruneisein parameters.
# Each element [i,j,k] is the the Gruneisein parameter at *nq=i*, *mode=j* and direction
# *k* (for example, in hex systems *k=0* is *a* direction, *k=2* is *c* direction, others are zero)
#
# Note that the Gruneisein parameters are not multiplied for the lattice parameters.
# """
# #nq = 10 # for testing quickly
# f = np.zeros((nq,modes))
# grun = np.zeros((6,nq,modes)) # initialize the Gruneisein parameters matrix
# for i in range(0,nq):
# for j in range(0,modes):
# if typefreq=="quadratic":
# f[i,j] = fquadratic(min0,afreq[i][j],ibrav=4)
# if f[i,j]<1E-5:
# grun[:,i,j] = 0.0
# else:
# grun[:,i,j] = fquadratic_der(min0,afreq[i][j],ibrav)/f[i,j]*min0
# elif typefreq=="quartic":
# f[i,j] = fquartic(min0,afreq[i][j],ibrav=4)
# if f[i,j]<1E-5:
# grun[:,i,j] = 0.0
# else:
# grun[:,i,j] = fquartic_der(min0,afreq[i][j],ibrav)/f[i,j]*min0
#
# return f, grun
#
# Path: pyqha/properties_anis.py
# def compute_volume(celldms,ibrav=4):
# """
# Compute the volume given the *celldms*. Only for ibrav=4 for now, else
# returns 0.
# """
# if ibrav==4:
# return 0.866025404*celldms[0]*celldms[0]*celldms[2]
#
# return 0
#
# Path: pyqha/fitC.py
# def fS(aS,mintemp,typeCx):
# """
# An auxiliary function returning the elastic compliances 6x6 tensor at the
# set of lattice parameters given in input as *mintemp*. These should be the
# lattice parameters at a given temperature obtained from the free energy
# minimization, so that S(T) can be obtained.
# Before calling this function, the polynomial coefficients resulting from
# fitting the elastic compliances over a grid of lattice parameters, i.e. over
# different geometries, must be obtained and passed as input in *aS*.
# *typeCx* defines what kind of polynomial to use for fitting ("quadratic" or
# "quartic")
# """
# S = np.zeros((6,6))
# for i in range(0,6):
# for j in range(0,6):
# if typeCx=="quadratic":
# S[i,j] = fquadratic(mintemp,aS[i,j],ibrav=4)
# elif typeCx=="quartic":
# S[i,j] = fquartic(mintemp,aS[i,j],ibrav=4)
# return S
. Output only the next line. | 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 module available
#
is_grunc = False
try:
is_grunc = True
except:
print ("Warning: C module c_qvc not imported, using python (slower) version.")
################################################################################
#
def c_qv_python(T,omega):
"""
This function calculates the mode contribution to the heat capacity at a given T
and omega. A similar (faster) function should be available as C extension.
"""
#print ("Python c_qv")
if (T<1E-9 or omega<1E-9):
return 0.0
x = omega * KB1 / T
expx = math.exp(-x) # exponential term
x2 = math.pow(x,2)
if expx>1E-3: # compute normally
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
import math
from .constants import RY_KBAR, K_BOLTZMANN_RY, KB1
from .fitfreqgrun import freqmingrun
from .properties_anis import compute_volume
from .fitC import fS
from multiprocessing import Pool
from grunc import c_qvc # This is the same routine c_qv implemented in C to speed it up
and context (class names, function names, or code) available:
# Path: pyqha/constants.py
# RY_KBAR = 10.0 * AU_GPA / 2.0
#
# K_BOLTZMANN_RY = K_BOLTZMANN_SI / RYDBERG_SI
#
# KB1=1.0/K_BOLTZMANN_RY/RY_TO_CMM1 # inverse Boltzmann constant in cm^{-1}/K
#
# Path: pyqha/fitfreqgrun.py
# def freqmingrun(afreq, min0, nq, modes, ibrav, typefreq):
# """
# This function calculates the frequencies and the Gruneisen parameters
# from the fitted polynomials coeffients (one
# for each q point and mode) at the minimun point *min0* given in input.
# *afreq* is a :math:`nq*modes` numpy matrix containing the fitted polynomial coefficients.
# It can be obtained from :py:func:`fitfreqxx`.
#
# It returns a :math:`nq*modes` matrix, each element [i,j] being the fitted frequency
# In addition, it returns a :math:`nq*modes*6` with the Gruneisein parameters.
# Each element [i,j,k] is the the Gruneisein parameter at *nq=i*, *mode=j* and direction
# *k* (for example, in hex systems *k=0* is *a* direction, *k=2* is *c* direction, others are zero)
#
# Note that the Gruneisein parameters are not multiplied for the lattice parameters.
# """
# #nq = 10 # for testing quickly
# f = np.zeros((nq,modes))
# grun = np.zeros((6,nq,modes)) # initialize the Gruneisein parameters matrix
# for i in range(0,nq):
# for j in range(0,modes):
# if typefreq=="quadratic":
# f[i,j] = fquadratic(min0,afreq[i][j],ibrav=4)
# if f[i,j]<1E-5:
# grun[:,i,j] = 0.0
# else:
# grun[:,i,j] = fquadratic_der(min0,afreq[i][j],ibrav)/f[i,j]*min0
# elif typefreq=="quartic":
# f[i,j] = fquartic(min0,afreq[i][j],ibrav=4)
# if f[i,j]<1E-5:
# grun[:,i,j] = 0.0
# else:
# grun[:,i,j] = fquartic_der(min0,afreq[i][j],ibrav)/f[i,j]*min0
#
# return f, grun
#
# Path: pyqha/properties_anis.py
# def compute_volume(celldms,ibrav=4):
# """
# Compute the volume given the *celldms*. Only for ibrav=4 for now, else
# returns 0.
# """
# if ibrav==4:
# return 0.866025404*celldms[0]*celldms[0]*celldms[2]
#
# return 0
#
# Path: pyqha/fitC.py
# def fS(aS,mintemp,typeCx):
# """
# An auxiliary function returning the elastic compliances 6x6 tensor at the
# set of lattice parameters given in input as *mintemp*. These should be the
# lattice parameters at a given temperature obtained from the free energy
# minimization, so that S(T) can be obtained.
# Before calling this function, the polynomial coefficients resulting from
# fitting the elastic compliances over a grid of lattice parameters, i.e. over
# different geometries, must be obtained and passed as input in *aS*.
# *typeCx* defines what kind of polynomial to use for fitting ("quadratic" or
# "quartic")
# """
# S = np.zeros((6,6))
# for i in range(0,6):
# for j in range(0,6):
# if typeCx=="quadratic":
# S[i,j] = fquadratic(mintemp,aS[i,j],ibrav=4)
# elif typeCx=="quartic":
# S[i,j] = fquartic(mintemp,aS[i,j],ibrav=4)
# return S
. Output only the next line. | 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 (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 module available
#
is_grunc = False
try:
is_grunc = True
except:
print ("Warning: C module c_qvc not imported, using python (slower) version.")
################################################################################
#
def c_qv_python(T,omega):
"""
This function calculates the mode contribution to the heat capacity at a given T
and omega. A similar (faster) function should be available as C extension.
"""
#print ("Python c_qv")
if (T<1E-9 or omega<1E-9):
return 0.0
<|code_end|>
. Use current file imports:
import numpy as np
import math
from .constants import RY_KBAR, K_BOLTZMANN_RY, KB1
from .fitfreqgrun import freqmingrun
from .properties_anis import compute_volume
from .fitC import fS
from multiprocessing import Pool
from grunc import c_qvc # This is the same routine c_qv implemented in C to speed it up
and context (classes, functions, or code) from other files:
# Path: pyqha/constants.py
# RY_KBAR = 10.0 * AU_GPA / 2.0
#
# K_BOLTZMANN_RY = K_BOLTZMANN_SI / RYDBERG_SI
#
# KB1=1.0/K_BOLTZMANN_RY/RY_TO_CMM1 # inverse Boltzmann constant in cm^{-1}/K
#
# Path: pyqha/fitfreqgrun.py
# def freqmingrun(afreq, min0, nq, modes, ibrav, typefreq):
# """
# This function calculates the frequencies and the Gruneisen parameters
# from the fitted polynomials coeffients (one
# for each q point and mode) at the minimun point *min0* given in input.
# *afreq* is a :math:`nq*modes` numpy matrix containing the fitted polynomial coefficients.
# It can be obtained from :py:func:`fitfreqxx`.
#
# It returns a :math:`nq*modes` matrix, each element [i,j] being the fitted frequency
# In addition, it returns a :math:`nq*modes*6` with the Gruneisein parameters.
# Each element [i,j,k] is the the Gruneisein parameter at *nq=i*, *mode=j* and direction
# *k* (for example, in hex systems *k=0* is *a* direction, *k=2* is *c* direction, others are zero)
#
# Note that the Gruneisein parameters are not multiplied for the lattice parameters.
# """
# #nq = 10 # for testing quickly
# f = np.zeros((nq,modes))
# grun = np.zeros((6,nq,modes)) # initialize the Gruneisein parameters matrix
# for i in range(0,nq):
# for j in range(0,modes):
# if typefreq=="quadratic":
# f[i,j] = fquadratic(min0,afreq[i][j],ibrav=4)
# if f[i,j]<1E-5:
# grun[:,i,j] = 0.0
# else:
# grun[:,i,j] = fquadratic_der(min0,afreq[i][j],ibrav)/f[i,j]*min0
# elif typefreq=="quartic":
# f[i,j] = fquartic(min0,afreq[i][j],ibrav=4)
# if f[i,j]<1E-5:
# grun[:,i,j] = 0.0
# else:
# grun[:,i,j] = fquartic_der(min0,afreq[i][j],ibrav)/f[i,j]*min0
#
# return f, grun
#
# Path: pyqha/properties_anis.py
# def compute_volume(celldms,ibrav=4):
# """
# Compute the volume given the *celldms*. Only for ibrav=4 for now, else
# returns 0.
# """
# if ibrav==4:
# return 0.866025404*celldms[0]*celldms[0]*celldms[2]
#
# return 0
#
# Path: pyqha/fitC.py
# def fS(aS,mintemp,typeCx):
# """
# An auxiliary function returning the elastic compliances 6x6 tensor at the
# set of lattice parameters given in input as *mintemp*. These should be the
# lattice parameters at a given temperature obtained from the free energy
# minimization, so that S(T) can be obtained.
# Before calling this function, the polynomial coefficients resulting from
# fitting the elastic compliances over a grid of lattice parameters, i.e. over
# different geometries, must be obtained and passed as input in *aS*.
# *typeCx* defines what kind of polynomial to use for fitting ("quadratic" or
# "quartic")
# """
# S = np.zeros((6,6))
# for i in range(0,6):
# for j in range(0,6):
# if typeCx=="quadratic":
# S[i,j] = fquadratic(mintemp,aS[i,j],ibrav=4)
# elif typeCx=="quartic":
# S[i,j] = fquartic(mintemp,aS[i,j],ibrav=4)
# return S
. Output only the next line. | 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
essentially calls the compute_alpha_grun function with the proper parameters
according to the selected option. "it" is a list with all function parameters
for the call in pool.map
it[0]== 0 -> use V, S, average frequencies and gruneisen parameters at 0 K
it[0]== 1 -> use S at 0 K, calculate V, average frequencies and gruneisen parameters at each T
it[0]== 2 -> calculate S, V, average frequencies and gruneisen parameters at each T
"""
alphaT = []
if (it[0]==0): # use V, S, average frequencies and gruneisen parameters at 0 K
for i in range(it[1],it[2]+1):
alpha = compute_alpha_grun(it[3][i],it[4],it[5],it[6],it[7],it[8],it[9])
print ("T= "+str(it[3][i])+"\nalpha = ", alpha)
alphaT.append(alpha)
elif (it[0]==1): # use S at 0 K, calculate V, average frequencies and gruneisen parameters at each T
for i in range(it[1],it[2]+1):
V=compute_volume(it[11][i],it[9])
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
import math
from .constants import RY_KBAR, K_BOLTZMANN_RY, KB1
from .fitfreqgrun import freqmingrun
from .properties_anis import compute_volume
from .fitC import fS
from multiprocessing import Pool
from grunc import c_qvc # This is the same routine c_qv implemented in C to speed it up
and context (class names, function names, or code) available:
# Path: pyqha/constants.py
# RY_KBAR = 10.0 * AU_GPA / 2.0
#
# K_BOLTZMANN_RY = K_BOLTZMANN_SI / RYDBERG_SI
#
# KB1=1.0/K_BOLTZMANN_RY/RY_TO_CMM1 # inverse Boltzmann constant in cm^{-1}/K
#
# Path: pyqha/fitfreqgrun.py
# def freqmingrun(afreq, min0, nq, modes, ibrav, typefreq):
# """
# This function calculates the frequencies and the Gruneisen parameters
# from the fitted polynomials coeffients (one
# for each q point and mode) at the minimun point *min0* given in input.
# *afreq* is a :math:`nq*modes` numpy matrix containing the fitted polynomial coefficients.
# It can be obtained from :py:func:`fitfreqxx`.
#
# It returns a :math:`nq*modes` matrix, each element [i,j] being the fitted frequency
# In addition, it returns a :math:`nq*modes*6` with the Gruneisein parameters.
# Each element [i,j,k] is the the Gruneisein parameter at *nq=i*, *mode=j* and direction
# *k* (for example, in hex systems *k=0* is *a* direction, *k=2* is *c* direction, others are zero)
#
# Note that the Gruneisein parameters are not multiplied for the lattice parameters.
# """
# #nq = 10 # for testing quickly
# f = np.zeros((nq,modes))
# grun = np.zeros((6,nq,modes)) # initialize the Gruneisein parameters matrix
# for i in range(0,nq):
# for j in range(0,modes):
# if typefreq=="quadratic":
# f[i,j] = fquadratic(min0,afreq[i][j],ibrav=4)
# if f[i,j]<1E-5:
# grun[:,i,j] = 0.0
# else:
# grun[:,i,j] = fquadratic_der(min0,afreq[i][j],ibrav)/f[i,j]*min0
# elif typefreq=="quartic":
# f[i,j] = fquartic(min0,afreq[i][j],ibrav=4)
# if f[i,j]<1E-5:
# grun[:,i,j] = 0.0
# else:
# grun[:,i,j] = fquartic_der(min0,afreq[i][j],ibrav)/f[i,j]*min0
#
# return f, grun
#
# Path: pyqha/properties_anis.py
# def compute_volume(celldms,ibrav=4):
# """
# Compute the volume given the *celldms*. Only for ibrav=4 for now, else
# returns 0.
# """
# if ibrav==4:
# return 0.866025404*celldms[0]*celldms[0]*celldms[2]
#
# return 0
#
# Path: pyqha/fitC.py
# def fS(aS,mintemp,typeCx):
# """
# An auxiliary function returning the elastic compliances 6x6 tensor at the
# set of lattice parameters given in input as *mintemp*. These should be the
# lattice parameters at a given temperature obtained from the free energy
# minimization, so that S(T) can be obtained.
# Before calling this function, the polynomial coefficients resulting from
# fitting the elastic compliances over a grid of lattice parameters, i.e. over
# different geometries, must be obtained and passed as input in *aS*.
# *typeCx* defines what kind of polynomial to use for fitting ("quadratic" or
# "quartic")
# """
# S = np.zeros((6,6))
# for i in range(0,6):
# for j in range(0,6):
# if typeCx=="quadratic":
# S[i,j] = fquadratic(mintemp,aS[i,j],ibrav=4)
# elif typeCx=="quartic":
# S[i,j] = fquartic(mintemp,aS[i,j],ibrav=4)
# return S
. Output only the next line. | 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 calls the compute_alpha_grun function with the proper parameters
according to the selected option. "it" is a list with all function parameters
for the call in pool.map
it[0]== 0 -> use V, S, average frequencies and gruneisen parameters at 0 K
it[0]== 1 -> use S at 0 K, calculate V, average frequencies and gruneisen parameters at each T
it[0]== 2 -> calculate S, V, average frequencies and gruneisen parameters at each T
"""
alphaT = []
if (it[0]==0): # use V, S, average frequencies and gruneisen parameters at 0 K
for i in range(it[1],it[2]+1):
alpha = compute_alpha_grun(it[3][i],it[4],it[5],it[6],it[7],it[8],it[9])
print ("T= "+str(it[3][i])+"\nalpha = ", alpha)
alphaT.append(alpha)
elif (it[0]==1): # use S at 0 K, calculate V, average frequencies and gruneisen parameters at each T
for i in range(it[1],it[2]+1):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
import math
from .constants import RY_KBAR, K_BOLTZMANN_RY, KB1
from .fitfreqgrun import freqmingrun
from .properties_anis import compute_volume
from .fitC import fS
from multiprocessing import Pool
from grunc import c_qvc # This is the same routine c_qv implemented in C to speed it up
and context:
# Path: pyqha/constants.py
# RY_KBAR = 10.0 * AU_GPA / 2.0
#
# K_BOLTZMANN_RY = K_BOLTZMANN_SI / RYDBERG_SI
#
# KB1=1.0/K_BOLTZMANN_RY/RY_TO_CMM1 # inverse Boltzmann constant in cm^{-1}/K
#
# Path: pyqha/fitfreqgrun.py
# def freqmingrun(afreq, min0, nq, modes, ibrav, typefreq):
# """
# This function calculates the frequencies and the Gruneisen parameters
# from the fitted polynomials coeffients (one
# for each q point and mode) at the minimun point *min0* given in input.
# *afreq* is a :math:`nq*modes` numpy matrix containing the fitted polynomial coefficients.
# It can be obtained from :py:func:`fitfreqxx`.
#
# It returns a :math:`nq*modes` matrix, each element [i,j] being the fitted frequency
# In addition, it returns a :math:`nq*modes*6` with the Gruneisein parameters.
# Each element [i,j,k] is the the Gruneisein parameter at *nq=i*, *mode=j* and direction
# *k* (for example, in hex systems *k=0* is *a* direction, *k=2* is *c* direction, others are zero)
#
# Note that the Gruneisein parameters are not multiplied for the lattice parameters.
# """
# #nq = 10 # for testing quickly
# f = np.zeros((nq,modes))
# grun = np.zeros((6,nq,modes)) # initialize the Gruneisein parameters matrix
# for i in range(0,nq):
# for j in range(0,modes):
# if typefreq=="quadratic":
# f[i,j] = fquadratic(min0,afreq[i][j],ibrav=4)
# if f[i,j]<1E-5:
# grun[:,i,j] = 0.0
# else:
# grun[:,i,j] = fquadratic_der(min0,afreq[i][j],ibrav)/f[i,j]*min0
# elif typefreq=="quartic":
# f[i,j] = fquartic(min0,afreq[i][j],ibrav=4)
# if f[i,j]<1E-5:
# grun[:,i,j] = 0.0
# else:
# grun[:,i,j] = fquartic_der(min0,afreq[i][j],ibrav)/f[i,j]*min0
#
# return f, grun
#
# Path: pyqha/properties_anis.py
# def compute_volume(celldms,ibrav=4):
# """
# Compute the volume given the *celldms*. Only for ibrav=4 for now, else
# returns 0.
# """
# if ibrav==4:
# return 0.866025404*celldms[0]*celldms[0]*celldms[2]
#
# return 0
#
# Path: pyqha/fitC.py
# def fS(aS,mintemp,typeCx):
# """
# An auxiliary function returning the elastic compliances 6x6 tensor at the
# set of lattice parameters given in input as *mintemp*. These should be the
# lattice parameters at a given temperature obtained from the free energy
# minimization, so that S(T) can be obtained.
# Before calling this function, the polynomial coefficients resulting from
# fitting the elastic compliances over a grid of lattice parameters, i.e. over
# different geometries, must be obtained and passed as input in *aS*.
# *typeCx* defines what kind of polynomial to use for fitting ("quadratic" or
# "quartic")
# """
# S = np.zeros((6,6))
# for i in range(0,6):
# for j in range(0,6):
# if typeCx=="quadratic":
# S[i,j] = fquadratic(mintemp,aS[i,j],ibrav=4)
# elif typeCx=="quartic":
# S[i,j] = fquartic(mintemp,aS[i,j],ibrav=4)
# return S
which might include code, classes, or functions. Output only the next line. | 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 function parameters
for the call in pool.map
it[0]== 0 -> use V, S, average frequencies and gruneisen parameters at 0 K
it[0]== 1 -> use S at 0 K, calculate V, average frequencies and gruneisen parameters at each T
it[0]== 2 -> calculate S, V, average frequencies and gruneisen parameters at each T
"""
alphaT = []
if (it[0]==0): # use V, S, average frequencies and gruneisen parameters at 0 K
for i in range(it[1],it[2]+1):
alpha = compute_alpha_grun(it[3][i],it[4],it[5],it[6],it[7],it[8],it[9])
print ("T= "+str(it[3][i])+"\nalpha = ", alpha)
alphaT.append(alpha)
elif (it[0]==1): # use S at 0 K, calculate V, average frequencies and gruneisen parameters at each T
for i in range(it[1],it[2]+1):
V=compute_volume(it[11][i],it[9])
freq, grun = freqmingrun(it[10],it[11][i],it[12],it[13],it[9],it[14])
alpha = compute_alpha_grun(it[3][i],V,it[5],it[6],freq,grun,it[9])
print ("V = ",str(V),"\nT= "+str(it[3][i])+"\nalpha = ", alpha)
alphaT.append(alpha)
elif (it[0]==2): # calculate V, average frequencies, gruneisen parameters ans S at each T
for i in range(it[1],it[2]+1):
V=compute_volume(it[11][i],it[9])
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
import math
from .constants import RY_KBAR, K_BOLTZMANN_RY, KB1
from .fitfreqgrun import freqmingrun
from .properties_anis import compute_volume
from .fitC import fS
from multiprocessing import Pool
from grunc import c_qvc # This is the same routine c_qv implemented in C to speed it up
and context (class names, function names, or code) available:
# Path: pyqha/constants.py
# RY_KBAR = 10.0 * AU_GPA / 2.0
#
# K_BOLTZMANN_RY = K_BOLTZMANN_SI / RYDBERG_SI
#
# KB1=1.0/K_BOLTZMANN_RY/RY_TO_CMM1 # inverse Boltzmann constant in cm^{-1}/K
#
# Path: pyqha/fitfreqgrun.py
# def freqmingrun(afreq, min0, nq, modes, ibrav, typefreq):
# """
# This function calculates the frequencies and the Gruneisen parameters
# from the fitted polynomials coeffients (one
# for each q point and mode) at the minimun point *min0* given in input.
# *afreq* is a :math:`nq*modes` numpy matrix containing the fitted polynomial coefficients.
# It can be obtained from :py:func:`fitfreqxx`.
#
# It returns a :math:`nq*modes` matrix, each element [i,j] being the fitted frequency
# In addition, it returns a :math:`nq*modes*6` with the Gruneisein parameters.
# Each element [i,j,k] is the the Gruneisein parameter at *nq=i*, *mode=j* and direction
# *k* (for example, in hex systems *k=0* is *a* direction, *k=2* is *c* direction, others are zero)
#
# Note that the Gruneisein parameters are not multiplied for the lattice parameters.
# """
# #nq = 10 # for testing quickly
# f = np.zeros((nq,modes))
# grun = np.zeros((6,nq,modes)) # initialize the Gruneisein parameters matrix
# for i in range(0,nq):
# for j in range(0,modes):
# if typefreq=="quadratic":
# f[i,j] = fquadratic(min0,afreq[i][j],ibrav=4)
# if f[i,j]<1E-5:
# grun[:,i,j] = 0.0
# else:
# grun[:,i,j] = fquadratic_der(min0,afreq[i][j],ibrav)/f[i,j]*min0
# elif typefreq=="quartic":
# f[i,j] = fquartic(min0,afreq[i][j],ibrav=4)
# if f[i,j]<1E-5:
# grun[:,i,j] = 0.0
# else:
# grun[:,i,j] = fquartic_der(min0,afreq[i][j],ibrav)/f[i,j]*min0
#
# return f, grun
#
# Path: pyqha/properties_anis.py
# def compute_volume(celldms,ibrav=4):
# """
# Compute the volume given the *celldms*. Only for ibrav=4 for now, else
# returns 0.
# """
# if ibrav==4:
# return 0.866025404*celldms[0]*celldms[0]*celldms[2]
#
# return 0
#
# Path: pyqha/fitC.py
# def fS(aS,mintemp,typeCx):
# """
# An auxiliary function returning the elastic compliances 6x6 tensor at the
# set of lattice parameters given in input as *mintemp*. These should be the
# lattice parameters at a given temperature obtained from the free energy
# minimization, so that S(T) can be obtained.
# Before calling this function, the polynomial coefficients resulting from
# fitting the elastic compliances over a grid of lattice parameters, i.e. over
# different geometries, must be obtained and passed as input in *aS*.
# *typeCx* defines what kind of polynomial to use for fitting ("quadratic" or
# "quartic")
# """
# S = np.zeros((6,6))
# for i in range(0,6):
# for j in range(0,6):
# if typeCx=="quadratic":
# S[i,j] = fquadratic(mintemp,aS[i,j],ibrav=4)
# elif typeCx=="quartic":
# S[i,j] = fquartic(mintemp,aS[i,j],ibrav=4)
# return S
. Output only the next line. | 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: # if not use a single x axis
for i in range(0,len(y[0,:])):
ax.plot(x, y[:,i], colors[i],label=labels[i])
ax.legend()
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
plt.show()
return fig
def plot_EV(V,E,a=None,labely="Etot"):
"""
This function plots with matplotlib E(V) data and if a is given it also plot
the fitted results
"""
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1) # create an axes object in the figure
ax.plot(V, E, 'o', label=labely+" data", markersize=10)
if (a!=None):
<|code_end|>
, generate the next line using the imports in this file:
from matplotlib import use
from .eos import calculate_fitted_points
from mpl_toolkits.mplot3d import axes3d
from matplotlib import cm
from .minutils import calculate_fitted_points_anis
from .minutils import calculate_fitted_points_anis
import matplotlib.pyplot as plt
import numpy as np
and context (functions, classes, or occasionally code) from other files:
# Path: pyqha/eos.py
# def calculate_fitted_points(V,a):
# """
# Calculates a denser mesh of E(V) points (1000) for plotting.
# """
# Vstep = (V[len(V)-1]-V[0])/1000
# Vdense = np.zeros(1000)
# Edensefitted = np.zeros(1000)
# for i in range(0,1000):
# Vdense[i] = V[0] + Vstep*i
# Edensefitted[i] = E_Murn(Vdense[i],a)
#
# return Vdense, Edensefitted
. Output only the next line. | 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. Then writes the output on file(s)
if fout!=None.
Output file(s) have the following format:
+------+-----------------+-----------------+-----------------+-----------------+
| T | :math:`E_{vib}` | :math:`F_{vib}` | :math:`S_{vib}` | :math:`C_{vib}` |
+======+=================+=================+=================+=================+
| 1 | ... | ... | ... | ... |
+------+-----------------+-----------------+-----------------+-----------------+
and are names *fout* +1, *fout* +2,... for each geometry.
Returning values are (len(TT),ngeo) numpy matrices (T,gEvib,gFvib,gSvib,gCvib,gZPE,gmodes)
containing the
temperatures and the above mentioned thermodynamic functions as for example:
Fvib[T,geo] -> Fvib at the temperature "T" for the geometry "geo"
"""
gEvib=np.zeros((len(TT),ngeo))
gFvib=np.zeros((len(TT),ngeo))
gSvib=np.zeros((len(TT),ngeo))
gCvib=np.zeros((len(TT),ngeo))
gZPE=np.zeros((ngeo))
gmodes=np.zeros((ngeo))
for i in range(0,ngeo):
E, dos = read_dos(fin+str(i+1))
<|code_end|>
, determine the next line of code. You have imports:
from .constants import RY_TO_CMM1, K_BOLTZMANN_RY
from math import tanh, sinh, log, exp
from .read import read_dos, read_dos_geo
from .write import write_thermo
import numpy as np
and context (class names, function names, or code) available:
# Path: pyqha/constants.py
# RY_TO_CMM1 = 1.0E+10 * RY_TO_THZ / C_SI
#
# K_BOLTZMANN_RY = K_BOLTZMANN_SI / RYDBERG_SI
#
# Path: pyqha/read.py
# def read_dos(filename):
# """
# Read the phonon density of states (y axis) and the corresponding energies (x axis)
# from the input file *filename* (1st col energies, 2nd col DOS) and store it
# in two numpy arrays which are returned.
#
# """
# E = []
# dens = []
# print ("Reading phonon dos file "+filename+"...")
# with open(filename, "r") as lines:
# for line in lines:
# linesplit=line.split()
# if (float(linesplit[0])<1.0E-10):
# E.append(1.0E-10)
# else:
# E.append(float(linesplit[0]))
# dens.append(float(linesplit[1]))
#
# return np.array(E), np.array(dens)
#
# def read_dos_geo(fin,ngeo):
# """
# Read the phonon density of states and energies as in :py:func:`read_dos` from *ngeo* input files
# *fin1*, *fin2*, etc. and store it in two numpy matrices which are returned.
# """
#
# # read the first file to determine the number of DOS points
# E, dos = read_dos(fin+"1")
#
# gE = np.zeros((len(E),ngeo))
# gdos = np.zeros((len(E),ngeo))
# gE[:,0] = E
# gdos[:,0] = dos
#
# # then read the rest of files
# for i in range(1,ngeo):
# EE, ddos = read_dos(fin+str(i+1))
# gE[:,i] = EE
# gdos[:,i] = ddos
#
# return gE, gdos
#
# Path: pyqha/write.py
# def write_thermo(fname,T, Evib, Fvib, Svib, Cvib,ZPE,modes):
# fout=open(fname,"w")
# fout.write('# total modes from dos = {:.10e}\n'.format(modes))
# fout.write('# ZPE = {:.10e} Ry/cell\n'.format(ZPE))
# fout.write("# Multiply by 13.6058 to have energies in eV/cell etc..\n\
# # Multiply by 13.6058 x 23060.35 = 313 754.5 to have energies in cal/(N mol).\n\
# # Multiply by 13.6058 x 96526.0 = 1 313 313 to have energies in J/(N mol).\n\
# # N is the number of formula units per cell.\n#\n")
#
# fout.write("# T (K) \tEvib (Ry/cell)\tFvib (Ry/cell)\tSvib (Ry/cell/K)\tCvib (Ry/cell/K)\n")
# for i in range(0,len(Evib)):
# fout.write('{:.10e}\t{:.10e}\t{:.10e}\t{:.10e}\t{:.10e}\n'.format(T[i],Evib[i],Fvib[i],Svib[i],Cvib[i]))
# fout.close()
. Output only the next line. | 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 the phonon DOS(E). The calculation is done over a set of
temperatures given in input as a numpy array *TT*.
It also computes the number of phonon modes obtained from the input DOS (which
must be approximately equal to :math:`3*N`, with *N* the number of atoms per cell)
and the ZPE. The input energy and dos are expected to be in 1/cm-1.
It returns numpy arrays for the following quantities (in this order):
temperatures, vibrational energy, Helmholtz energy, entropy, heat capacity.
Plus it returns the ZPE and number of phonon modes obtained from the input DOS.
"""
if (len(dos)<3):
print ("Not enough points in the phonon DOS!")
return None
ZPE = 0.5*dos_integral(E,dos,1)
modes = dos_integral(E,dos)
EvibT = np.zeros(len(TT))
SvibT = np.zeros(len(TT))
CvibT = np.zeros(len(TT))
FvibT = np.zeros(len(TT))
for i in range(0,len(TT)):
h = 0.5*(E[2]-E[0])
<|code_end|>
with the help of current file imports:
from .constants import RY_TO_CMM1, K_BOLTZMANN_RY
from math import tanh, sinh, log, exp
from .read import read_dos, read_dos_geo
from .write import write_thermo
import numpy as np
and context from other files:
# Path: pyqha/constants.py
# RY_TO_CMM1 = 1.0E+10 * RY_TO_THZ / C_SI
#
# K_BOLTZMANN_RY = K_BOLTZMANN_SI / RYDBERG_SI
#
# Path: pyqha/read.py
# def read_dos(filename):
# """
# Read the phonon density of states (y axis) and the corresponding energies (x axis)
# from the input file *filename* (1st col energies, 2nd col DOS) and store it
# in two numpy arrays which are returned.
#
# """
# E = []
# dens = []
# print ("Reading phonon dos file "+filename+"...")
# with open(filename, "r") as lines:
# for line in lines:
# linesplit=line.split()
# if (float(linesplit[0])<1.0E-10):
# E.append(1.0E-10)
# else:
# E.append(float(linesplit[0]))
# dens.append(float(linesplit[1]))
#
# return np.array(E), np.array(dens)
#
# def read_dos_geo(fin,ngeo):
# """
# Read the phonon density of states and energies as in :py:func:`read_dos` from *ngeo* input files
# *fin1*, *fin2*, etc. and store it in two numpy matrices which are returned.
# """
#
# # read the first file to determine the number of DOS points
# E, dos = read_dos(fin+"1")
#
# gE = np.zeros((len(E),ngeo))
# gdos = np.zeros((len(E),ngeo))
# gE[:,0] = E
# gdos[:,0] = dos
#
# # then read the rest of files
# for i in range(1,ngeo):
# EE, ddos = read_dos(fin+str(i+1))
# gE[:,i] = EE
# gdos[:,i] = ddos
#
# return gE, gdos
#
# Path: pyqha/write.py
# def write_thermo(fname,T, Evib, Fvib, Svib, Cvib,ZPE,modes):
# fout=open(fname,"w")
# fout.write('# total modes from dos = {:.10e}\n'.format(modes))
# fout.write('# ZPE = {:.10e} Ry/cell\n'.format(ZPE))
# fout.write("# Multiply by 13.6058 to have energies in eV/cell etc..\n\
# # Multiply by 13.6058 x 23060.35 = 313 754.5 to have energies in cal/(N mol).\n\
# # Multiply by 13.6058 x 96526.0 = 1 313 313 to have energies in J/(N mol).\n\
# # N is the number of formula units per cell.\n#\n")
#
# fout.write("# T (K) \tEvib (Ry/cell)\tFvib (Ry/cell)\tSvib (Ry/cell/K)\tCvib (Ry/cell/K)\n")
# for i in range(0,len(Evib)):
# fout.write('{:.10e}\t{:.10e}\t{:.10e}\t{:.10e}\t{:.10e}\n'.format(T[i],Evib[i],Fvib[i],Svib[i],Cvib[i]))
# fout.close()
, which may contain function names, class names, or code. Output only the next line. | 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 approximation. Then writes the output on file(s)
if fout!=None.
Output file(s) have the following format:
+------+-----------------+-----------------+-----------------+-----------------+
| T | :math:`E_{vib}` | :math:`F_{vib}` | :math:`S_{vib}` | :math:`C_{vib}` |
+======+=================+=================+=================+=================+
| 1 | ... | ... | ... | ... |
+------+-----------------+-----------------+-----------------+-----------------+
and are names *fout* +1, *fout* +2,... for each geometry.
Returning values are (len(TT),ngeo) numpy matrices (T,gEvib,gFvib,gSvib,gCvib,gZPE,gmodes)
containing the
temperatures and the above mentioned thermodynamic functions as for example:
Fvib[T,geo] -> Fvib at the temperature "T" for the geometry "geo"
"""
gEvib=np.zeros((len(TT),ngeo))
gFvib=np.zeros((len(TT),ngeo))
gSvib=np.zeros((len(TT),ngeo))
gCvib=np.zeros((len(TT),ngeo))
gZPE=np.zeros((ngeo))
gmodes=np.zeros((ngeo))
for i in range(0,ngeo):
<|code_end|>
. Use current file imports:
(from .constants import RY_TO_CMM1, K_BOLTZMANN_RY
from math import tanh, sinh, log, exp
from .read import read_dos, read_dos_geo
from .write import write_thermo
import numpy as np)
and context including class names, function names, or small code snippets from other files:
# Path: pyqha/constants.py
# RY_TO_CMM1 = 1.0E+10 * RY_TO_THZ / C_SI
#
# K_BOLTZMANN_RY = K_BOLTZMANN_SI / RYDBERG_SI
#
# Path: pyqha/read.py
# def read_dos(filename):
# """
# Read the phonon density of states (y axis) and the corresponding energies (x axis)
# from the input file *filename* (1st col energies, 2nd col DOS) and store it
# in two numpy arrays which are returned.
#
# """
# E = []
# dens = []
# print ("Reading phonon dos file "+filename+"...")
# with open(filename, "r") as lines:
# for line in lines:
# linesplit=line.split()
# if (float(linesplit[0])<1.0E-10):
# E.append(1.0E-10)
# else:
# E.append(float(linesplit[0]))
# dens.append(float(linesplit[1]))
#
# return np.array(E), np.array(dens)
#
# def read_dos_geo(fin,ngeo):
# """
# Read the phonon density of states and energies as in :py:func:`read_dos` from *ngeo* input files
# *fin1*, *fin2*, etc. and store it in two numpy matrices which are returned.
# """
#
# # read the first file to determine the number of DOS points
# E, dos = read_dos(fin+"1")
#
# gE = np.zeros((len(E),ngeo))
# gdos = np.zeros((len(E),ngeo))
# gE[:,0] = E
# gdos[:,0] = dos
#
# # then read the rest of files
# for i in range(1,ngeo):
# EE, ddos = read_dos(fin+str(i+1))
# gE[:,i] = EE
# gdos[:,i] = ddos
#
# return gE, gdos
#
# Path: pyqha/write.py
# def write_thermo(fname,T, Evib, Fvib, Svib, Cvib,ZPE,modes):
# fout=open(fname,"w")
# fout.write('# total modes from dos = {:.10e}\n'.format(modes))
# fout.write('# ZPE = {:.10e} Ry/cell\n'.format(ZPE))
# fout.write("# Multiply by 13.6058 to have energies in eV/cell etc..\n\
# # Multiply by 13.6058 x 23060.35 = 313 754.5 to have energies in cal/(N mol).\n\
# # Multiply by 13.6058 x 96526.0 = 1 313 313 to have energies in J/(N mol).\n\
# # N is the number of formula units per cell.\n#\n")
#
# fout.write("# T (K) \tEvib (Ry/cell)\tFvib (Ry/cell)\tSvib (Ry/cell/K)\tCvib (Ry/cell/K)\n")
# for i in range(0,len(Evib)):
# fout.write('{:.10e}\t{:.10e}\t{:.10e}\t{:.10e}\t{:.10e}\n'.format(T[i],Evib[i],Fvib[i],Svib[i],Cvib[i]))
# fout.close()
. Output only the next line. | 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(s) have the following format:
+------+-----------------+-----------------+-----------------+-----------------+
| T | :math:`E_{vib}` | :math:`F_{vib}` | :math:`S_{vib}` | :math:`C_{vib}` |
+======+=================+=================+=================+=================+
| 1 | ... | ... | ... | ... |
+------+-----------------+-----------------+-----------------+-----------------+
and are names *fout* +1, *fout* +2,... for each geometry.
Returning values are (len(TT),ngeo) numpy matrices (T,gEvib,gFvib,gSvib,gCvib,gZPE,gmodes)
containing the
temperatures and the above mentioned thermodynamic functions as for example:
Fvib[T,geo] -> Fvib at the temperature "T" for the geometry "geo"
"""
gEvib=np.zeros((len(TT),ngeo))
gFvib=np.zeros((len(TT),ngeo))
gSvib=np.zeros((len(TT),ngeo))
gCvib=np.zeros((len(TT),ngeo))
gZPE=np.zeros((ngeo))
gmodes=np.zeros((ngeo))
for i in range(0,ngeo):
E, dos = read_dos(fin+str(i+1))
T, Evib, Svib, Cvib, Fvib, ZPE, modes = compute_thermo(E/RY_TO_CMM1,dos*RY_TO_CMM1,TT)
if (fout!=None):
<|code_end|>
, predict the immediate next line with the help of imports:
from .constants import RY_TO_CMM1, K_BOLTZMANN_RY
from math import tanh, sinh, log, exp
from .read import read_dos, read_dos_geo
from .write import write_thermo
import numpy as np
and context (classes, functions, sometimes code) from other files:
# Path: pyqha/constants.py
# RY_TO_CMM1 = 1.0E+10 * RY_TO_THZ / C_SI
#
# K_BOLTZMANN_RY = K_BOLTZMANN_SI / RYDBERG_SI
#
# Path: pyqha/read.py
# def read_dos(filename):
# """
# Read the phonon density of states (y axis) and the corresponding energies (x axis)
# from the input file *filename* (1st col energies, 2nd col DOS) and store it
# in two numpy arrays which are returned.
#
# """
# E = []
# dens = []
# print ("Reading phonon dos file "+filename+"...")
# with open(filename, "r") as lines:
# for line in lines:
# linesplit=line.split()
# if (float(linesplit[0])<1.0E-10):
# E.append(1.0E-10)
# else:
# E.append(float(linesplit[0]))
# dens.append(float(linesplit[1]))
#
# return np.array(E), np.array(dens)
#
# def read_dos_geo(fin,ngeo):
# """
# Read the phonon density of states and energies as in :py:func:`read_dos` from *ngeo* input files
# *fin1*, *fin2*, etc. and store it in two numpy matrices which are returned.
# """
#
# # read the first file to determine the number of DOS points
# E, dos = read_dos(fin+"1")
#
# gE = np.zeros((len(E),ngeo))
# gdos = np.zeros((len(E),ngeo))
# gE[:,0] = E
# gdos[:,0] = dos
#
# # then read the rest of files
# for i in range(1,ngeo):
# EE, ddos = read_dos(fin+str(i+1))
# gE[:,i] = EE
# gdos[:,i] = ddos
#
# return gE, gdos
#
# Path: pyqha/write.py
# def write_thermo(fname,T, Evib, Fvib, Svib, Cvib,ZPE,modes):
# fout=open(fname,"w")
# fout.write('# total modes from dos = {:.10e}\n'.format(modes))
# fout.write('# ZPE = {:.10e} Ry/cell\n'.format(ZPE))
# fout.write("# Multiply by 13.6058 to have energies in eV/cell etc..\n\
# # Multiply by 13.6058 x 23060.35 = 313 754.5 to have energies in cal/(N mol).\n\
# # Multiply by 13.6058 x 96526.0 = 1 313 313 to have energies in J/(N mol).\n\
# # N is the number of formula units per cell.\n#\n")
#
# fout.write("# T (K) \tEvib (Ry/cell)\tFvib (Ry/cell)\tSvib (Ry/cell/K)\tCvib (Ry/cell/K)\n")
# for i in range(0,len(Evib)):
# fout.write('{:.10e}\t{:.10e}\t{:.10e}\t{:.10e}\t{:.10e}\n'.format(T[i],Evib[i],Fvib[i],Svib[i],Cvib[i]))
# fout.close()
. Output only the next line. | 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()
for e in elem.findall('entry'):
if e.get('type') == 'image':
self.hdr = hdr.load(os.path.join(self.dirname, e.text))
self.image = hdr.tonemap(self.hdr)
elif e.get('type') == 'mask':
self.mask = sp.misc.imread(os.path.join(self.dirname, e.text), flatten=True)
self.mask[np.where(self.mask < 128)] = 0
self.mask[np.where(self.mask >= 128)] = 1
elif e.get('type') == 'bssrdf':
<|code_end|>
. Write the next line using the current file imports:
import os
import numpy as np
import scipy as sp
import scipy.misc
import xml.dom.minidom
import bssrdf_estimate.hdr as hdr
from xml.etree.ElementTree import ElementTree
from .diffuse_bssrdf import DiffuseBSSRDF
from .render_parameters import RenderParameters
and context from other files:
# Path: bssrdf_estimate/tools/diffuse_bssrdf.py
# class DiffuseBSSRDF(object):
# def __init__(self):
# self.distances = None
# self.colors = None
#
# @staticmethod
# def load(filename):
# ret = DiffuseBSSRDF()
# with open(filename, 'rb') as fp:
# ret.colors = [None] * 3
# sz = struct.unpack('i', fp.read(4))[0]
# ret.distances = np.array(struct.unpack('f' * sz, fp.read(4 * sz)), dtype='float32')
# ret.colors = np.zeros((sz,3), dtype='float32')
# ret.colors[:,0] = np.array(struct.unpack('f' * sz, fp.read(4 * sz)), dtype='float32')
# ret.colors[:,1] = np.array(struct.unpack('f' * sz, fp.read(4 * sz)), dtype='float32')
# ret.colors[:,2] = np.array(struct.unpack('f' * sz, fp.read(4 * sz)), dtype='float32')
# return ret
#
# def save(self, filename):
# with open(filename, 'wb') as fp:
# sz = self.distances.size
# fp.write(struct.pack('i', sz))
# fp.write(struct.pack('f' * sz, *self.distances))
# fp.write(struct.pack('f' * sz, *self.colors[:,0]))
# fp.write(struct.pack('f' * sz, *self.colors[:,1]))
# fp.write(struct.pack('f' * sz, *self.colors[:,2]))
#
# def scaled(self, sc):
# ret = DiffuseBSSRDF()
# ret.distances = self.distances / sc
# ret.colors = self.colors / (sc * sc)
# return ret
#
# Path: bssrdf_estimate/tools/render_parameters.py
# class RenderParameters(object):
# def __init__(self, image_width=400, image_height=300, spp=1, photons=1000000, scale=1.0):
# self._image_width = image_width
# self._image_height = image_height
# self._spp = spp
# self._photons = photons
# self._bssrdf_scale = scale
#
# @property
# def image_width(self):
# return self._image_width
#
# @property
# def image_height(self):
# return self._image_height
#
# @property
# def spp(self):
# return self._spp
#
# @property
# def photons(self):
# return self._photons
#
# @property
# def bssrdf_scale(self):
# return self._bssrdf_scale
, which may include functions, classes, or code. Output only the next line. | 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()
for e in elem.findall('entry'):
if e.get('type') == 'image':
self.hdr = hdr.load(os.path.join(self.dirname, e.text))
self.image = hdr.tonemap(self.hdr)
elif e.get('type') == 'mask':
self.mask = sp.misc.imread(os.path.join(self.dirname, e.text), flatten=True)
self.mask[np.where(self.mask < 128)] = 0
self.mask[np.where(self.mask >= 128)] = 1
elif e.get('type') == 'bssrdf':
self.bssrdf = DiffuseBSSRDF.load(os.path.join(self.dirname, e.text))
elif e.get('type') == 'render-params':
table = {}
for ee in e.findall('param'):
table[ee.get('type')] = ee.text
<|code_end|>
, generate the next line using the imports in this file:
import os
import numpy as np
import scipy as sp
import scipy.misc
import xml.dom.minidom
import bssrdf_estimate.hdr as hdr
from xml.etree.ElementTree import ElementTree
from .diffuse_bssrdf import DiffuseBSSRDF
from .render_parameters import RenderParameters
and context (functions, classes, or occasionally code) from other files:
# Path: bssrdf_estimate/tools/diffuse_bssrdf.py
# class DiffuseBSSRDF(object):
# def __init__(self):
# self.distances = None
# self.colors = None
#
# @staticmethod
# def load(filename):
# ret = DiffuseBSSRDF()
# with open(filename, 'rb') as fp:
# ret.colors = [None] * 3
# sz = struct.unpack('i', fp.read(4))[0]
# ret.distances = np.array(struct.unpack('f' * sz, fp.read(4 * sz)), dtype='float32')
# ret.colors = np.zeros((sz,3), dtype='float32')
# ret.colors[:,0] = np.array(struct.unpack('f' * sz, fp.read(4 * sz)), dtype='float32')
# ret.colors[:,1] = np.array(struct.unpack('f' * sz, fp.read(4 * sz)), dtype='float32')
# ret.colors[:,2] = np.array(struct.unpack('f' * sz, fp.read(4 * sz)), dtype='float32')
# return ret
#
# def save(self, filename):
# with open(filename, 'wb') as fp:
# sz = self.distances.size
# fp.write(struct.pack('i', sz))
# fp.write(struct.pack('f' * sz, *self.distances))
# fp.write(struct.pack('f' * sz, *self.colors[:,0]))
# fp.write(struct.pack('f' * sz, *self.colors[:,1]))
# fp.write(struct.pack('f' * sz, *self.colors[:,2]))
#
# def scaled(self, sc):
# ret = DiffuseBSSRDF()
# ret.distances = self.distances / sc
# ret.colors = self.colors / (sc * sc)
# return ret
#
# Path: bssrdf_estimate/tools/render_parameters.py
# class RenderParameters(object):
# def __init__(self, image_width=400, image_height=300, spp=1, photons=1000000, scale=1.0):
# self._image_width = image_width
# self._image_height = image_height
# self._spp = spp
# self._photons = photons
# self._bssrdf_scale = scale
#
# @property
# def image_width(self):
# return self._image_width
#
# @property
# def image_height(self):
# return self._image_height
#
# @property
# def spp(self):
# return self._spp
#
# @property
# def photons(self):
# return self._photons
#
# @property
# def bssrdf_scale(self):
# return self._bssrdf_scale
. Output only the next line. | 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(image, mask, depth)
self.translucent_shadowmap(lights)
# Build up system of linear equations
inv_pi = 1.0 / math.pi
num_pixels = len(self.pixels)
dscale = 1.0 / max(width, height)
A = np.zeros((num_pixels, NUM_BASES))
for i in range(num_pixels):
for k in range(num_pixels):
# Front side
p_f = self.pixels[k].pos
r_f = (self.pixels[i].pos - p_f).norm()
j_f = int(r_f * dscale)
if j_f >= 0 and j_f < NUM_BASES:
delta_A = 1.0 / (abs(self.pixels[i].normal.z) + EPS)
A[i,j_f] += self.pixels[k].front_E * delta_A
# Back side
<|code_end|>
using the current file's imports:
import math
import struct
import numpy as np
from itertools import product
from random import *
from .vector3d import Vector3D
from .diffuse_bssrdf import DiffuseBSSRDF
from .solvers import *
and any relevant context from other files:
# Path: bssrdf_estimate/tools/vector3d.py
# class Vector3D(object):
# def __init__(self, x=0.0, y=0.0, z=0.0):
# self._x = x
# self._y = y
# self._z = z
#
# @property
# def x(self):
# return self._x
#
# @property
# def y(self):
# return self._y
#
# @property
# def z(self):
# return self._z
#
# def dot(self, v):
# return self._x * v.x + self._y * v.y + self._z * v.z
#
# def norm(self):
# return math.sqrt(self.dot(self))
#
# def normalized(self):
# return self / self.norm()
#
# def __neg__(self):
# return Vector3D(-self._x, -self._y, -self._z)
#
# def __add__(self, v):
# return Vector3D(self._x + v.x, self._y + v.y, self._z + v.z)
#
# def __sub__(self, v):
# return Vector3D(self._x - v.x, self._y - v.y, self._z - v.z)
#
# def __mul__(self, s):
# return Vector3D(self._x * s, self._y * s, self._z * s)
#
# def __rmul__(self, s):
# return self.__mul__(s)
#
# def __truediv__(self, s):
# return self * (1.0 / s)
#
# Path: bssrdf_estimate/tools/diffuse_bssrdf.py
# class DiffuseBSSRDF(object):
# def __init__(self):
# self.distances = None
# self.colors = None
#
# @staticmethod
# def load(filename):
# ret = DiffuseBSSRDF()
# with open(filename, 'rb') as fp:
# ret.colors = [None] * 3
# sz = struct.unpack('i', fp.read(4))[0]
# ret.distances = np.array(struct.unpack('f' * sz, fp.read(4 * sz)), dtype='float32')
# ret.colors = np.zeros((sz,3), dtype='float32')
# ret.colors[:,0] = np.array(struct.unpack('f' * sz, fp.read(4 * sz)), dtype='float32')
# ret.colors[:,1] = np.array(struct.unpack('f' * sz, fp.read(4 * sz)), dtype='float32')
# ret.colors[:,2] = np.array(struct.unpack('f' * sz, fp.read(4 * sz)), dtype='float32')
# return ret
#
# def save(self, filename):
# with open(filename, 'wb') as fp:
# sz = self.distances.size
# fp.write(struct.pack('i', sz))
# fp.write(struct.pack('f' * sz, *self.distances))
# fp.write(struct.pack('f' * sz, *self.colors[:,0]))
# fp.write(struct.pack('f' * sz, *self.colors[:,1]))
# fp.write(struct.pack('f' * sz, *self.colors[:,2]))
#
# def scaled(self, sc):
# ret = DiffuseBSSRDF()
# ret.distances = self.distances / sc
# ret.colors = self.colors / (sc * sc)
# return ret
. Output only the next line. | 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 = f_E
b_normal = Vector3D(0.0, 0.0, -1.0)
b_E = 0.0
for j in range(num_lights):
light_dir = lights[j].direction()
angl = -light_dir.dot(b_normal)
if angl >= 0.0:
b_E += Ft(eta, angl) * angl * light_E
self.pixels[i].back_E = b_E
def solve_linear_system(self, A, bb, constrained=False):
if constrained:
print('[INFO] Use constrained solver...')
xx = SolveCon(A, bb).xx
else:
print('[INFO] Use unconstrained solver...')
xx = SolveUnc(A, bb).xx
assert xx is not None, "[ASSERT] Solution x is invalid"
self.set_curves(xx)
def set_curves(self, xx):
# Smoothing the Rd curve
<|code_end|>
using the current file's imports:
import math
import struct
import numpy as np
from itertools import product
from random import *
from .vector3d import Vector3D
from .diffuse_bssrdf import DiffuseBSSRDF
from .solvers import *
and any relevant context from other files:
# Path: bssrdf_estimate/tools/vector3d.py
# class Vector3D(object):
# def __init__(self, x=0.0, y=0.0, z=0.0):
# self._x = x
# self._y = y
# self._z = z
#
# @property
# def x(self):
# return self._x
#
# @property
# def y(self):
# return self._y
#
# @property
# def z(self):
# return self._z
#
# def dot(self, v):
# return self._x * v.x + self._y * v.y + self._z * v.z
#
# def norm(self):
# return math.sqrt(self.dot(self))
#
# def normalized(self):
# return self / self.norm()
#
# def __neg__(self):
# return Vector3D(-self._x, -self._y, -self._z)
#
# def __add__(self, v):
# return Vector3D(self._x + v.x, self._y + v.y, self._z + v.z)
#
# def __sub__(self, v):
# return Vector3D(self._x - v.x, self._y - v.y, self._z - v.z)
#
# def __mul__(self, s):
# return Vector3D(self._x * s, self._y * s, self._z * s)
#
# def __rmul__(self, s):
# return self.__mul__(s)
#
# def __truediv__(self, s):
# return self * (1.0 / s)
#
# Path: bssrdf_estimate/tools/diffuse_bssrdf.py
# class DiffuseBSSRDF(object):
# def __init__(self):
# self.distances = None
# self.colors = None
#
# @staticmethod
# def load(filename):
# ret = DiffuseBSSRDF()
# with open(filename, 'rb') as fp:
# ret.colors = [None] * 3
# sz = struct.unpack('i', fp.read(4))[0]
# ret.distances = np.array(struct.unpack('f' * sz, fp.read(4 * sz)), dtype='float32')
# ret.colors = np.zeros((sz,3), dtype='float32')
# ret.colors[:,0] = np.array(struct.unpack('f' * sz, fp.read(4 * sz)), dtype='float32')
# ret.colors[:,1] = np.array(struct.unpack('f' * sz, fp.read(4 * sz)), dtype='float32')
# ret.colors[:,2] = np.array(struct.unpack('f' * sz, fp.read(4 * sz)), dtype='float32')
# return ret
#
# def save(self, filename):
# with open(filename, 'wb') as fp:
# sz = self.distances.size
# fp.write(struct.pack('i', sz))
# fp.write(struct.pack('f' * sz, *self.distances))
# fp.write(struct.pack('f' * sz, *self.colors[:,0]))
# fp.write(struct.pack('f' * sz, *self.colors[:,1]))
# fp.write(struct.pack('f' * sz, *self.colors[:,2]))
#
# def scaled(self, sc):
# ret = DiffuseBSSRDF()
# ret.distances = self.distances / sc
# ret.colors = self.colors / (sc * sc)
# return ret
. Output only the next line. | 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.save_curve_figure('result/Rd_curve_before_smoothing.png', self.xx)
for c in range(ATb.shape[1]):
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
import scipy as sp
import scipy.sparse
import scipy.sparse.linalg
import matplotlib.pyplot as plt
from .polyfit import cubic_fitting
and context (class names, function names, or code) available:
# Path: bssrdf_estimate/tools/solvers/polyfit.py
# def cubic_fitting(ps):
# n_div = 5
#
# x0 = ps.copy()
#
# # Linear interpolation
# ps = map(lambda p0, p1: linear_interpolation(p0, p1, n_div), ps, ps[1:])
# ps = np.array(list(chain(*ps)))
#
# def func(x, ps = ps):
# w_d = 1.0
# w_p = 10.0
# w_s = 1.0e-4
#
# # Hermite interpolation
# _ , xs = spline_interpolate(x, n_div)
#
# cost = 0.0
#
# # Error between original
# cost += w_d * sum(map(lambda x, p: (x - p) ** 2.0, xs, ps))
#
# # Penalize increase
# cost += w_p * sum(map(lambda x0, x1: (x0 - x1) ** 2.0 if x0 - x1 < 0.0 else 0.0, xs, xs[1:]))
# cost += w_p * xs[-1] * xs[-1] if xs[-1] < 0.0 else 0.0
#
# # Penalize smoothness
# cost += w_s * sum(map(lambda x0, x1, x2: (x0 - 2.0 * x1 + x2) ** 2.0, xs, xs[1:], xs[2:]))
#
# return cost
#
# opt = { 'maxiter': 2000, 'disp': False }
# res = sp.optimize.minimize(func, x0, method='L-BFGS-B', options=opt)
#
# if not res.success:
# print('[ERROR] failed: %s' % res.message)
# else:
# print('[INFO] L-BFGS-B Success!!')
#
# return res.x
. Output only the next line. | 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.phi) * math.cos(self.theta)
z = math.sin(self.theta)
<|code_end|>
, generate the next line using the imports in this file:
import math
from .vector3d import Vector3D
and context (functions, classes, or occasionally code) from other files:
# Path: bssrdf_estimate/tools/vector3d.py
# class Vector3D(object):
# def __init__(self, x=0.0, y=0.0, z=0.0):
# self._x = x
# self._y = y
# self._z = z
#
# @property
# def x(self):
# return self._x
#
# @property
# def y(self):
# return self._y
#
# @property
# def z(self):
# return self._z
#
# def dot(self, v):
# return self._x * v.x + self._y * v.y + self._z * v.z
#
# def norm(self):
# return math.sqrt(self.dot(self))
#
# def normalized(self):
# return self / self.norm()
#
# def __neg__(self):
# return Vector3D(-self._x, -self._y, -self._z)
#
# def __add__(self, v):
# return Vector3D(self._x + v.x, self._y + v.y, self._z + v.z)
#
# def __sub__(self, v):
# return Vector3D(self._x - v.x, self._y - v.y, self._z - v.z)
#
# def __mul__(self, s):
# return Vector3D(self._x * s, self._y * s, self._z * s)
#
# def __rmul__(self, s):
# return self.__mul__(s)
#
# def __truediv__(self, s):
# return self * (1.0 / s)
. Output only the next line. | 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(self):
render(self.render_params.image_width,
self.render_params.image_height,
self.render_params.spp,
self.render_params.photons,
self.bssrdf.distances,
self.bssrdf.colors)
<|code_end|>
, predict the next line using imports from the current file:
import os
import scipy as sp
import scipy.misc
from PyQt5.QtCore import QTimer, QThread
from .image_widget import ImageWidget
from bssrdf_estimate.render import render
and context including class names, function names, and sometimes code from other files:
# Path: bssrdf_estimate/interface/image_widget.py
# class ImageWidget(QWidget):
# def __init__(self, parent=None):
# super(ImageWidget, self).__init__(parent)
#
# self.imageScale = 1.0
# self.prevMousePos = QPoint(0, 0)
#
# self.imageLabel = QLabel()
# self.gridLayout = QGridLayout()
# self.scrollArea = QScrollArea()
# self.scrollArea.viewport().installEventFilter(self)
# self.scrollArea.setWidget(self.imageLabel)
# self.scrollArea.setWidgetResizable(True)
#
# self.gridLayout.addWidget(self.scrollArea)
# self.setLayout(self.gridLayout)
#
# self.pixmap = None
#
# def showImage(self, image):
# if isinstance(image, np.ndarray):
# image = self.numpy2qimage(image)
# self.pixmap = QPixmap(QPixmap.fromImage(image))
# self.imageLabel.setPixmap(self.pixmap)
# self.show()
#
# def mousePressEvent(self, ev):
# if ev.button() == Qt.LeftButton:
# self.prevMousePos.setX(ev.x())
# self.prevMousePos.setY(ev.y())
#
# def mouseMoveEvent(self, ev):
# if ev.buttons() & Qt.LeftButton:
# dx = ev.x() - self.prevMousePos.x()
# dy = ev.y() - self.prevMousePos.y()
# self.scrollArea.verticalScrollBar().setValue(self.scrollArea.verticalScrollBar().value() - dy)
# self.scrollArea.horizontalScrollBar().setValue(self.scrollArea.horizontalScrollBar().value() - dx)
# self.prevMousePos.setX(ev.x())
# self.prevMousePos.setY(ev.y())
#
# def wheelEvent(self, ev):
# scale = (1.0 / 0.95) if ev.angleDelta().y() > 0.0 else 0.95
# self.imageScale *= scale
# self.imageScale = max(self.imageScale, 0.2)
# self.imageScale = min(self.imageScale, 3.0)
#
# newSize = self.imageScale * self.pixmap.size()
# self.imageLabel.setPixmap(self.pixmap.scaled(newSize))
# self.imageLabel.resize(newSize)
#
# def eventFilter(self, obj, ev):
# if ev.type() == QEvent.Wheel:
# ev.ignore()
# return True
# return False
#
# @classmethod
# def numpy2qimage(cls, image):
# w = image.shape[1]
# h = image.shape[0]
# ret = QImage(w, h, QImage.Format_RGB888)
# for y, x in product(range(h), range(w)):
# if image.ndim == 3:
# c = image[y,x,:]
# r = int(min(c[0], 1.0) * 255.0)
# g = int(min(c[1], 1.0) * 255.0)
# b = int(min(c[2], 1.0) * 255.0)
# ret.setPixel(x, y, qRgb(r, g, b))
# else:
# c = int(min(image[y, x], 1.0) * 255.0)
# ret.setPixel(x, y, qRgb(c, c, c))
# return ret
. Output only the next line. | 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)
strwrite(fp, '# Made with100%% pure HDR Shop%c' % ret)
strwrite(fp, 'FORMAT=32-bit_rle_rgbe%c' % ret)
strwrite(fp, 'EXPOSURE=1.0000000000000%c%c' % (ret, ret))
# Write size
[height, width, dim] = hdr.shape
if dim != 3:
raise Exception('HDR image must have 3 channels')
strwrite(fp, '-Y %d +X %d%c' % (height, width, ret))
for i in range(height):
line = [None] * width
for j in range(width):
r = hdr[i, j, 0]
g = hdr[i, j, 1]
b = hdr[i, j, 2]
<|code_end|>
, predict the next line using imports from the current file:
import struct
from .hdr_pixel import HDRPixel
and context including class names, function names, and sometimes code from other files:
# Path: bssrdf_estimate/hdr/hdr_pixel.py
# class HDRPixel(object):
# def __init__(self, r, g, b):
# d = max(r, max(g, b))
# if (d < 1.0e-32):
# self.r = 0
# self.g = 0
# self.b = 0
# self.e = 0
# return
#
# m, ie = math.frexp(d)
# d = m * 256.0 / d
#
# self.r = int(clamp(r * d, 0, 255))
# self.g = int(clamp(g * d, 0, 255))
# self.b = int(clamp(b * d, 0, 255))
# self.e = int(clamp(ie + 128, 0, 255))
#
# def get(self, i):
# if i == 0: return self.r
# if i == 1: return self.g
# if i == 2: return self.b
# if i == 3: return self.e
# raise Exception('Channel index out of bounds')
. Output only the next line. | 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 ExtensionSettingsTestCase(unittest.TestCase):
def setUp(self):
self.app = QtGui.QApplication([])
self.app.setOrganizationName("test_case");
self.app.setApplicationName("testing_app");
<|code_end|>
. Write the next line using the current file imports:
from PyQt4 import QtCore
from PyQt4 import QtGui
from commotion_client.utils import extension_manager
import unittest
import re
import os
import sys
import copy
import types
and context from other files:
# Path: commotion_client/utils/extension_manager.py
# class ExtensionManager(object):
# class ConfigManager(object):
# def __init__(self):
# def get_user_settings(self):
# def reset_settings_group(self):
# def init_extension_libraries(self):
# def set_library_defaults(self):
# def init_libraries(self):
# def init_extension_config(self, ext_type=None):
# def check_installed(self, name=None):
# def get_installed(self):
# def load_core(self):
# def install_loaded(self, ext_type=None):
# def get_extension_from_property(self, key, val):
# def get_property(self, name, key):
# def load_user_interface(self, extension_name, gui):
# def get_config(self, name):
# def remove_extension_settings(self, name):
# def save_settings(self, extension_config, extension_type="global"):
# def __init__(self, path=None):
# def has_configs(self):
# def find(self, name=None):
# def get_paths(self, directory):
# def get(self, paths=None):
# def load(self, path):
, which may include functions, classes, or code. Output only the next line. | 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 section that will allow a developer building a extension to add functionality they need.
"""
#Standard Library Imports
#PyQt imports
#Commotion Client Imports
class ToolBar(QtGui.QWidget):
"""
The Core toolbar object that populates manditory toolbar sections.
"""
<|code_end|>
, predict the next line using imports from the current file:
import logging
from PyQt4 import QtCore
from PyQt4 import QtGui
from commotion_client.assets import commotion_assets_rc
from commotion_client.GUI import extension_toolbar
and context including class names, function names, and sometimes code from other files:
# Path: commotion_client/GUI/extension_toolbar.py
# class ExtensionToolBar(object):
# class MenuItem(QtGui.QToolButton):
# def __init__(self, viewport):
# def add_item(self, tool_button):
# def __init__(self, parent=None, viewport=None):
# def set_menu(self, value):
. Output only the next line. | 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} found".format(name)))
return False
def get_paths(self, directory):
"""Returns the paths to all extensions with config files within a directory.
Args:
directory (string): The path to the folder that extension's are within. Extensions can be up to one level below the directory given.
Returns:
config_files (array): An array of paths to all extension objects with config files that were found.
Raises:
TypeError: If no extensions exist within the directory requested.
AssertionError: If the directory path does not exist.
"""
#Check the directory and raise value error if not there
dir_obj = QtCore.QDir(str(directory))
if not dir_obj.exists(dir_obj.absolutePath()):
raise ValueError(self.translate("logs", "Folder at path {0} does not exist. No Config files loaded.".format(str(directory))))
else:
path = dir_obj.absolutePath()
config_files = []
try:
<|code_end|>
, predict the next line using imports from the current file:
import logging
import importlib
import shutil
import os
import re
import sys
import zipfile
import json
import zipimport
from PyQt4 import QtCore
from commotion_client.utils import fs_utils
from commotion_client.utils import validate
from commotion_client.utils import settings
from commotion_client import extensions
and context including class names, function names, and sometimes code from other files:
# Path: commotion_client/utils/fs_utils.py
# def is_file(unknown):
# def walklevel(some_dir, level=1):
# def make_temp_dir(new=None):
# def clean_dir(path=None):
# def copy_contents(start, end):
# def json_load(path):
#
# Path: commotion_client/utils/validate.py
# class ClientConfig(object):
# class Networking(object):
# def __init__(self, config, directory=None):
# def config(self):
# def config(self, value):
# def extension_path(self):
# def extension_path(self, value):
# def validate_all(self):
# def gui(self, gui_name):
# def name(self):
# def menu_item(self):
# def parent(self):
# def menu_level(self):
# def tests(self):
# def check_menu_text(self, menu_text):
# def check_exists(self, file_name):
# def check_path(self, file_name):
# def check_path_chars(self, file_name):
# def check_path_length(self, file_name=None):
# def __init__(self):
# def ipaddr(self, ip_addr, addr_type=None):
#
# Path: commotion_client/utils/settings.py
# class UserSettingsManager(object):
# def __init__(self):
# def save(self):
# def load(self):
# def get(self):
. Output only the next line. | 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 would delete all the extensions if it was allowed to succeed."))
raise ValueError(self.translate("logs", "You must specify an extension name greater than 1 char."))
return False
def save_settings(self, extension_config, extension_type="global"):
"""Saves an extensions core properties into the applications extension settings.
long description
Args:
extension_config (dict) An extension config in dictionary format.
extension_type (string): Type of extension "user" or "global". Defaults to global.
Returns:
bool: True if successful, False on any failures
"""
_settings = self.user_settings
#get extension dir
try:
extension_dir = self.libraries[extension_type]
except KeyError:
self.log.warning(self.translate("logs", "Invalid extension type. Please check the extension type and try again."))
return False
#create validator
try:
<|code_end|>
, generate the next line using the imports in this file:
import logging
import importlib
import shutil
import os
import re
import sys
import zipfile
import json
import zipimport
from PyQt4 import QtCore
from commotion_client.utils import fs_utils
from commotion_client.utils import validate
from commotion_client.utils import settings
from commotion_client import extensions
and context (functions, classes, or occasionally code) from other files:
# Path: commotion_client/utils/fs_utils.py
# def is_file(unknown):
# def walklevel(some_dir, level=1):
# def make_temp_dir(new=None):
# def clean_dir(path=None):
# def copy_contents(start, end):
# def json_load(path):
#
# Path: commotion_client/utils/validate.py
# class ClientConfig(object):
# class Networking(object):
# def __init__(self, config, directory=None):
# def config(self):
# def config(self, value):
# def extension_path(self):
# def extension_path(self, value):
# def validate_all(self):
# def gui(self, gui_name):
# def name(self):
# def menu_item(self):
# def parent(self):
# def menu_level(self):
# def tests(self):
# def check_menu_text(self, menu_text):
# def check_exists(self, file_name):
# def check_path(self, file_name):
# def check_path_chars(self, file_name):
# def check_path_length(self, file_name=None):
# def __init__(self):
# def ipaddr(self, ip_addr, addr_type=None):
#
# Path: commotion_client/utils/settings.py
# class UserSettingsManager(object):
# def __init__(self):
# def save(self):
# def load(self):
# def get(self):
. Output only the next line. | 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
self.extensions = {}
self.libraries = {}
self.set_library_defaults()
self.user_settings = self.get_user_settings()
self.config_keys = ["name",
"main",
"menu_item",
"menu_level",
"parent",
"settings",
"toolbar",
"tests",
"initialized",
"type",]
def get_user_settings(self):
"""Get the currently logged in user settings object."""
<|code_end|>
with the help of current file imports:
import logging
import importlib
import shutil
import os
import re
import sys
import zipfile
import json
import zipimport
from PyQt4 import QtCore
from commotion_client.utils import fs_utils
from commotion_client.utils import validate
from commotion_client.utils import settings
from commotion_client import extensions
and context from other files:
# Path: commotion_client/utils/fs_utils.py
# def is_file(unknown):
# def walklevel(some_dir, level=1):
# def make_temp_dir(new=None):
# def clean_dir(path=None):
# def copy_contents(start, end):
# def json_load(path):
#
# Path: commotion_client/utils/validate.py
# class ClientConfig(object):
# class Networking(object):
# def __init__(self, config, directory=None):
# def config(self):
# def config(self, value):
# def extension_path(self):
# def extension_path(self, value):
# def validate_all(self):
# def gui(self, gui_name):
# def name(self):
# def menu_item(self):
# def parent(self):
# def menu_level(self):
# def tests(self):
# def check_menu_text(self, menu_text):
# def check_exists(self, file_name):
# def check_path(self, file_name):
# def check_path_chars(self, file_name):
# def check_path_length(self, file_name=None):
# def __init__(self):
# def ipaddr(self, ip_addr, addr_type=None):
#
# Path: commotion_client/utils/settings.py
# class UserSettingsManager(object):
# def __init__(self):
# def save(self):
# def load(self):
# def get(self):
, which may contain function names, class names, or code. Output only the next line. | 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 so that exit/quit works on errors.
QtCore.QTimer.singleShot(0, self.init_client)
#=================================================
# CLIENT LOGIC
#=================================================
def init_client(self):
"""
Start up client using current status to determine run_level.
"""
try:
if not self.status:
self.start_full()
elif self.status == "daemon":
self.start_daemon()
except Exception as _excp: #log failure here and exit
_catch_all = self.translate("logs", "Could not fully initialize applicaiton. Application must be halted.")
self.log.critical(_catch_all)
self.log.exception(_excp)
self.end(_catch_all)
def init_logging(self, level=None, logfile=None):
<|code_end|>
, predict the next line using imports from the current file:
import sys
import argparse
import logging
import time
from PyQt4 import QtGui
from PyQt4 import QtCore
from commotion_client.utils import logger
from commotion_client.utils import thread
from commotion_client.utils import single_application
from commotion_client.utils import extension_manager
from commotion_client.GUI import main_window
from commotion_client.GUI import system_tray
and context including class names, function names, and sometimes code from other files:
# Path: commotion_client/utils/logger.py
# class LogHandler(object):
# def __init__(self, name, verbosity=None, logfile=None):
# def set_logfile(self, logfile=None):
# def set_verbosity(self, verbosity=None, log_type=None):
# def get_logger(self):
#
# Path: commotion_client/utils/thread.py
# class GenericThread(QtCore.QThread):
# def __init__(self):
# def __del__(self):
# def run(self):
#
# Path: commotion_client/utils/single_application.py
# class SingleApplication(QtGui.QApplication):
# class SingleApplicationWithMessaging(SingleApplication):
# def __init__(self, key, argv):
# def is_running(self):
# def __init__(self, key, argv):
# def handle_message(self):
# def send_message(self, message):
# def process_message(self, message):
#
# Path: commotion_client/utils/extension_manager.py
# class ExtensionManager(object):
# class ConfigManager(object):
# def __init__(self):
# def get_user_settings(self):
# def reset_settings_group(self):
# def init_extension_libraries(self):
# def set_library_defaults(self):
# def init_libraries(self):
# def init_extension_config(self, ext_type=None):
# def check_installed(self, name=None):
# def get_installed(self):
# def load_core(self):
# def install_loaded(self, ext_type=None):
# def get_extension_from_property(self, key, val):
# def get_property(self, name, key):
# def load_user_interface(self, extension_name, gui):
# def get_config(self, name):
# def remove_extension_settings(self, name):
# def save_settings(self, extension_config, extension_type="global"):
# def __init__(self, path=None):
# def has_configs(self):
# def find(self, name=None):
# def get_paths(self, directory):
# def get(self, paths=None):
# def load(self, path):
#
# Path: commotion_client/GUI/main_window.py
# class MainWindow(QtGui.QMainWindow):
# def __init__(self, parent=None):
# def toggle_menu_bar(self):
# def setup_menu_bar(self):
# def init_crash_reporter(self):
# def set_viewport(self):
# def apply_viewport(self, viewport, toolbar=None):
# def init_viewport_signals(self):
# def change_viewport(self, viewport):
# def init_toolbar(self, ext_toolbar):
# def purge(self):
# def closeEvent(self, event):
# def exitEvent(self):
# def cleanup(self):
# def bring_front(self):
# def load_settings(self):
# def save_settings(self):
# def crash(self, crash_type):
# def is_dirty(self):
#
# Path: commotion_client/GUI/system_tray.py
# class TrayIcon(QtGui.QWidget):
# def __init__(self, parent=None):
# def tray_iconActivated(self, reason):
. Output only the next line. | 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 evaluated to ensure that it is pulling in correct translators
locale = QtCore.QLocale.system().name()
qt_translator = QtCore.QTranslator()
if qt_translator.load("qt_"+locale, ":/"):
app.installTranslator(qt_translator)
app_translator = QtCore.QTranslator()
if app_translator.load("imagechanger_"+locale, ":/"): #TODO This code needs to be evaluated to ensure that it syncs with any internationalized images
app.installTranslator(app_translator)
#check for existing application w/wo a message
if app.is_running():
if args['message']:
#Checking for custom message
msg = args['message']
app.send_message(msg)
app.log.info(app.translate("logs", "application is already running, sent following message: \n\"{0}\"".format(msg)))
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.exit(app.exec_())
app.log.debug(app.translate("logs", "Shutting down"))
<|code_end|>
, generate the next line using the imports in this file:
import sys
import argparse
import logging
import time
from PyQt4 import QtGui
from PyQt4 import QtCore
from commotion_client.utils import logger
from commotion_client.utils import thread
from commotion_client.utils import single_application
from commotion_client.utils import extension_manager
from commotion_client.GUI import main_window
from commotion_client.GUI import system_tray
and context (functions, classes, or occasionally code) from other files:
# Path: commotion_client/utils/logger.py
# class LogHandler(object):
# def __init__(self, name, verbosity=None, logfile=None):
# def set_logfile(self, logfile=None):
# def set_verbosity(self, verbosity=None, log_type=None):
# def get_logger(self):
#
# Path: commotion_client/utils/thread.py
# class GenericThread(QtCore.QThread):
# def __init__(self):
# def __del__(self):
# def run(self):
#
# Path: commotion_client/utils/single_application.py
# class SingleApplication(QtGui.QApplication):
# class SingleApplicationWithMessaging(SingleApplication):
# def __init__(self, key, argv):
# def is_running(self):
# def __init__(self, key, argv):
# def handle_message(self):
# def send_message(self, message):
# def process_message(self, message):
#
# Path: commotion_client/utils/extension_manager.py
# class ExtensionManager(object):
# class ConfigManager(object):
# def __init__(self):
# def get_user_settings(self):
# def reset_settings_group(self):
# def init_extension_libraries(self):
# def set_library_defaults(self):
# def init_libraries(self):
# def init_extension_config(self, ext_type=None):
# def check_installed(self, name=None):
# def get_installed(self):
# def load_core(self):
# def install_loaded(self, ext_type=None):
# def get_extension_from_property(self, key, val):
# def get_property(self, name, key):
# def load_user_interface(self, extension_name, gui):
# def get_config(self, name):
# def remove_extension_settings(self, name):
# def save_settings(self, extension_config, extension_type="global"):
# def __init__(self, path=None):
# def has_configs(self):
# def find(self, name=None):
# def get_paths(self, directory):
# def get(self, paths=None):
# def load(self, path):
#
# Path: commotion_client/GUI/main_window.py
# class MainWindow(QtGui.QMainWindow):
# def __init__(self, parent=None):
# def toggle_menu_bar(self):
# def setup_menu_bar(self):
# def init_crash_reporter(self):
# def set_viewport(self):
# def apply_viewport(self, viewport, toolbar=None):
# def init_viewport_signals(self):
# def change_viewport(self, viewport):
# def init_toolbar(self, ext_toolbar):
# def purge(self):
# def closeEvent(self, event):
# def exitEvent(self):
# def cleanup(self):
# def bring_front(self):
# def load_settings(self):
# def save_settings(self):
# def crash(self, crash_type):
# def is_dirty(self):
#
# Path: commotion_client/GUI/system_tray.py
# class TrayIcon(QtGui.QWidget):
# def __init__(self, parent=None):
# def tray_iconActivated(self, reason):
. Output only the next line. | 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.exit(app.exec_())
app.log.debug(app.translate("logs", "Shutting down"))
class HoldStateDuringRestart(thread.GenericThread):
"""
A thread that will run during the restart of all other components to keep the applicaiton alive.
"""
def __init__(self):
super().__init__()
self.restart_complete = None
self.log = logging.getLogger("commotion_client."+__name__)
def end(self):
self.restart_complete = True
def run(self):
self.log.debug(QtCore.QCoreApplication.translate("logs", "Running restart thread"))
while True:
time.sleep(0.3)
if self.restart_complete:
self.log.debug(QtCore.QCoreApplication.translate("logs", "Restart event identified. Thread quitting"))
break
self.end()
<|code_end|>
, generate the next line using the imports in this file:
import sys
import argparse
import logging
import time
from PyQt4 import QtGui
from PyQt4 import QtCore
from commotion_client.utils import logger
from commotion_client.utils import thread
from commotion_client.utils import single_application
from commotion_client.utils import extension_manager
from commotion_client.GUI import main_window
from commotion_client.GUI import system_tray
and context (functions, classes, or occasionally code) from other files:
# Path: commotion_client/utils/logger.py
# class LogHandler(object):
# def __init__(self, name, verbosity=None, logfile=None):
# def set_logfile(self, logfile=None):
# def set_verbosity(self, verbosity=None, log_type=None):
# def get_logger(self):
#
# Path: commotion_client/utils/thread.py
# class GenericThread(QtCore.QThread):
# def __init__(self):
# def __del__(self):
# def run(self):
#
# Path: commotion_client/utils/single_application.py
# class SingleApplication(QtGui.QApplication):
# class SingleApplicationWithMessaging(SingleApplication):
# def __init__(self, key, argv):
# def is_running(self):
# def __init__(self, key, argv):
# def handle_message(self):
# def send_message(self, message):
# def process_message(self, message):
#
# Path: commotion_client/utils/extension_manager.py
# class ExtensionManager(object):
# class ConfigManager(object):
# def __init__(self):
# def get_user_settings(self):
# def reset_settings_group(self):
# def init_extension_libraries(self):
# def set_library_defaults(self):
# def init_libraries(self):
# def init_extension_config(self, ext_type=None):
# def check_installed(self, name=None):
# def get_installed(self):
# def load_core(self):
# def install_loaded(self, ext_type=None):
# def get_extension_from_property(self, key, val):
# def get_property(self, name, key):
# def load_user_interface(self, extension_name, gui):
# def get_config(self, name):
# def remove_extension_settings(self, name):
# def save_settings(self, extension_config, extension_type="global"):
# def __init__(self, path=None):
# def has_configs(self):
# def find(self, name=None):
# def get_paths(self, directory):
# def get(self, paths=None):
# def load(self, path):
#
# Path: commotion_client/GUI/main_window.py
# class MainWindow(QtGui.QMainWindow):
# def __init__(self, parent=None):
# def toggle_menu_bar(self):
# def setup_menu_bar(self):
# def init_crash_reporter(self):
# def set_viewport(self):
# def apply_viewport(self, viewport, toolbar=None):
# def init_viewport_signals(self):
# def change_viewport(self, viewport):
# def init_toolbar(self, ext_toolbar):
# def purge(self):
# def closeEvent(self, event):
# def exitEvent(self):
# def cleanup(self):
# def bring_front(self):
# def load_settings(self):
# def save_settings(self):
# def crash(self, crash_type):
# def is_dirty(self):
#
# Path: commotion_client/GUI/system_tray.py
# class TrayIcon(QtGui.QWidget):
# def __init__(self, parent=None):
# def tray_iconActivated(self, reason):
. Output only the next line. | 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 run_level.
"""
try:
if not self.status:
self.start_full()
elif self.status == "daemon":
self.start_daemon()
except Exception as _excp: #log failure here and exit
_catch_all = self.translate("logs", "Could not fully initialize applicaiton. Application must be halted.")
self.log.critical(_catch_all)
self.log.exception(_excp)
self.end(_catch_all)
def init_logging(self, level=None, logfile=None):
self.logger = logger.LogHandler("commotion_client", level, logfile)
self.log = self.logger.get_logger()
def start_full(self):
"""
Start or switch client over to full client.
"""
<|code_end|>
, determine the next line of code. You have imports:
import sys
import argparse
import logging
import time
from PyQt4 import QtGui
from PyQt4 import QtCore
from commotion_client.utils import logger
from commotion_client.utils import thread
from commotion_client.utils import single_application
from commotion_client.utils import extension_manager
from commotion_client.GUI import main_window
from commotion_client.GUI import system_tray
and context (class names, function names, or code) available:
# Path: commotion_client/utils/logger.py
# class LogHandler(object):
# def __init__(self, name, verbosity=None, logfile=None):
# def set_logfile(self, logfile=None):
# def set_verbosity(self, verbosity=None, log_type=None):
# def get_logger(self):
#
# Path: commotion_client/utils/thread.py
# class GenericThread(QtCore.QThread):
# def __init__(self):
# def __del__(self):
# def run(self):
#
# Path: commotion_client/utils/single_application.py
# class SingleApplication(QtGui.QApplication):
# class SingleApplicationWithMessaging(SingleApplication):
# def __init__(self, key, argv):
# def is_running(self):
# def __init__(self, key, argv):
# def handle_message(self):
# def send_message(self, message):
# def process_message(self, message):
#
# Path: commotion_client/utils/extension_manager.py
# class ExtensionManager(object):
# class ConfigManager(object):
# def __init__(self):
# def get_user_settings(self):
# def reset_settings_group(self):
# def init_extension_libraries(self):
# def set_library_defaults(self):
# def init_libraries(self):
# def init_extension_config(self, ext_type=None):
# def check_installed(self, name=None):
# def get_installed(self):
# def load_core(self):
# def install_loaded(self, ext_type=None):
# def get_extension_from_property(self, key, val):
# def get_property(self, name, key):
# def load_user_interface(self, extension_name, gui):
# def get_config(self, name):
# def remove_extension_settings(self, name):
# def save_settings(self, extension_config, extension_type="global"):
# def __init__(self, path=None):
# def has_configs(self):
# def find(self, name=None):
# def get_paths(self, directory):
# def get(self, paths=None):
# def load(self, path):
#
# Path: commotion_client/GUI/main_window.py
# class MainWindow(QtGui.QMainWindow):
# def __init__(self, parent=None):
# def toggle_menu_bar(self):
# def setup_menu_bar(self):
# def init_crash_reporter(self):
# def set_viewport(self):
# def apply_viewport(self, viewport, toolbar=None):
# def init_viewport_signals(self):
# def change_viewport(self, viewport):
# def init_toolbar(self, ext_toolbar):
# def purge(self):
# def closeEvent(self, event):
# def exitEvent(self):
# def cleanup(self):
# def bring_front(self):
# def load_settings(self):
# def save_settings(self):
# def crash(self, crash_type):
# def is_dirty(self):
#
# Path: commotion_client/GUI/system_tray.py
# class TrayIcon(QtGui.QWidget):
# def __init__(self, parent=None):
# def tray_iconActivated(self, reason):
. Output only the next line. | 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 restarted. Applicaiton will now be halted")
self.log.error(_catch_all)
self.log.exception(_excp)
self.end(_catch_all)
else:
self.log.error(self.translate("logs", "Client could not be restarted."))
self.log.info(self.translate("logs", "It is reccomended that you restart the application."))
self.log.exception(_excp)
raise
_restart.end()
#=================================================
# MAIN WINDOW
#=================================================
def create_main_window(self):
"""
Will create a new main window or return existing main window if one is already created.
"""
if self.main:
self.log.debug(self.translate("logs", "New window requested when one already exists. Returning existing main window."))
self.log.info(self.translate("logs", "If you would like to close the main window and re-open it please call close_main_window() first."))
return self.main
try:
<|code_end|>
, predict the next line using imports from the current file:
import sys
import argparse
import logging
import time
from PyQt4 import QtGui
from PyQt4 import QtCore
from commotion_client.utils import logger
from commotion_client.utils import thread
from commotion_client.utils import single_application
from commotion_client.utils import extension_manager
from commotion_client.GUI import main_window
from commotion_client.GUI import system_tray
and context including class names, function names, and sometimes code from other files:
# Path: commotion_client/utils/logger.py
# class LogHandler(object):
# def __init__(self, name, verbosity=None, logfile=None):
# def set_logfile(self, logfile=None):
# def set_verbosity(self, verbosity=None, log_type=None):
# def get_logger(self):
#
# Path: commotion_client/utils/thread.py
# class GenericThread(QtCore.QThread):
# def __init__(self):
# def __del__(self):
# def run(self):
#
# Path: commotion_client/utils/single_application.py
# class SingleApplication(QtGui.QApplication):
# class SingleApplicationWithMessaging(SingleApplication):
# def __init__(self, key, argv):
# def is_running(self):
# def __init__(self, key, argv):
# def handle_message(self):
# def send_message(self, message):
# def process_message(self, message):
#
# Path: commotion_client/utils/extension_manager.py
# class ExtensionManager(object):
# class ConfigManager(object):
# def __init__(self):
# def get_user_settings(self):
# def reset_settings_group(self):
# def init_extension_libraries(self):
# def set_library_defaults(self):
# def init_libraries(self):
# def init_extension_config(self, ext_type=None):
# def check_installed(self, name=None):
# def get_installed(self):
# def load_core(self):
# def install_loaded(self, ext_type=None):
# def get_extension_from_property(self, key, val):
# def get_property(self, name, key):
# def load_user_interface(self, extension_name, gui):
# def get_config(self, name):
# def remove_extension_settings(self, name):
# def save_settings(self, extension_config, extension_type="global"):
# def __init__(self, path=None):
# def has_configs(self):
# def find(self, name=None):
# def get_paths(self, directory):
# def get(self, paths=None):
# def load(self, path):
#
# Path: commotion_client/GUI/main_window.py
# class MainWindow(QtGui.QMainWindow):
# def __init__(self, parent=None):
# def toggle_menu_bar(self):
# def setup_menu_bar(self):
# def init_crash_reporter(self):
# def set_viewport(self):
# def apply_viewport(self, viewport, toolbar=None):
# def init_viewport_signals(self):
# def change_viewport(self, viewport):
# def init_toolbar(self, ext_toolbar):
# def purge(self):
# def closeEvent(self, event):
# def exitEvent(self):
# def cleanup(self):
# def bring_front(self):
# def load_settings(self):
# def save_settings(self):
# def crash(self, crash_type):
# def is_dirty(self):
#
# Path: commotion_client/GUI/system_tray.py
# class TrayIcon(QtGui.QWidget):
# def __init__(self, parent=None):
# def tray_iconActivated(self, reason):
. Output only the next line. | _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."))
self.log.exception(_excp)
raise
#=================================================
# SYSTEM TRAY
#=================================================
def init_sys_tray(self):
"""
System Tray initializer that runs all processes required to connect the system tray to other application commponents
"""
try:
if self.main:
self.sys_tray.exit.triggered.connect(self.main.exitEvent)
self.sys_tray.show_main.connect(self.main.bring_front)
except Exception as _excp:
self.log.error(self.translate("logs", "Could not initialize connections between the system tray and other application components."))
self.log.exception(_excp)
raise
def create_sys_tray(self):
"""
Starts the system tray
"""
try:
<|code_end|>
. Use current file imports:
(import sys
import argparse
import logging
import time
from PyQt4 import QtGui
from PyQt4 import QtCore
from commotion_client.utils import logger
from commotion_client.utils import thread
from commotion_client.utils import single_application
from commotion_client.utils import extension_manager
from commotion_client.GUI import main_window
from commotion_client.GUI import system_tray)
and context including class names, function names, or small code snippets from other files:
# Path: commotion_client/utils/logger.py
# class LogHandler(object):
# def __init__(self, name, verbosity=None, logfile=None):
# def set_logfile(self, logfile=None):
# def set_verbosity(self, verbosity=None, log_type=None):
# def get_logger(self):
#
# Path: commotion_client/utils/thread.py
# class GenericThread(QtCore.QThread):
# def __init__(self):
# def __del__(self):
# def run(self):
#
# Path: commotion_client/utils/single_application.py
# class SingleApplication(QtGui.QApplication):
# class SingleApplicationWithMessaging(SingleApplication):
# def __init__(self, key, argv):
# def is_running(self):
# def __init__(self, key, argv):
# def handle_message(self):
# def send_message(self, message):
# def process_message(self, message):
#
# Path: commotion_client/utils/extension_manager.py
# class ExtensionManager(object):
# class ConfigManager(object):
# def __init__(self):
# def get_user_settings(self):
# def reset_settings_group(self):
# def init_extension_libraries(self):
# def set_library_defaults(self):
# def init_libraries(self):
# def init_extension_config(self, ext_type=None):
# def check_installed(self, name=None):
# def get_installed(self):
# def load_core(self):
# def install_loaded(self, ext_type=None):
# def get_extension_from_property(self, key, val):
# def get_property(self, name, key):
# def load_user_interface(self, extension_name, gui):
# def get_config(self, name):
# def remove_extension_settings(self, name):
# def save_settings(self, extension_config, extension_type="global"):
# def __init__(self, path=None):
# def has_configs(self):
# def find(self, name=None):
# def get_paths(self, directory):
# def get(self, paths=None):
# def load(self, path):
#
# Path: commotion_client/GUI/main_window.py
# class MainWindow(QtGui.QMainWindow):
# def __init__(self, parent=None):
# def toggle_menu_bar(self):
# def setup_menu_bar(self):
# def init_crash_reporter(self):
# def set_viewport(self):
# def apply_viewport(self, viewport, toolbar=None):
# def init_viewport_signals(self):
# def change_viewport(self, viewport):
# def init_toolbar(self, ext_toolbar):
# def purge(self):
# def closeEvent(self, event):
# def exitEvent(self):
# def cleanup(self):
# def bring_front(self):
# def load_settings(self):
# def save_settings(self):
# def crash(self, crash_type):
# def is_dirty(self):
#
# Path: commotion_client/GUI/system_tray.py
# class TrayIcon(QtGui.QWidget):
# def __init__(self, parent=None):
# def tray_iconActivated(self, reason):
. Output only the next line. | 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.translate = QtCore.QCoreApplication.translate
self.setupUi(self)
self.start_report_collection.connect(self.send_signal)
self._dirty = False
@property
def is_dirty(self):
"""The current state of the viewport object """
return self._dirty
def clean_up(self):
self.on_stop.emit()
def send_signal(self):
self.data_report.emit("myModule", {"value01":"value", "value02":"value", "value03":"value"})
def send_error(self):
"""HI"""
self.error_report.emit("THIS IS AN ERROR MESSAGE!!!")
pass
<|code_end|>
using the current file's imports:
import logging
import sys
from PyQt4 import QtCore
from PyQt4 import QtGui
from commotion_client.GUI import extension_toolbar
from ui import Ui_config_manager
and any relevant context from other files:
# Path: commotion_client/GUI/extension_toolbar.py
# class ExtensionToolBar(object):
# class MenuItem(QtGui.QToolButton):
# def __init__(self, viewport):
# def add_item(self, tool_button):
# def __init__(self, parent=None, viewport=None):
# def set_menu(self, value):
. Output only the next line. | 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 developer building a extension to add functionality they need.
"""
#Standard Library Imports
#PyQt imports
#Commotion Client Imports
class ToolBar(QtGui.QWidget):
"""
The Core toolbar object that populates manditory toolbar sections.
"""
<|code_end|>
. Use current file imports:
import logging
import commotion_assets_rc
from PyQt4 import QtCore
from PyQt4 import QtGui
from commotion_client.GUI import extension_toolbar
and context (classes, functions, or code) from other files:
# Path: commotion_client/GUI/extension_toolbar.py
# class ExtensionToolBar(object):
# class MenuItem(QtGui.QToolButton):
# def __init__(self, viewport):
# def add_item(self, tool_button):
# def __init__(self, parent=None, viewport=None):
# def set_menu(self, value):
. Output only the next line. | 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(CONFIG_KEY, {})
cache = app.get(CACHE_APP_KEY)
<|code_end|>
. Use current file imports:
from .client import GitHubClient
from api.cache import APP_KEY as CACHE_APP_KEY
and context (classes, functions, or code) from other files:
# Path: api/github/client.py
# class GitHubClient:
#
# def __init__(self, client_id: str, client_secret: str, cache: BaseCache=None):
# self.client_id = client_id
# self.client_secret = client_secret
# if not cache:
# logger.warning('No caching enabled for GitHubClient')
# self.cache = cache
#
# async def make_request(self, url, method='get', cache_key: str=None, **kwargs):
# url = url.lstrip('/')
#
# kwargs.setdefault('params', {})
# kwargs['params'].update({
# 'client_id': self.client_id,
# 'client_secret': self.client_secret,
# })
#
# kwargs.setdefault('headers', {})
# kwargs['headers'].update({
# 'User-Agent': 'sir',
# 'Accept': 'application/vnd.github.v3+json',
# })
#
# 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.upper(), full_url, **kwargs) as resp:
# if resp.status >= 400:
# json = await resp.json()
# raise GitHubClientError(json, resp)
# else:
# if self.cache and resp.status == HTTPStatus.NOT_MODIFIED:
# logger.info('Cache HIT for {}; Etag: {}'.format(url, etag))
# return self.cache.get(cache_key)['response']
# else:
# json = await resp.json()
# new_etag = resp.headers.get('ETag')
# logger.info('Cache MISS for {}'.format(url))
# if new_etag and self.cache:
# cache_payload = {
# 'etag': new_etag,
# 'response': json
# }
# logger.info('Caching etag and response: {}'.format(new_etag))
# self.cache.set(cache_key, cache_payload)
# return json
#
# async def user_repos(self, username: str, sort: str='pushed'):
# cache_key = get_cache_key('user_repos', {
# 'username': username,
# 'sort': sort
# })
# return await self.make_request(
# '/users/{username}/repos'.format(username=username),
# params={'sort': sort},
# cache_key=cache_key
# )
#
# async def repo_tags(self, username: str, repo: str):
# cache_key = get_cache_key('repo_tags', {
# 'username': username,
# 'repo': repo
# })
# return await self.make_request(
# '/repos/{username}/{repo}/tags'.format(
# username=username, repo=repo
# ),
# cache_key=cache_key
# )
#
# async def compare(self, username: str, repo: str, base: str, head='HEAD'):
# cache_key = get_cache_key('compare', {
# 'username': username,
# 'repo': repo,
# 'base': base,
# 'head': head,
# })
# return await self.make_request(
# '/repos/{username}/{repo}/compare/{base}...{head}'.format(**locals()),
# cache_key=cache_key
# )
#
# async def rate_limit(self):
# return await self.make_request('/rate_limit')
#
# Path: api/cache.py
# APP_KEY = 'cache'
. Output only the next line. | 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(CONFIG_KEY, {})
<|code_end|>
. Use current file imports:
(from .client import GitHubClient
from api.cache import APP_KEY as CACHE_APP_KEY)
and context including class names, function names, or small code snippets from other files:
# Path: api/github/client.py
# class GitHubClient:
#
# def __init__(self, client_id: str, client_secret: str, cache: BaseCache=None):
# self.client_id = client_id
# self.client_secret = client_secret
# if not cache:
# logger.warning('No caching enabled for GitHubClient')
# self.cache = cache
#
# async def make_request(self, url, method='get', cache_key: str=None, **kwargs):
# url = url.lstrip('/')
#
# kwargs.setdefault('params', {})
# kwargs['params'].update({
# 'client_id': self.client_id,
# 'client_secret': self.client_secret,
# })
#
# kwargs.setdefault('headers', {})
# kwargs['headers'].update({
# 'User-Agent': 'sir',
# 'Accept': 'application/vnd.github.v3+json',
# })
#
# 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.upper(), full_url, **kwargs) as resp:
# if resp.status >= 400:
# json = await resp.json()
# raise GitHubClientError(json, resp)
# else:
# if self.cache and resp.status == HTTPStatus.NOT_MODIFIED:
# logger.info('Cache HIT for {}; Etag: {}'.format(url, etag))
# return self.cache.get(cache_key)['response']
# else:
# json = await resp.json()
# new_etag = resp.headers.get('ETag')
# logger.info('Cache MISS for {}'.format(url))
# if new_etag and self.cache:
# cache_payload = {
# 'etag': new_etag,
# 'response': json
# }
# logger.info('Caching etag and response: {}'.format(new_etag))
# self.cache.set(cache_key, cache_payload)
# return json
#
# async def user_repos(self, username: str, sort: str='pushed'):
# cache_key = get_cache_key('user_repos', {
# 'username': username,
# 'sort': sort
# })
# return await self.make_request(
# '/users/{username}/repos'.format(username=username),
# params={'sort': sort},
# cache_key=cache_key
# )
#
# async def repo_tags(self, username: str, repo: str):
# cache_key = get_cache_key('repo_tags', {
# 'username': username,
# 'repo': repo
# })
# return await self.make_request(
# '/repos/{username}/{repo}/tags'.format(
# username=username, repo=repo
# ),
# cache_key=cache_key
# )
#
# async def compare(self, username: str, repo: str, base: str, head='HEAD'):
# cache_key = get_cache_key('compare', {
# 'username': username,
# 'repo': repo,
# 'base': base,
# 'head': head,
# })
# return await self.make_request(
# '/repos/{username}/{repo}/compare/{base}...{head}'.format(**locals()),
# cache_key=cache_key
# )
#
# async def rate_limit(self):
# return await self.make_request('/rate_limit')
#
# Path: api/cache.py
# APP_KEY = 'cache'
. Output only the next line. | 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.upper(), full_url, **kwargs) as resp:
if resp.status >= 400:
json = await resp.json()
raise GitHubClientError(json, resp)
else:
if self.cache and resp.status == HTTPStatus.NOT_MODIFIED:
logger.info('Cache HIT for {}; Etag: {}'.format(url, etag))
return self.cache.get(cache_key)['response']
else:
json = await resp.json()
new_etag = resp.headers.get('ETag')
logger.info('Cache MISS for {}'.format(url))
if new_etag and self.cache:
cache_payload = {
'etag': new_etag,
'response': json
}
logger.info('Caching etag and response: {}'.format(new_etag))
self.cache.set(cache_key, cache_payload)
return json
async def user_repos(self, username: str, sort: str='pushed'):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from http import HTTPStatus
from werkzeug.contrib.cache import BaseCache
from api.cache import get_cache_key
import logging
import aiohttp
and context:
# Path: api/cache.py
# def get_cache_key(name: str, kwargs: dict):
# key_parts = [name]
# if kwargs:
# key_parts.append(KWARG_MARK)
# key_parts.extend(sorted(kwargs.items()))
# return str(hash(tuple(key_parts)))
which might include code, classes, or functions. Output only the next line. | 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, **kwargs):
return {
'ahead_by': 42,
'base_commit': {'sha': '123abc'}
}
class MockGitHubErrorClient(BaseMockGitHubClient):
async def repo_tags(self, *args, **kwargs):
mock_resp = mock.Mock()
mock_resp.status = 400
<|code_end|>
. Use current file imports:
from unittest import mock
from webtest_aiohttp import TestApp
from api.github.client import GitHubClientError
from api.tests.conftest import BaseMockGitHubClient
import pytest
and context (classes, functions, or code) from other files:
# Path: api/github/client.py
# class GitHubClientError(Exception):
# def __init__(self, body, response):
# self.body = body
# self.response = response
#
# Path: api/tests/conftest.py
# class BaseMockGitHubClient(GitHubClient):
#
# # Stub out request method
# async def make_request(self, **kwargs):
# pass
#
# async def repo_tags(self, username, repo):
# raise NotImplementedError
#
# async def user_repos(self, username, sort='pushed'):
# raise NotImplementedError
#
# async def compare(self, username: str, repo: str, base: str, head='HEAD'):
# raise NotImplementedError
#
# async def rate_limit(self):
# raise NotImplementedError
. Output only the next line. | 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 uppercased variables.
"""
<|code_end|>
using the current file's imports:
from aiohttp import web
from aiohttp_utils import negotiation, path_norm
from .config import Config
from . import settings
from . import routes
from .github import plugin as github_plugin
from . import cache
and any relevant context from other files:
# Path: api/config.py
# class Config(dict):
# """The simplest config object ever."""
#
# def from_object(self, obj):
# for key in dir(obj):
# if key.isupper():
# self[key] = getattr(obj, key)
#
# def __getattr__(self, name):
# try:
# return self[name]
# except KeyError:
# raise AttributeError('"{}" not found'.format(name))
#
# def __setattr__(self, name, value):
# self[name] = value
#
# Path: api/github/plugin.py
# CONFIG_KEY = 'GITHUB'
# APP_CLIENT_KEY = 'github_client'
# def setup(app):
. Output only the next line. | 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 variables.
"""
config = Config()
config.from_object(settings)
if settings_obj: # Update with overrides
config.from_object(settings_obj)
app = web.Application(debug=config.DEBUG)
# Store uppercased configuration variables on app
app.update(config)
# Set up routes
routes.setup(app)
# Set up cache
cache.setup(app)
# Use content negotiation middleware to render JSON responses
negotiation.setup(app)
# Normalize paths: https://aiohttp-utils.readthedocs.org/en/latest/modules/path_norm.html
path_norm.setup(app)
# Set up Github client
<|code_end|>
with the help of current file imports:
from aiohttp import web
from aiohttp_utils import negotiation, path_norm
from .config import Config
from . import settings
from . import routes
from .github import plugin as github_plugin
from . import cache
and context from other files:
# Path: api/config.py
# class Config(dict):
# """The simplest config object ever."""
#
# def from_object(self, obj):
# for key in dir(obj):
# if key.isupper():
# self[key] = getattr(obj, key)
#
# def __getattr__(self, name):
# try:
# return self[name]
# except KeyError:
# raise AttributeError('"{}" not found'.format(name))
#
# def __setattr__(self, name, value):
# self[name] = value
#
# Path: api/github/plugin.py
# CONFIG_KEY = 'GITHUB'
# APP_CLIENT_KEY = 'github_client'
# def setup(app):
, which may contain function names, class names, or code. Output only the next line. | 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_tags(self, *args, **kwargs):
return self._response_from_file('repo_tags.json')
async def user_repos(self, *args, **kwargs):
return self._response_from_file('user_repos.json')
async def compare(self, *args, **kwargs):
return self._response_from_file('compare.json')
class TestRepoProcessor:
@pytest.fixture()
def client(self):
return MockGitHubClient('myid', 'mysecret')
@pytest.fixture()
def processor(self, client):
<|code_end|>
, determine the next line of code. You have imports:
import json
import os
import pytest
from api.github import process
from api.tests.conftest import async_test, BaseMockGitHubClient
and context (class names, function names, or code) available:
# Path: api/github/process.py
# class RepoProcessor:
# def __init__(self, client: GitHubClient):
# async def get_comparison_since_last_release(self, username: str, repo: str):
#
# Path: api/tests/conftest.py
# @decorator
# def async_test(func, *args, **kwargs):
# future = func(*args, **kwargs)
# asyncio.get_event_loop().run_until_complete(future)
#
# class BaseMockGitHubClient(GitHubClient):
#
# # Stub out request method
# async def make_request(self, **kwargs):
# pass
#
# async def repo_tags(self, username, repo):
# raise NotImplementedError
#
# async def user_repos(self, username, sort='pushed'):
# raise NotImplementedError
#
# async def compare(self, username: str, repo: str, base: str, head='HEAD'):
# raise NotImplementedError
#
# async def rate_limit(self):
# raise NotImplementedError
. Output only the next line. | 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 def repo_tags(self, *args, **kwargs):
return self._response_from_file('repo_tags.json')
async def user_repos(self, *args, **kwargs):
return self._response_from_file('user_repos.json')
async def compare(self, *args, **kwargs):
return self._response_from_file('compare.json')
class TestRepoProcessor:
@pytest.fixture()
def client(self):
return MockGitHubClient('myid', 'mysecret')
@pytest.fixture()
def processor(self, client):
return process.RepoProcessor(client)
<|code_end|>
using the current file's imports:
import json
import os
import pytest
from api.github import process
from api.tests.conftest import async_test, BaseMockGitHubClient
and any relevant context from other files:
# Path: api/github/process.py
# class RepoProcessor:
# def __init__(self, client: GitHubClient):
# async def get_comparison_since_last_release(self, username: str, repo: str):
#
# Path: api/tests/conftest.py
# @decorator
# def async_test(func, *args, **kwargs):
# future = func(*args, **kwargs)
# asyncio.get_event_loop().run_until_complete(future)
#
# class BaseMockGitHubClient(GitHubClient):
#
# # Stub out request method
# async def make_request(self, **kwargs):
# pass
#
# async def repo_tags(self, username, repo):
# raise NotImplementedError
#
# async def user_repos(self, username, sort='pushed'):
# raise NotImplementedError
#
# async def compare(self, username: str, repo: str, base: str, head='HEAD'):
# raise NotImplementedError
#
# async def rate_limit(self):
# raise NotImplementedError
. Output only the next line. | @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):
pass
async def repo_tags(self, username, repo):
raise NotImplementedError
async def user_repos(self, username, sort='pushed'):
raise NotImplementedError
async def compare(self, username: str, repo: str, base: str, head='HEAD'):
raise NotImplementedError
async def rate_limit(self):
raise NotImplementedError
@pytest.fixture()
def make_app():
def maker(github=None):
<|code_end|>
, determine the next line of code. You have imports:
import asyncio
import os
import sys
import pytest
from decorator import decorator
from api.app import create_app
from api.github.client import GitHubClient
from api.github.plugin import APP_CLIENT_KEY as GITHUB_APP_KEY
and context (class names, function names, or code) available:
# Path: api/app.py
# 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 variables.
# """
# config = Config()
# config.from_object(settings)
# if settings_obj: # Update with overrides
# config.from_object(settings_obj)
# app = web.Application(debug=config.DEBUG)
# # Store uppercased configuration variables on app
# app.update(config)
#
# # Set up routes
# routes.setup(app)
# # Set up cache
# cache.setup(app)
# # Use content negotiation middleware to render JSON responses
# negotiation.setup(app)
# # Normalize paths: https://aiohttp-utils.readthedocs.org/en/latest/modules/path_norm.html
# path_norm.setup(app)
# # Set up Github client
# github_plugin.setup(app)
#
# return app
#
# Path: api/github/client.py
# class GitHubClient:
#
# def __init__(self, client_id: str, client_secret: str, cache: BaseCache=None):
# self.client_id = client_id
# self.client_secret = client_secret
# if not cache:
# logger.warning('No caching enabled for GitHubClient')
# self.cache = cache
#
# async def make_request(self, url, method='get', cache_key: str=None, **kwargs):
# url = url.lstrip('/')
#
# kwargs.setdefault('params', {})
# kwargs['params'].update({
# 'client_id': self.client_id,
# 'client_secret': self.client_secret,
# })
#
# kwargs.setdefault('headers', {})
# kwargs['headers'].update({
# 'User-Agent': 'sir',
# 'Accept': 'application/vnd.github.v3+json',
# })
#
# 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.upper(), full_url, **kwargs) as resp:
# if resp.status >= 400:
# json = await resp.json()
# raise GitHubClientError(json, resp)
# else:
# if self.cache and resp.status == HTTPStatus.NOT_MODIFIED:
# logger.info('Cache HIT for {}; Etag: {}'.format(url, etag))
# return self.cache.get(cache_key)['response']
# else:
# json = await resp.json()
# new_etag = resp.headers.get('ETag')
# logger.info('Cache MISS for {}'.format(url))
# if new_etag and self.cache:
# cache_payload = {
# 'etag': new_etag,
# 'response': json
# }
# logger.info('Caching etag and response: {}'.format(new_etag))
# self.cache.set(cache_key, cache_payload)
# return json
#
# async def user_repos(self, username: str, sort: str='pushed'):
# cache_key = get_cache_key('user_repos', {
# 'username': username,
# 'sort': sort
# })
# return await self.make_request(
# '/users/{username}/repos'.format(username=username),
# params={'sort': sort},
# cache_key=cache_key
# )
#
# async def repo_tags(self, username: str, repo: str):
# cache_key = get_cache_key('repo_tags', {
# 'username': username,
# 'repo': repo
# })
# return await self.make_request(
# '/repos/{username}/{repo}/tags'.format(
# username=username, repo=repo
# ),
# cache_key=cache_key
# )
#
# async def compare(self, username: str, repo: str, base: str, head='HEAD'):
# cache_key = get_cache_key('compare', {
# 'username': username,
# 'repo': repo,
# 'base': base,
# 'head': head,
# })
# return await self.make_request(
# '/repos/{username}/{repo}/compare/{base}...{head}'.format(**locals()),
# cache_key=cache_key
# )
#
# async def rate_limit(self):
# return await self.make_request('/rate_limit')
#
# Path: api/github/plugin.py
# APP_CLIENT_KEY = 'github_client'
. Output only the next line. | 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 imports:
(import asyncio
import os
import sys
import pytest
from decorator import decorator
from api.app import create_app
from api.github.client import GitHubClient
from api.github.plugin import APP_CLIENT_KEY as GITHUB_APP_KEY)
and context including class names, function names, or small code snippets from other files:
# Path: api/app.py
# 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 variables.
# """
# config = Config()
# config.from_object(settings)
# if settings_obj: # Update with overrides
# config.from_object(settings_obj)
# app = web.Application(debug=config.DEBUG)
# # Store uppercased configuration variables on app
# app.update(config)
#
# # Set up routes
# routes.setup(app)
# # Set up cache
# cache.setup(app)
# # Use content negotiation middleware to render JSON responses
# negotiation.setup(app)
# # Normalize paths: https://aiohttp-utils.readthedocs.org/en/latest/modules/path_norm.html
# path_norm.setup(app)
# # Set up Github client
# github_plugin.setup(app)
#
# return app
#
# Path: api/github/client.py
# class GitHubClient:
#
# def __init__(self, client_id: str, client_secret: str, cache: BaseCache=None):
# self.client_id = client_id
# self.client_secret = client_secret
# if not cache:
# logger.warning('No caching enabled for GitHubClient')
# self.cache = cache
#
# async def make_request(self, url, method='get', cache_key: str=None, **kwargs):
# url = url.lstrip('/')
#
# kwargs.setdefault('params', {})
# kwargs['params'].update({
# 'client_id': self.client_id,
# 'client_secret': self.client_secret,
# })
#
# kwargs.setdefault('headers', {})
# kwargs['headers'].update({
# 'User-Agent': 'sir',
# 'Accept': 'application/vnd.github.v3+json',
# })
#
# 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.upper(), full_url, **kwargs) as resp:
# if resp.status >= 400:
# json = await resp.json()
# raise GitHubClientError(json, resp)
# else:
# if self.cache and resp.status == HTTPStatus.NOT_MODIFIED:
# logger.info('Cache HIT for {}; Etag: {}'.format(url, etag))
# return self.cache.get(cache_key)['response']
# else:
# json = await resp.json()
# new_etag = resp.headers.get('ETag')
# logger.info('Cache MISS for {}'.format(url))
# if new_etag and self.cache:
# cache_payload = {
# 'etag': new_etag,
# 'response': json
# }
# logger.info('Caching etag and response: {}'.format(new_etag))
# self.cache.set(cache_key, cache_payload)
# return json
#
# async def user_repos(self, username: str, sort: str='pushed'):
# cache_key = get_cache_key('user_repos', {
# 'username': username,
# 'sort': sort
# })
# return await self.make_request(
# '/users/{username}/repos'.format(username=username),
# params={'sort': sort},
# cache_key=cache_key
# )
#
# async def repo_tags(self, username: str, repo: str):
# cache_key = get_cache_key('repo_tags', {
# 'username': username,
# 'repo': repo
# })
# return await self.make_request(
# '/repos/{username}/{repo}/tags'.format(
# username=username, repo=repo
# ),
# cache_key=cache_key
# )
#
# async def compare(self, username: str, repo: str, base: str, head='HEAD'):
# cache_key = get_cache_key('compare', {
# 'username': username,
# 'repo': repo,
# 'base': base,
# 'head': head,
# })
# return await self.make_request(
# '/repos/{username}/{repo}/compare/{base}...{head}'.format(**locals()),
# cache_key=cache_key
# )
#
# async def rate_limit(self):
# return await self.make_request('/rate_limit')
#
# Path: api/github/plugin.py
# APP_CLIENT_KEY = 'github_client'
. Output only the next line. | 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 def repo_tags(self, username, repo):
raise NotImplementedError
async def user_repos(self, username, sort='pushed'):
raise NotImplementedError
async def compare(self, username: str, repo: str, base: str, head='HEAD'):
raise NotImplementedError
async def rate_limit(self):
raise NotImplementedError
@pytest.fixture()
def make_app():
def maker(github=None):
app = create_app(TestConfig)
# Prevent any inadvertent requests
<|code_end|>
, predict the next line using imports from the current file:
import asyncio
import os
import sys
import pytest
from decorator import decorator
from api.app import create_app
from api.github.client import GitHubClient
from api.github.plugin import APP_CLIENT_KEY as GITHUB_APP_KEY
and context including class names, function names, and sometimes code from other files:
# Path: api/app.py
# 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 variables.
# """
# config = Config()
# config.from_object(settings)
# if settings_obj: # Update with overrides
# config.from_object(settings_obj)
# app = web.Application(debug=config.DEBUG)
# # Store uppercased configuration variables on app
# app.update(config)
#
# # Set up routes
# routes.setup(app)
# # Set up cache
# cache.setup(app)
# # Use content negotiation middleware to render JSON responses
# negotiation.setup(app)
# # Normalize paths: https://aiohttp-utils.readthedocs.org/en/latest/modules/path_norm.html
# path_norm.setup(app)
# # Set up Github client
# github_plugin.setup(app)
#
# return app
#
# Path: api/github/client.py
# class GitHubClient:
#
# def __init__(self, client_id: str, client_secret: str, cache: BaseCache=None):
# self.client_id = client_id
# self.client_secret = client_secret
# if not cache:
# logger.warning('No caching enabled for GitHubClient')
# self.cache = cache
#
# async def make_request(self, url, method='get', cache_key: str=None, **kwargs):
# url = url.lstrip('/')
#
# kwargs.setdefault('params', {})
# kwargs['params'].update({
# 'client_id': self.client_id,
# 'client_secret': self.client_secret,
# })
#
# kwargs.setdefault('headers', {})
# kwargs['headers'].update({
# 'User-Agent': 'sir',
# 'Accept': 'application/vnd.github.v3+json',
# })
#
# 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.upper(), full_url, **kwargs) as resp:
# if resp.status >= 400:
# json = await resp.json()
# raise GitHubClientError(json, resp)
# else:
# if self.cache and resp.status == HTTPStatus.NOT_MODIFIED:
# logger.info('Cache HIT for {}; Etag: {}'.format(url, etag))
# return self.cache.get(cache_key)['response']
# else:
# json = await resp.json()
# new_etag = resp.headers.get('ETag')
# logger.info('Cache MISS for {}'.format(url))
# if new_etag and self.cache:
# cache_payload = {
# 'etag': new_etag,
# 'response': json
# }
# logger.info('Caching etag and response: {}'.format(new_etag))
# self.cache.set(cache_key, cache_payload)
# return json
#
# async def user_repos(self, username: str, sort: str='pushed'):
# cache_key = get_cache_key('user_repos', {
# 'username': username,
# 'sort': sort
# })
# return await self.make_request(
# '/users/{username}/repos'.format(username=username),
# params={'sort': sort},
# cache_key=cache_key
# )
#
# async def repo_tags(self, username: str, repo: str):
# cache_key = get_cache_key('repo_tags', {
# 'username': username,
# 'repo': repo
# })
# return await self.make_request(
# '/repos/{username}/{repo}/tags'.format(
# username=username, repo=repo
# ),
# cache_key=cache_key
# )
#
# async def compare(self, username: str, repo: str, base: str, head='HEAD'):
# cache_key = get_cache_key('compare', {
# 'username': username,
# 'repo': repo,
# 'base': base,
# 'head': head,
# })
# return await self.make_request(
# '/repos/{username}/{repo}/compare/{base}...{head}'.format(**locals()),
# cache_key=cache_key
# )
#
# async def rate_limit(self):
# return await self.make_request('/rate_limit')
#
# Path: api/github/plugin.py
# APP_CLIENT_KEY = 'github_client'
. Output only the next line. | 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')
),
}
})
async def should_i_release(request):
client = request.app['github_client']
processor = RepoProcessor(client)
username = request.match_info['username']
repo = request.match_info['repo']
try:
comparison_json = await processor.get_comparison_since_last_release(username, repo)
<|code_end|>
using the current file's imports:
from aiohttp_utils import Response
from .github.client import GitHubClientError
from .github.process import RepoProcessor
and any relevant context from other files:
# Path: api/github/client.py
# class GitHubClientError(Exception):
# def __init__(self, body, response):
# self.body = body
# self.response = response
#
# Path: api/github/process.py
# class RepoProcessor:
#
# def __init__(self, client: GitHubClient):
# self.client = client
#
# async def get_comparison_since_last_release(self, username: str, repo: str):
# tags_json = await self.client.repo_tags(username, repo)
# if not tags_json:
# return None
# latest_tag_sha = tags_json[0]['commit']['sha']
#
# comparison_json = await self.client.compare(
# username,
# repo,
# base=latest_tag_sha,
# head='HEAD'
# )
# comparison_json['latest_tag'] = tags_json[0]['name']
# return comparison_json
. Output only the next line. | 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')
),
}
})
async def should_i_release(request):
client = request.app['github_client']
<|code_end|>
with the help of current file imports:
from aiohttp_utils import Response
from .github.client import GitHubClientError
from .github.process import RepoProcessor
and context from other files:
# Path: api/github/client.py
# class GitHubClientError(Exception):
# def __init__(self, body, response):
# self.body = body
# self.response = response
#
# Path: api/github/process.py
# class RepoProcessor:
#
# def __init__(self, client: GitHubClient):
# self.client = client
#
# async def get_comparison_since_last_release(self, username: str, repo: str):
# tags_json = await self.client.repo_tags(username, repo)
# if not tags_json:
# return None
# latest_tag_sha = tags_json[0]['commit']['sha']
#
# comparison_json = await self.client.compare(
# username,
# repo,
# base=latest_tag_sha,
# head='HEAD'
# )
# comparison_json['latest_tag'] = tags_json[0]['name']
# return comparison_json
, which may contain function names, class names, or code. Output only the next line. | 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": "Point", "coordinates": [102.0, 0.5]}, "properties": {"prop0": "value0"} },
{ "type": "Feature", "geometry": { "type": "LineString", "coordinates": [ [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0] ] }, "properties": { "prop0": "value0", "prop1": 0.0 } },
{ "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] ] }, "properties": { "prop0": "value0", "prop1": {"this": "that"}, "prop2": true, "prop3": null } }
] }'''
<|code_end|>
, generate the next line using the imports in this file:
import json
import unittest
from io import BytesIO
from ..sample import sample_geojson, stream_geojson
and context (functions, classes, or occasionally code) from other files:
# Path: openaddr/sample.py
# def sample_geojson(stream, max_features):
# ''' Read a stream of input GeoJSON and return a string with a limited feature count.
# '''
# features = list()
#
# for feature in stream_geojson(stream):
# if len(features) == max_features:
# break
#
# features.append(feature)
#
# geojson = dict(type='FeatureCollection', features=features)
# return json.dumps(geojson)
#
# def stream_geojson(stream):
# '''
# '''
# data = ijson.parse(stream)
#
# for (prefix1, event1, value1) in data:
# if event1 != 'start_map':
# # A root GeoJSON object is a map.
# raise ValueError((prefix1, event1, value1))
#
# for (prefix2, event2, value2) in data:
# if event2 == 'map_key' and value2 == 'type':
# prefix3, event3, value3 = next(data)
#
# if event3 != 'string' and value3 != 'FeatureCollection':
# # We only want GeoJSON feature collections
# raise ValueError((prefix3, event3, value3))
#
# elif event2 == 'map_key' and value2 == 'features':
# prefix4, event4, value4 = next(data)
#
# if event4 != 'start_array':
# # We only want lists of features here.
# raise ValueError((prefix4, event4, value4))
#
# for (prefix5, event5, value5) in data:
# if event5 == 'end_array':
# break
#
# # let _build_value() handle the feature.
# _data = chain([(prefix5, event5, value5)], data)
# feature = _build_value(_data)
# yield feature
. Output only the next line. | 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')
self.assertEqual(geojson1['features'][0]['properties']['prop0'], 'value0')
self.assertEqual(geojson1['features'][0]['geometry']['type'], 'Point')
self.assertEqual(len(geojson1['features'][0]['geometry']['coordinates']), 2)
self.assertEqual(geojson1['features'][0]['geometry']['coordinates'][0], 102.)
self.assertEqual(geojson1['features'][0]['geometry']['coordinates'][1], .5)
self.assertEqual(geojson2['features'][1]['geometry']['type'], 'LineString')
self.assertEqual(len(geojson2['features'][1]['geometry']['coordinates']), 4)
self.assertEqual(geojson2['features'][1]['geometry']['coordinates'][0][0], 102.)
self.assertEqual(geojson2['features'][1]['geometry']['coordinates'][0][1], 0.)
self.assertEqual(geojson3['features'][2]['geometry']['type'], 'Polygon')
self.assertEqual(len(geojson3['features'][2]['geometry']['coordinates']), 1)
self.assertEqual(geojson3['features'][2]['geometry']['coordinates'][0][0][0], 100.)
self.assertEqual(geojson3['features'][2]['geometry']['coordinates'][0][0][1], 0.)
def test_stream(self):
geojson_input = b'''{ "type": "FeatureCollection", "features": [
{ "type": "Feature", "geometry": {"type": "Point", "coordinates": [102.0, 0.5]}, "properties": {"prop0": "value0"} },
{ "type": "Feature", "geometry": { "type": "LineString", "coordinates": [ [102.0, 0.0], [103.0, 1.0], [104.0, 0.0], [105.0, 1.0] ] }, "properties": { "prop0": "value0", "prop1": 0.0 } },
{ "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] ] }, "properties": { "prop0": "value0", "prop1": {"this": "that"}, "prop2": true, "prop3": null } }
] }'''
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import unittest
from io import BytesIO
from ..sample import sample_geojson, stream_geojson
and context (classes, functions, sometimes code) from other files:
# Path: openaddr/sample.py
# def sample_geojson(stream, max_features):
# ''' Read a stream of input GeoJSON and return a string with a limited feature count.
# '''
# features = list()
#
# for feature in stream_geojson(stream):
# if len(features) == max_features:
# break
#
# features.append(feature)
#
# geojson = dict(type='FeatureCollection', features=features)
# return json.dumps(geojson)
#
# def stream_geojson(stream):
# '''
# '''
# data = ijson.parse(stream)
#
# for (prefix1, event1, value1) in data:
# if event1 != 'start_map':
# # A root GeoJSON object is a map.
# raise ValueError((prefix1, event1, value1))
#
# for (prefix2, event2, value2) in data:
# if event2 == 'map_key' and value2 == 'type':
# prefix3, event3, value3 = next(data)
#
# if event3 != 'string' and value3 != 'FeatureCollection':
# # We only want GeoJSON feature collections
# raise ValueError((prefix3, event3, value3))
#
# elif event2 == 'map_key' and value2 == 'features':
# prefix4, event4, value4 = next(data)
#
# if event4 != 'start_array':
# # We only want lists of features here.
# raise ValueError((prefix4, event4, value4))
#
# for (prefix5, event5, value5) in data:
# if event5 == 'end_array':
# break
#
# # let _build_value() handle the feature.
# _data = chain([(prefix5, event5, value5)], data)
# feature = _build_value(_data)
# yield feature
. Output only the next line. | 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.sample = blob_dict.get('sample')
self.geometry_type = blob_dict.get('geometry type')
self.address_count = blob_dict.get('address count')
self.version = blob_dict.get('version')
self.fingerprint = blob_dict.get('fingerprint')
self.cache_time = blob_dict.get('cache time')
self.processed = blob_dict.get('processed')
self.output = blob_dict.get('output')
self.preview = blob_dict.get('preview')
self.slippymap = blob_dict.get('slippymap')
self.process_time = blob_dict.get('process time')
self.process_hash = blob_dict.get('process hash')
self.website = blob_dict.get('website')
self.skipped = blob_dict.get('skipped')
self.license = blob_dict.get('license')
self.share_alike = blob_dict.get('share-alike')
self.attribution_required = blob_dict.get('attribution required')
self.attribution_name = blob_dict.get('attribution name')
self.attribution_flag = blob_dict.get('attribution flag')
self.code_version = blob_dict.get('code version')
self.tests_passed = blob_dict.get('tests passed')
raw_problem = blob_dict.get('source problem', None)
<|code_end|>
with the help of current file imports:
import logging; _L = logging.getLogger('openaddr.ci.objects')
import json, pickle, copy, time
from ..process_one import SourceProblem
and context from other files:
# Path: openaddr/process_one.py
# class SourceProblem (enum.Enum):
# ''' Possible problems encountered in a source.
# '''
# skip_source = 'Source says to skip'
# missing_conform = 'Source is missing a conform object'
# unknown_conform_format = 'Unknown source conform format'
# unknown_conform_protocol = 'Unknown source conform protocol'
# download_source_failed = 'Could not download source data'
# conform_source_failed = 'Could not conform source data'
# no_coverage = 'Missing or incomplete coverage'
# no_esri_token = 'Missing required ESRI token'
# test_failed = 'An acceptance test failed'
# no_addresses_found = 'Found no addresses in source data'
#
# # Old tag naming; replaced with "format" or "protocol"
# unknown_conform_type = 'Unknown source conform type'
, which may contain function names, class names, or code. Output only the next line. | 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['geometry'])
if config.clean_geom:
if not geom.is_valid: # sends warnings to stderr
clean = geom.buffer(0.0) # attempt to clean shape
assert clean.is_valid
geom = clean
if geom.geom_type == 'Polygon':
return geom
return None
def scrape_fiona_metadata(obj, source):
"""
Uses openaddress machine code to scrape metadata from a fiona object.
"""
with open('{}/sources/{}'.format(config.openaddr_dir, source)) as file:
source_json = json.load(file)
<|code_end|>
with the help of current file imports:
import csv
import fiona
import json
import logging
import os
import requests
import sys
import traceback
import zipfile
from . import config
from shapely.geometry import shape
from shapely.wkt import loads, dumps
from openaddr.conform import conform_smash_case, row_transform_and_convert
and context from other files:
# Path: openaddr/conform.py
# def conform_smash_case(source_definition):
# "Convert all named fields in source_definition object to lowercase. Returns new object."
# new_sd = copy.deepcopy(source_definition)
# conform = new_sd["conform"]
# for k, v in conform.items():
# if v not in (X_FIELDNAME, Y_FIELDNAME) and getattr(v, 'lower', None):
# conform[k] = v.lower()
# if type(conform[k]) is list:
# conform[k] = [s.lower() for s in conform[k]]
# if type(conform[k]) is dict:
# fxn_smash_case(conform[k])
#
# if "functions" in conform[k] and type(conform[k]["functions"]) is list:
# for function in conform[k]["functions"]:
# if type(function) is dict:
# if "field" in function:
# function["field"] = function["field"].lower()
#
# if "fields" in function:
# function["fields"] = [s.lower() for s in function["fields"]]
#
# if "field_to_remove" in function:
# function["field_to_remove"] = function["field_to_remove"].lower()
#
# if "advanced_merge" in conform:
# raise ValueError('Found unsupported "advanced_merge" option in conform')
# return new_sd
#
# def row_transform_and_convert(sd, row):
# "Apply the full conform transform and extract operations to a row"
#
# # Some conform specs have fields named with a case different from the source
# row = row_smash_case(sd, row)
#
# c = sd["conform"]
#
# "Attribute tags can utilize processing fxns"
# for k, v in c.items():
# if k in attrib_types and type(v) is list:
# "Lists are a concat shortcut to concat fields with spaces"
# row = row_merge(sd, row, k)
# if k in attrib_types and type(v) is dict:
# "Dicts are custom processing functions"
# row = row_function(sd, row, k, v)
#
# if "advanced_merge" in c:
# raise ValueError('Found unsupported "advanced_merge" option in conform')
# if "split" in c:
# raise ValueError('Found unsupported "split" option in conform')
#
# # Make up a random fingerprint if none exists
# cache_fingerprint = sd.get('fingerprint', str(uuid4()))
#
# row2 = row_convert_to_out(sd, row)
# row3 = row_canonicalize_unit_and_number(sd, row2)
# row4 = row_round_lat_lon(sd, row3)
# row5 = row_calculate_hash(cache_fingerprint, row4)
# return row5
, which may contain function names, class names, or code. Output only the next line. | 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 to stderr
clean = geom.buffer(0.0) # attempt to clean shape
assert clean.is_valid
geom = clean
if geom.geom_type == 'Polygon':
return geom
return None
def scrape_fiona_metadata(obj, source):
"""
Uses openaddress machine code to scrape metadata from a fiona object.
"""
with open('{}/sources/{}'.format(config.openaddr_dir, source)) as file:
source_json = json.load(file)
cleaned_json = conform_smash_case(source_json)
cleaned_prop = {k: str(v or '') for (k, v) in obj['properties'].items()}
<|code_end|>
, generate the next line using the imports in this file:
import csv
import fiona
import json
import logging
import os
import requests
import sys
import traceback
import zipfile
from . import config
from shapely.geometry import shape
from shapely.wkt import loads, dumps
from openaddr.conform import conform_smash_case, row_transform_and_convert
and context (functions, classes, or occasionally code) from other files:
# Path: openaddr/conform.py
# def conform_smash_case(source_definition):
# "Convert all named fields in source_definition object to lowercase. Returns new object."
# new_sd = copy.deepcopy(source_definition)
# conform = new_sd["conform"]
# for k, v in conform.items():
# if v not in (X_FIELDNAME, Y_FIELDNAME) and getattr(v, 'lower', None):
# conform[k] = v.lower()
# if type(conform[k]) is list:
# conform[k] = [s.lower() for s in conform[k]]
# if type(conform[k]) is dict:
# fxn_smash_case(conform[k])
#
# if "functions" in conform[k] and type(conform[k]["functions"]) is list:
# for function in conform[k]["functions"]:
# if type(function) is dict:
# if "field" in function:
# function["field"] = function["field"].lower()
#
# if "fields" in function:
# function["fields"] = [s.lower() for s in function["fields"]]
#
# if "field_to_remove" in function:
# function["field_to_remove"] = function["field_to_remove"].lower()
#
# if "advanced_merge" in conform:
# raise ValueError('Found unsupported "advanced_merge" option in conform')
# return new_sd
#
# def row_transform_and_convert(sd, row):
# "Apply the full conform transform and extract operations to a row"
#
# # Some conform specs have fields named with a case different from the source
# row = row_smash_case(sd, row)
#
# c = sd["conform"]
#
# "Attribute tags can utilize processing fxns"
# for k, v in c.items():
# if k in attrib_types and type(v) is list:
# "Lists are a concat shortcut to concat fields with spaces"
# row = row_merge(sd, row, k)
# if k in attrib_types and type(v) is dict:
# "Dicts are custom processing functions"
# row = row_function(sd, row, k, v)
#
# if "advanced_merge" in c:
# raise ValueError('Found unsupported "advanced_merge" option in conform')
# if "split" in c:
# raise ValueError('Found unsupported "split" option in conform')
#
# # Make up a random fingerprint if none exists
# cache_fingerprint = sd.get('fingerprint', str(uuid4()))
#
# row2 = row_convert_to_out(sd, row)
# row3 = row_canonicalize_unit_and_number(sd, row2)
# row4 = row_round_lat_lon(sd, row3)
# row5 = row_calculate_hash(cache_fingerprint, row4)
# return row5
. Output only the next line. | 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)
header = state.pop(0)
return state, header
def filter_polygons(state, header):
"""
Removes any non-polygon sources from the state file.
We are only interested in parsing parcel data, which is
marked as Polygon in the state file.
"""
filtered_state = []
for source in state:
if 'Polygon' in source[header.index('geometry type')]:
filtered_state.append(source)
return filtered_state
if __name__ == '__main__':
<|code_end|>
with the help of current file imports:
import csv
import logging
import os
import re
import shutil
import sys
import traceback
from . import config
from openaddr.jobs import setup_logger
from shapely.wkt import dumps
from .utils import fetch, unzip, rlistdir, import_with_fiona, import_csv
and context from other files:
# Path: openaddr/jobs.py
# def setup_logger(logfile = None, log_level = logging.DEBUG, log_stderr = True, log_config_file = "~/.openaddr-logging.json"):
# ''' Set up logging for openaddr code.
# If the file ~/.openaddr-logging.json exists, it will be used as a DictConfig
# Otherwise a default configuration will be set according to function parameters.
# Default is to log DEBUG and above to stderr, and nothing to a file.
# '''
# # Get a handle for the openaddr logger and its children
# openaddr_logger = logging.getLogger('openaddr')
#
# # Default logging format. {0} will be replaced with a destination-appropriate timestamp
# log_format = '%(process)06s {0} %(levelname)06s: %(message)s'
#
# # Set the logger level to show everything, and filter down in the handlers.
# openaddr_logger.setLevel(logging.DEBUG)
#
# # Remove all previously installed handlers
# for old_handler in openaddr_logger.handlers:
# openaddr_logger.removeHandler(old_handler)
#
# # Tell multiprocessing to log messages as well. Multiprocessing can interact strangely
# # with logging, see http://bugs.python.org/issue23278
# mp_logger = multiprocessing.get_logger()
# mp_logger.propagate=True
#
# log_config_file = os.path.expanduser(log_config_file)
# if os.path.exists(log_config_file):
# # Use a JSON config file in the user's home directory if it exists
# # See http://victorlin.me/posts/2012/08/26/good-logging-practice-in-python
# log_config_dict = json.load(file(log_config_file))
# # Override this flag; needs to be set for our module-level loggers to work.
# log_config_dict['disable_existing_loggers'] = False
# logging.config.dictConfig(log_config_dict)
# openaddr_logger.info("Using logger config at %s", log_config_file)
# else:
# # No config file? Set up some sensible defaults
#
# # Set multiprocessing level as requested
# mp_logger.setLevel(log_level)
#
# everything_logger = logging.getLogger()
# # Set up a logger to stderr
# if log_stderr:
# handler1 = logging.StreamHandler()
# handler1.setLevel(log_level)
# handler1.setFormatter(logging.Formatter(log_format.format('%(relativeCreated)10.1f')))
# everything_logger.addHandler(handler1)
# # Set up a logger to a file
# if logfile:
# handler2 = logging.FileHandler(logfile, mode='w')
# handler2.setLevel(log_level)
# handler2.setFormatter(logging.Formatter(log_format.format('%(asctime)s')))
# everything_logger.addHandler(handler2)
#
# Path: openaddr/parcels/utils.py
# def fetch(url, filepath):
# r = requests.get(url, stream=True)
# with open(filepath, 'wb') as f:
# for chunk in r.iter_content(chunk_size=1024):
# if chunk: # filter out keep-alive new chunks
# f.write(chunk)
# f.flush()
#
# return filepath
#
# def unzip(filepath, dest):
# with zipfile.ZipFile(filepath) as zf:
# zf.extractall(dest)
#
# def rlistdir(path):
# """
# Recursively return all files in path.
#
# Does not follow symlinks.
# """
# files = []
# for dirpath, dirnames, filenames in os.walk(path):
# for f in filenames:
# files.append(os.path.join(dirpath, f))
#
# return files
#
# def import_with_fiona(fpath, source):
# """
# Use fiona to import a parcel file.
#
# Return a list of dict objects containing WKT-formatted geometries in
# addition to any metadata.
# """
# shapes = []
#
# try:
# with fiona.Env():
# data = fiona.open(fpath)
# for obj in data:
# try:
# shape = scrape_fiona_metadata(obj, source)
# geom = to_shapely_obj(obj)
# if geom:
# shape['geom'] = dumps(geom)
# shapes.append(shape)
# except Exception as e:
# _L.warning('error loading shape from fiona. {}'.format(e))
# except Exception as e:
# _L.warning('error importing file. {}'.format(e))
#
# return shapes
#
# def import_csv(fpath, source):
# """
# Import a csv file
#
# Return a list of dict objects containing WKT-formatted geometries in
# addition to any metadata.
# """
#
# data = []
# try:
# csvdata = []
# with open(fpath, 'r') as f:
# statereader = csv.reader(f, delimiter=',')
# for row in statereader:
# csvdata.append(row)
# header = csvdata.pop(0)
# for row in csvdata:
# try:
# shape = scrape_csv_metadata(row, header, source)
# shape['geom'] = row[header.index('OA:geom')]
# data.append(shape)
# except Exception as e:
# _L.warning('error loading shape from csv. {}'.format(e))
# except Exception as e:
# _L.warning('error importing csv. {}'.format(e))
#
# return data
, which may contain function names, class names, or code. Output only the next line. | 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)
if not os.path.exists(path):
os.makedirs(path)
cache_url = source[header.index('cache')]
cache_filename = re.search('/[^/]*$', cache_url).group()
<|code_end|>
, predict the next line using imports from the current file:
import csv
import logging
import os
import re
import shutil
import sys
import traceback
from . import config
from openaddr.jobs import setup_logger
from shapely.wkt import dumps
from .utils import fetch, unzip, rlistdir, import_with_fiona, import_csv
and context including class names, function names, and sometimes code from other files:
# Path: openaddr/jobs.py
# def setup_logger(logfile = None, log_level = logging.DEBUG, log_stderr = True, log_config_file = "~/.openaddr-logging.json"):
# ''' Set up logging for openaddr code.
# If the file ~/.openaddr-logging.json exists, it will be used as a DictConfig
# Otherwise a default configuration will be set according to function parameters.
# Default is to log DEBUG and above to stderr, and nothing to a file.
# '''
# # Get a handle for the openaddr logger and its children
# openaddr_logger = logging.getLogger('openaddr')
#
# # Default logging format. {0} will be replaced with a destination-appropriate timestamp
# log_format = '%(process)06s {0} %(levelname)06s: %(message)s'
#
# # Set the logger level to show everything, and filter down in the handlers.
# openaddr_logger.setLevel(logging.DEBUG)
#
# # Remove all previously installed handlers
# for old_handler in openaddr_logger.handlers:
# openaddr_logger.removeHandler(old_handler)
#
# # Tell multiprocessing to log messages as well. Multiprocessing can interact strangely
# # with logging, see http://bugs.python.org/issue23278
# mp_logger = multiprocessing.get_logger()
# mp_logger.propagate=True
#
# log_config_file = os.path.expanduser(log_config_file)
# if os.path.exists(log_config_file):
# # Use a JSON config file in the user's home directory if it exists
# # See http://victorlin.me/posts/2012/08/26/good-logging-practice-in-python
# log_config_dict = json.load(file(log_config_file))
# # Override this flag; needs to be set for our module-level loggers to work.
# log_config_dict['disable_existing_loggers'] = False
# logging.config.dictConfig(log_config_dict)
# openaddr_logger.info("Using logger config at %s", log_config_file)
# else:
# # No config file? Set up some sensible defaults
#
# # Set multiprocessing level as requested
# mp_logger.setLevel(log_level)
#
# everything_logger = logging.getLogger()
# # Set up a logger to stderr
# if log_stderr:
# handler1 = logging.StreamHandler()
# handler1.setLevel(log_level)
# handler1.setFormatter(logging.Formatter(log_format.format('%(relativeCreated)10.1f')))
# everything_logger.addHandler(handler1)
# # Set up a logger to a file
# if logfile:
# handler2 = logging.FileHandler(logfile, mode='w')
# handler2.setLevel(log_level)
# handler2.setFormatter(logging.Formatter(log_format.format('%(asctime)s')))
# everything_logger.addHandler(handler2)
#
# Path: openaddr/parcels/utils.py
# def fetch(url, filepath):
# r = requests.get(url, stream=True)
# with open(filepath, 'wb') as f:
# for chunk in r.iter_content(chunk_size=1024):
# if chunk: # filter out keep-alive new chunks
# f.write(chunk)
# f.flush()
#
# return filepath
#
# def unzip(filepath, dest):
# with zipfile.ZipFile(filepath) as zf:
# zf.extractall(dest)
#
# def rlistdir(path):
# """
# Recursively return all files in path.
#
# Does not follow symlinks.
# """
# files = []
# for dirpath, dirnames, filenames in os.walk(path):
# for f in filenames:
# files.append(os.path.join(dirpath, f))
#
# return files
#
# def import_with_fiona(fpath, source):
# """
# Use fiona to import a parcel file.
#
# Return a list of dict objects containing WKT-formatted geometries in
# addition to any metadata.
# """
# shapes = []
#
# try:
# with fiona.Env():
# data = fiona.open(fpath)
# for obj in data:
# try:
# shape = scrape_fiona_metadata(obj, source)
# geom = to_shapely_obj(obj)
# if geom:
# shape['geom'] = dumps(geom)
# shapes.append(shape)
# except Exception as e:
# _L.warning('error loading shape from fiona. {}'.format(e))
# except Exception as e:
# _L.warning('error importing file. {}'.format(e))
#
# return shapes
#
# def import_csv(fpath, source):
# """
# Import a csv file
#
# Return a list of dict objects containing WKT-formatted geometries in
# addition to any metadata.
# """
#
# data = []
# try:
# csvdata = []
# with open(fpath, 'r') as f:
# statereader = csv.reader(f, delimiter=',')
# for row in statereader:
# csvdata.append(row)
# header = csvdata.pop(0)
# for row in csvdata:
# try:
# shape = scrape_csv_metadata(row, header, source)
# shape['geom'] = row[header.index('OA:geom')]
# data.append(shape)
# except Exception as e:
# _L.warning('error loading shape from csv. {}'.format(e))
# except Exception as e:
# _L.warning('error importing csv. {}'.format(e))
#
# return data
. Output only the next line. | 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)
if not os.path.exists(path):
os.makedirs(path)
cache_url = source[header.index('cache')]
cache_filename = re.search('/[^/]*$', cache_url).group()
fetch(cache_url, path + cache_filename)
files = rlistdir(path)
for f in files:
if re.match('.*\.(zip|obj|exe)$', f): # some files had mislabelled ext
<|code_end|>
, predict the next line using imports from the current file:
import csv
import logging
import os
import re
import shutil
import sys
import traceback
from . import config
from openaddr.jobs import setup_logger
from shapely.wkt import dumps
from .utils import fetch, unzip, rlistdir, import_with_fiona, import_csv
and context including class names, function names, and sometimes code from other files:
# Path: openaddr/jobs.py
# def setup_logger(logfile = None, log_level = logging.DEBUG, log_stderr = True, log_config_file = "~/.openaddr-logging.json"):
# ''' Set up logging for openaddr code.
# If the file ~/.openaddr-logging.json exists, it will be used as a DictConfig
# Otherwise a default configuration will be set according to function parameters.
# Default is to log DEBUG and above to stderr, and nothing to a file.
# '''
# # Get a handle for the openaddr logger and its children
# openaddr_logger = logging.getLogger('openaddr')
#
# # Default logging format. {0} will be replaced with a destination-appropriate timestamp
# log_format = '%(process)06s {0} %(levelname)06s: %(message)s'
#
# # Set the logger level to show everything, and filter down in the handlers.
# openaddr_logger.setLevel(logging.DEBUG)
#
# # Remove all previously installed handlers
# for old_handler in openaddr_logger.handlers:
# openaddr_logger.removeHandler(old_handler)
#
# # Tell multiprocessing to log messages as well. Multiprocessing can interact strangely
# # with logging, see http://bugs.python.org/issue23278
# mp_logger = multiprocessing.get_logger()
# mp_logger.propagate=True
#
# log_config_file = os.path.expanduser(log_config_file)
# if os.path.exists(log_config_file):
# # Use a JSON config file in the user's home directory if it exists
# # See http://victorlin.me/posts/2012/08/26/good-logging-practice-in-python
# log_config_dict = json.load(file(log_config_file))
# # Override this flag; needs to be set for our module-level loggers to work.
# log_config_dict['disable_existing_loggers'] = False
# logging.config.dictConfig(log_config_dict)
# openaddr_logger.info("Using logger config at %s", log_config_file)
# else:
# # No config file? Set up some sensible defaults
#
# # Set multiprocessing level as requested
# mp_logger.setLevel(log_level)
#
# everything_logger = logging.getLogger()
# # Set up a logger to stderr
# if log_stderr:
# handler1 = logging.StreamHandler()
# handler1.setLevel(log_level)
# handler1.setFormatter(logging.Formatter(log_format.format('%(relativeCreated)10.1f')))
# everything_logger.addHandler(handler1)
# # Set up a logger to a file
# if logfile:
# handler2 = logging.FileHandler(logfile, mode='w')
# handler2.setLevel(log_level)
# handler2.setFormatter(logging.Formatter(log_format.format('%(asctime)s')))
# everything_logger.addHandler(handler2)
#
# Path: openaddr/parcels/utils.py
# def fetch(url, filepath):
# r = requests.get(url, stream=True)
# with open(filepath, 'wb') as f:
# for chunk in r.iter_content(chunk_size=1024):
# if chunk: # filter out keep-alive new chunks
# f.write(chunk)
# f.flush()
#
# return filepath
#
# def unzip(filepath, dest):
# with zipfile.ZipFile(filepath) as zf:
# zf.extractall(dest)
#
# def rlistdir(path):
# """
# Recursively return all files in path.
#
# Does not follow symlinks.
# """
# files = []
# for dirpath, dirnames, filenames in os.walk(path):
# for f in filenames:
# files.append(os.path.join(dirpath, f))
#
# return files
#
# def import_with_fiona(fpath, source):
# """
# Use fiona to import a parcel file.
#
# Return a list of dict objects containing WKT-formatted geometries in
# addition to any metadata.
# """
# shapes = []
#
# try:
# with fiona.Env():
# data = fiona.open(fpath)
# for obj in data:
# try:
# shape = scrape_fiona_metadata(obj, source)
# geom = to_shapely_obj(obj)
# if geom:
# shape['geom'] = dumps(geom)
# shapes.append(shape)
# except Exception as e:
# _L.warning('error loading shape from fiona. {}'.format(e))
# except Exception as e:
# _L.warning('error importing file. {}'.format(e))
#
# return shapes
#
# def import_csv(fpath, source):
# """
# Import a csv file
#
# Return a list of dict objects containing WKT-formatted geometries in
# addition to any metadata.
# """
#
# data = []
# try:
# csvdata = []
# with open(fpath, 'r') as f:
# statereader = csv.reader(f, delimiter=',')
# for row in statereader:
# csvdata.append(row)
# header = csvdata.pop(0)
# for row in csvdata:
# try:
# shape = scrape_csv_metadata(row, header, source)
# shape['geom'] = row[header.index('OA:geom')]
# data.append(shape)
# except Exception as e:
# _L.warning('error loading shape from csv. {}'.format(e))
# except Exception as e:
# _L.warning('error importing csv. {}'.format(e))
#
# return data
. Output only the next line. | 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):
os.makedirs(path)
cache_url = source[header.index('cache')]
cache_filename = re.search('/[^/]*$', cache_url).group()
fetch(cache_url, path + cache_filename)
<|code_end|>
, predict the immediate next line with the help of imports:
import csv
import logging
import os
import re
import shutil
import sys
import traceback
from . import config
from openaddr.jobs import setup_logger
from shapely.wkt import dumps
from .utils import fetch, unzip, rlistdir, import_with_fiona, import_csv
and context (classes, functions, sometimes code) from other files:
# Path: openaddr/jobs.py
# def setup_logger(logfile = None, log_level = logging.DEBUG, log_stderr = True, log_config_file = "~/.openaddr-logging.json"):
# ''' Set up logging for openaddr code.
# If the file ~/.openaddr-logging.json exists, it will be used as a DictConfig
# Otherwise a default configuration will be set according to function parameters.
# Default is to log DEBUG and above to stderr, and nothing to a file.
# '''
# # Get a handle for the openaddr logger and its children
# openaddr_logger = logging.getLogger('openaddr')
#
# # Default logging format. {0} will be replaced with a destination-appropriate timestamp
# log_format = '%(process)06s {0} %(levelname)06s: %(message)s'
#
# # Set the logger level to show everything, and filter down in the handlers.
# openaddr_logger.setLevel(logging.DEBUG)
#
# # Remove all previously installed handlers
# for old_handler in openaddr_logger.handlers:
# openaddr_logger.removeHandler(old_handler)
#
# # Tell multiprocessing to log messages as well. Multiprocessing can interact strangely
# # with logging, see http://bugs.python.org/issue23278
# mp_logger = multiprocessing.get_logger()
# mp_logger.propagate=True
#
# log_config_file = os.path.expanduser(log_config_file)
# if os.path.exists(log_config_file):
# # Use a JSON config file in the user's home directory if it exists
# # See http://victorlin.me/posts/2012/08/26/good-logging-practice-in-python
# log_config_dict = json.load(file(log_config_file))
# # Override this flag; needs to be set for our module-level loggers to work.
# log_config_dict['disable_existing_loggers'] = False
# logging.config.dictConfig(log_config_dict)
# openaddr_logger.info("Using logger config at %s", log_config_file)
# else:
# # No config file? Set up some sensible defaults
#
# # Set multiprocessing level as requested
# mp_logger.setLevel(log_level)
#
# everything_logger = logging.getLogger()
# # Set up a logger to stderr
# if log_stderr:
# handler1 = logging.StreamHandler()
# handler1.setLevel(log_level)
# handler1.setFormatter(logging.Formatter(log_format.format('%(relativeCreated)10.1f')))
# everything_logger.addHandler(handler1)
# # Set up a logger to a file
# if logfile:
# handler2 = logging.FileHandler(logfile, mode='w')
# handler2.setLevel(log_level)
# handler2.setFormatter(logging.Formatter(log_format.format('%(asctime)s')))
# everything_logger.addHandler(handler2)
#
# Path: openaddr/parcels/utils.py
# def fetch(url, filepath):
# r = requests.get(url, stream=True)
# with open(filepath, 'wb') as f:
# for chunk in r.iter_content(chunk_size=1024):
# if chunk: # filter out keep-alive new chunks
# f.write(chunk)
# f.flush()
#
# return filepath
#
# def unzip(filepath, dest):
# with zipfile.ZipFile(filepath) as zf:
# zf.extractall(dest)
#
# def rlistdir(path):
# """
# Recursively return all files in path.
#
# Does not follow symlinks.
# """
# files = []
# for dirpath, dirnames, filenames in os.walk(path):
# for f in filenames:
# files.append(os.path.join(dirpath, f))
#
# return files
#
# def import_with_fiona(fpath, source):
# """
# Use fiona to import a parcel file.
#
# Return a list of dict objects containing WKT-formatted geometries in
# addition to any metadata.
# """
# shapes = []
#
# try:
# with fiona.Env():
# data = fiona.open(fpath)
# for obj in data:
# try:
# shape = scrape_fiona_metadata(obj, source)
# geom = to_shapely_obj(obj)
# if geom:
# shape['geom'] = dumps(geom)
# shapes.append(shape)
# except Exception as e:
# _L.warning('error loading shape from fiona. {}'.format(e))
# except Exception as e:
# _L.warning('error importing file. {}'.format(e))
#
# return shapes
#
# def import_csv(fpath, source):
# """
# Import a csv file
#
# Return a list of dict objects containing WKT-formatted geometries in
# addition to any metadata.
# """
#
# data = []
# try:
# csvdata = []
# with open(fpath, 'r') as f:
# statereader = csv.reader(f, delimiter=',')
# for row in statereader:
# csvdata.append(row)
# header = csvdata.pop(0)
# for row in csvdata:
# try:
# shape = scrape_csv_metadata(row, header, source)
# shape['geom'] = row[header.index('OA:geom')]
# data.append(shape)
# except Exception as e:
# _L.warning('error loading shape from csv. {}'.format(e))
# except Exception as e:
# _L.warning('error importing csv. {}'.format(e))
#
# return data
. Output only the next line. | 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_paths:
return []
csv_path = ExcerptDataTask._make_csv_path(unzipped_paths.get(conform['file']))
return [csv_path]
@staticmethod
def _make_csv_path(csv_path):
_, csv_ext = os.path.splitext(csv_path.lower())
if csv_ext != '.csv':
# Convince OGR it's looking at a CSV file.
new_path = csv_path + '.csv'
os.link(csv_path, new_path)
csv_path = new_path
return csv_path
@staticmethod
def _sample_geojson_file(data_path):
# Sample a few GeoJSON features to save on memory for large datasets.
with open(data_path, 'r') as complete_layer:
temp_dir = os.path.dirname(data_path)
_, temp_path = tempfile.mkstemp(dir=temp_dir, suffix='.json')
with open(temp_path, 'w') as temp_file:
<|code_end|>
with the help of current file imports:
import logging; _L = logging.getLogger('openaddr.conform')
import os
import errno
import tempfile
import mimetypes
import json
import copy
import csv
import re
from zipfile import ZipFile
from locale import getpreferredencoding
from os.path import splitext
from hashlib import sha1
from uuid import uuid4
from .sample import sample_geojson, stream_geojson
from osgeo import ogr, osr, gdal
and context from other files:
# Path: openaddr/sample.py
# def sample_geojson(stream, max_features):
# ''' Read a stream of input GeoJSON and return a string with a limited feature count.
# '''
# features = list()
#
# for feature in stream_geojson(stream):
# if len(features) == max_features:
# break
#
# features.append(feature)
#
# geojson = dict(type='FeatureCollection', features=features)
# return json.dumps(geojson)
#
# def stream_geojson(stream):
# '''
# '''
# data = ijson.parse(stream)
#
# for (prefix1, event1, value1) in data:
# if event1 != 'start_map':
# # A root GeoJSON object is a map.
# raise ValueError((prefix1, event1, value1))
#
# for (prefix2, event2, value2) in data:
# if event2 == 'map_key' and value2 == 'type':
# prefix3, event3, value3 = next(data)
#
# if event3 != 'string' and value3 != 'FeatureCollection':
# # We only want GeoJSON feature collections
# raise ValueError((prefix3, event3, value3))
#
# elif event2 == 'map_key' and value2 == 'features':
# prefix4, event4, value4 = next(data)
#
# if event4 != 'start_array':
# # We only want lists of features here.
# raise ValueError((prefix4, event4, value4))
#
# for (prefix5, event5, value5) in data:
# if event5 == 'end_array':
# break
#
# # let _build_value() handle the feature.
# _data = chain([(prefix5, event5, value5)], data)
# feature = _build_value(_data)
# yield feature
, which may contain function names, class names, or code. Output only the next line. | 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.writeheader()
# For every row in the source CSV
row_number = 0
for source_row in reader:
row_number += 1
if len(source_row) != num_fields:
_L.debug("Skipping row. Got %d columns, expected %d", len(source_row), num_fields)
continue
try:
out_row = row_extract_and_reproject(source_definition, source_row)
except Exception as e:
_L.error('Error in row {}: {}'.format(row_number, e))
raise
else:
writer.writerow(out_row)
def geojson_source_to_csv(source_path, dest_path):
'''
'''
# For every row in the source GeoJSON
with open(source_path) as file:
# Write the extracted CSV file
with open(dest_path, 'w', encoding='utf-8') as dest_fp:
writer = None
<|code_end|>
. Write the next line using the current file imports:
import logging; _L = logging.getLogger('openaddr.conform')
import os
import errno
import tempfile
import mimetypes
import json
import copy
import csv
import re
from zipfile import ZipFile
from locale import getpreferredencoding
from os.path import splitext
from hashlib import sha1
from uuid import uuid4
from .sample import sample_geojson, stream_geojson
from osgeo import ogr, osr, gdal
and context from other files:
# Path: openaddr/sample.py
# def sample_geojson(stream, max_features):
# ''' Read a stream of input GeoJSON and return a string with a limited feature count.
# '''
# features = list()
#
# for feature in stream_geojson(stream):
# if len(features) == max_features:
# break
#
# features.append(feature)
#
# geojson = dict(type='FeatureCollection', features=features)
# return json.dumps(geojson)
#
# def stream_geojson(stream):
# '''
# '''
# data = ijson.parse(stream)
#
# for (prefix1, event1, value1) in data:
# if event1 != 'start_map':
# # A root GeoJSON object is a map.
# raise ValueError((prefix1, event1, value1))
#
# for (prefix2, event2, value2) in data:
# if event2 == 'map_key' and value2 == 'type':
# prefix3, event3, value3 = next(data)
#
# if event3 != 'string' and value3 != 'FeatureCollection':
# # We only want GeoJSON feature collections
# raise ValueError((prefix3, event3, value3))
#
# elif event2 == 'map_key' and value2 == 'features':
# prefix4, event4, value4 = next(data)
#
# if event4 != 'start_array':
# # We only want lists of features here.
# raise ValueError((prefix4, event4, value4))
#
# for (prefix5, event5, value5) in data:
# if event5 == 'end_array':
# break
#
# # let _build_value() handle the feature.
# _data = chain([(prefix5, event5, value5)], data)
# feature = _build_value(_data)
# yield feature
, which may include functions, classes, or code. Output only the next line. | 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)
vsize = int(hsize / aspect)
hscale = hsize / (right - left)
vscale = (hsize / aspect) / (bottom - top)
hoffset = -left
voffset = -top
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, hsize, vsize)
context = cairo.Context(surface)
context.scale(hscale, vscale)
context.translate(hoffset, voffset)
return surface, context, hscale
def load_live_state():
'''
'''
got = requests.get('https://results.openaddresses.io/state.txt')
state = csv.DictReader(io.StringIO(got.text), dialect='excel-tab')
<|code_end|>
using the current file's imports:
import logging; _L = logging.getLogger('openaddr.render')
import json, csv, io, os
import requests
import cairo
import cairocffi as cairo
from glob import glob
from unicodedata import normalize
from collections import defaultdict
from argparse import ArgumentParser
from itertools import combinations, chain
from os.path import join, dirname, splitext, relpath
from urllib.parse import urljoin
from osgeo import ogr, osr
from .ci import objects
and any relevant context from other files:
# Path: openaddr/ci/objects.py
# import logging; _L = logging.getLogger('openaddr.ci.objects')
# class Job:
# class Set:
# class Run:
# class RunState:
# class Zip:
# def __init__(self, id, status, task_files, states, file_results,
# github_owner, github_repository, github_status_url,
# github_comments_url, datetime_start, datetime_end):
# def __init__(self, id, commit_sha, datetime_start, datetime_end,
# render_world, render_europe, render_usa, render_geojson,
# owner, repository):
# def __init__(self, id, source_path, source_id, source_data, datetime_tz,
# state, status, copy_of, code_version, worker_id, job_id,
# set_id, commit_sha, is_merged):
# def __init__(self, json_blob):
# def get(self, json_key):
# def to_dict(self):
# def to_json(self):
# def __init__(self, url, content_length):
# def _result_runstate2dictionary(result):
# def result_dictionary2runstate(result):
# def add_job(db, job_id, status, task_files, file_states, file_results, owner, repo, status_url, comments_url):
# def write_job(db, job_id, status, task_files, file_states, file_results, owner, repo, status_url, comments_url):
# def read_job(db, job_id):
# def read_jobs(db, past_id):
# def add_set(db, owner, repository):
# def complete_set(db, set_id, commit_sha):
# def update_set_renders(db, set_id, render_world, render_usa, render_europe, render_geojson):
# def read_set(db, set_id):
# def read_sets(db, past_id):
# def read_latest_set(db, owner, repository):
# def add_run(db):
# def set_run(db, run_id, filename, file_id, content_b64, run_state, run_status,
# job_id, worker_id, commit_sha, is_merged, set_id):
# def copy_run(db, run_id, job_id, commit_sha, set_id):
# def read_run(db, run_id):
# def get_completed_file_run(db, file_id, interval):
# def get_completed_run(db, run_id, min_dtz):
# def old_read_completed_set_runs(db, set_id):
# def read_completed_set_runs(db, set_id):
# def read_completed_set_runs_count(db, set_id):
# def read_completed_source_runs(db, source_path):
# def read_completed_runs_to_date_cheaply(db):
# def read_completed_runs_to_date(db, starting_set_id):
# def mark_runs_for_index_page(db, runs):
# def read_latest_run(db, source_path):
# def load_collection_zips_dict(db):
. Output only the next line. | 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:
import os
import copy
import json
import csv
import re
import unittest
import tempfile
import shutil
from ..conform import (
GEOM_FIELDNAME, X_FIELDNAME, Y_FIELDNAME,
csv_source_to_csv, find_source_path, row_transform_and_convert,
row_fxn_regexp, row_smash_case, row_round_lat_lon, row_merge,
row_extract_and_reproject, row_convert_to_out, row_fxn_join, row_fxn_format,
row_fxn_prefixed_number, row_fxn_postfixed_street,
row_fxn_postfixed_unit,
row_fxn_remove_prefix, row_fxn_remove_postfix, row_fxn_chain,
row_fxn_first_non_empty,
row_fxn_get_from_array_string,
row_canonicalize_unit_and_number, conform_smash_case, conform_cli,
convert_regexp_replace, conform_license,
conform_attribution, conform_sharealike, normalize_ogr_filename_case,
OPENADDR_CSV_SCHEMA, is_in, geojson_source_to_csv, check_source_tests
)
and context from other files:
# Path: openaddr/conform.py
# import logging; _L = logging.getLogger('openaddr.conform')
# OPENADDR_CSV_SCHEMA = ['LON', 'LAT', 'NUMBER', 'STREET', 'UNIT', 'CITY',
# 'DISTRICT', 'REGION', 'POSTCODE', 'ID', 'HASH']
# GEOM_FIELDNAME = 'OA:geom'
# X_FIELDNAME, Y_FIELDNAME = 'OA:x', 'OA:y'
# UNZIPPED_DIRNAME = 'unzipped'
# def gdal_error_handler(err_class, err_num, err_msg):
# def mkdirsp(path):
# def __init__(self, processed, sample, website, license, geometry_type,
# address_count, path, elapsed, sharealike_flag,
# attribution_flag, attribution_name):
# def empty():
# def todict(self):
# def from_format_string(clz, format_string):
# def decompress(self, source_paths):
# def decompress(self, source_paths, workdir, filenames):
# def is_in(path, names):
# def decompress(self, source_paths, workdir, filenames):
# def excerpt(self, source_paths, workdir, conform):
# def _get_known_paths(source_paths, workdir, conform, known_types):
# def _make_csv_path(csv_path):
# def _sample_geojson_file(data_path):
# def _excerpt_csv_file(data_path, encoding, csvsplit):
# def elaborate_filenames(filename):
# def guess_source_encoding(datasource, layer):
# def find_source_path(source_definition, source_paths):
# def convert(self, source_definition, source_paths, workdir):
# def convert_regexp_replace(replace):
# def normalize_ogr_filename_case(source_path):
# def ogr_source_to_csv(source_definition, source_path, dest_path):
# def csv_source_to_csv(source_definition, source_path, dest_path):
# def geojson_source_to_csv(source_path, dest_path):
# def _transform_to_4326(srs):
# def row_extract_and_reproject(source_definition, source_row):
# def row_function(sd, row, key, fxn):
# def row_transform_and_convert(sd, row):
# def fxn_smash_case(fxn):
# def conform_smash_case(source_definition):
# def row_smash_case(sd, input):
# def row_merge(sd, row, key):
# def row_fxn_join(sd, row, key, fxn):
# def row_fxn_regexp(sd, row, key, fxn):
# def row_fxn_prefixed_number(sd, row, key, fxn):
# def row_fxn_postfixed_street(sd, row, key, fxn):
# def row_fxn_postfixed_unit(sd, row, key, fxn):
# def row_fxn_remove_prefix(sd, row, key, fxn):
# def row_fxn_remove_postfix(sd, row, key, fxn):
# def row_fxn_format(sd, row, key, fxn):
# def row_fxn_chain(sd, row, key, fxn):
# def row_fxn_first_non_empty(sd, row, key, fxn):
# def row_fxn_get_from_array_string(sd, row, key, fxn):
# def row_canonicalize_unit_and_number(sd, row):
# def _round_wgs84_to_7(n):
# def row_round_lat_lon(sd, row):
# def row_calculate_hash(cache_fingerprint, row):
# def row_convert_to_out(sd, row):
# def extract_to_source_csv(source_definition, source_path, extract_path):
# def transform_to_out_csv(source_definition, extract_path, dest_path):
# def conform_cli(source_definition, source_path, dest_path):
# def conform_license(license):
# def conform_attribution(license, attribution):
# def conform_sharealike(license):
# def check_source_tests(raw_source):
# class ConformResult:
# class DecompressionError(Exception):
# class DecompressionTask(object):
# class GuessDecompressTask(DecompressionTask):
# class ZipDecompressTask(DecompressionTask):
# class ExcerptDataTask(object):
# class ConvertToCsvTask(object):
, which may include functions, classes, or code. Output only the next line. | 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_units": True
}
} }
d = { "ADDRESS": "123 MAPLE ST" }
e = copy.deepcopy(d)
e.update({ "OA:street": "MAPLE ST" })
d = row_fxn_postfixed_street(c, d, "street", c["conform"]["street"])
self.assertEqual(e, d)
def test_row_fxn_postfixed_unit(self):
"postfixed_unit - UNIT-style"
c = { "conform": {
"unit": {
"function": "postfixed_unit",
"field": "ADDRESS"
}
} }
d = { "ADDRESS": "Main Street Unit 300" }
e = copy.deepcopy(d)
e.update({ "OA:unit": "Unit 300" })
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import copy
import json
import csv
import re
import unittest
import tempfile
import shutil
from ..conform import (
GEOM_FIELDNAME, X_FIELDNAME, Y_FIELDNAME,
csv_source_to_csv, find_source_path, row_transform_and_convert,
row_fxn_regexp, row_smash_case, row_round_lat_lon, row_merge,
row_extract_and_reproject, row_convert_to_out, row_fxn_join, row_fxn_format,
row_fxn_prefixed_number, row_fxn_postfixed_street,
row_fxn_postfixed_unit,
row_fxn_remove_prefix, row_fxn_remove_postfix, row_fxn_chain,
row_fxn_first_non_empty,
row_fxn_get_from_array_string,
row_canonicalize_unit_and_number, conform_smash_case, conform_cli,
convert_regexp_replace, conform_license,
conform_attribution, conform_sharealike, normalize_ogr_filename_case,
OPENADDR_CSV_SCHEMA, is_in, geojson_source_to_csv, check_source_tests
)
and context:
# Path: openaddr/conform.py
# import logging; _L = logging.getLogger('openaddr.conform')
# OPENADDR_CSV_SCHEMA = ['LON', 'LAT', 'NUMBER', 'STREET', 'UNIT', 'CITY',
# 'DISTRICT', 'REGION', 'POSTCODE', 'ID', 'HASH']
# GEOM_FIELDNAME = 'OA:geom'
# X_FIELDNAME, Y_FIELDNAME = 'OA:x', 'OA:y'
# UNZIPPED_DIRNAME = 'unzipped'
# def gdal_error_handler(err_class, err_num, err_msg):
# def mkdirsp(path):
# def __init__(self, processed, sample, website, license, geometry_type,
# address_count, path, elapsed, sharealike_flag,
# attribution_flag, attribution_name):
# def empty():
# def todict(self):
# def from_format_string(clz, format_string):
# def decompress(self, source_paths):
# def decompress(self, source_paths, workdir, filenames):
# def is_in(path, names):
# def decompress(self, source_paths, workdir, filenames):
# def excerpt(self, source_paths, workdir, conform):
# def _get_known_paths(source_paths, workdir, conform, known_types):
# def _make_csv_path(csv_path):
# def _sample_geojson_file(data_path):
# def _excerpt_csv_file(data_path, encoding, csvsplit):
# def elaborate_filenames(filename):
# def guess_source_encoding(datasource, layer):
# def find_source_path(source_definition, source_paths):
# def convert(self, source_definition, source_paths, workdir):
# def convert_regexp_replace(replace):
# def normalize_ogr_filename_case(source_path):
# def ogr_source_to_csv(source_definition, source_path, dest_path):
# def csv_source_to_csv(source_definition, source_path, dest_path):
# def geojson_source_to_csv(source_path, dest_path):
# def _transform_to_4326(srs):
# def row_extract_and_reproject(source_definition, source_row):
# def row_function(sd, row, key, fxn):
# def row_transform_and_convert(sd, row):
# def fxn_smash_case(fxn):
# def conform_smash_case(source_definition):
# def row_smash_case(sd, input):
# def row_merge(sd, row, key):
# def row_fxn_join(sd, row, key, fxn):
# def row_fxn_regexp(sd, row, key, fxn):
# def row_fxn_prefixed_number(sd, row, key, fxn):
# def row_fxn_postfixed_street(sd, row, key, fxn):
# def row_fxn_postfixed_unit(sd, row, key, fxn):
# def row_fxn_remove_prefix(sd, row, key, fxn):
# def row_fxn_remove_postfix(sd, row, key, fxn):
# def row_fxn_format(sd, row, key, fxn):
# def row_fxn_chain(sd, row, key, fxn):
# def row_fxn_first_non_empty(sd, row, key, fxn):
# def row_fxn_get_from_array_string(sd, row, key, fxn):
# def row_canonicalize_unit_and_number(sd, row):
# def _round_wgs84_to_7(n):
# def row_round_lat_lon(sd, row):
# def row_calculate_hash(cache_fingerprint, row):
# def row_convert_to_out(sd, row):
# def extract_to_source_csv(source_definition, source_path, extract_path):
# def transform_to_out_csv(source_definition, extract_path, dest_path):
# def conform_cli(source_definition, source_path, dest_path):
# def conform_license(license):
# def conform_attribution(license, attribution):
# def conform_sharealike(license):
# def check_source_tests(raw_source):
# class ConformResult:
# class DecompressionError(Exception):
# class DecompressionTask(object):
# class GuessDecompressTask(DecompressionTask):
# class ZipDecompressTask(DecompressionTask):
# class ExcerptDataTask(object):
# class ConvertToCsvTask(object):
which might include code, classes, or functions. Output only the next line. | 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 = { "ADDRESS": "Main Street" }
e = copy.deepcopy(d)
e.update({ "OA:unit": "" })
d = row_fxn_postfixed_unit(c, d, "unit", c["conform"]["unit"])
self.assertEqual(e, d)
def test_row_fxn_remove_prefix(self):
"remove_prefix - field_to_remove is a prefix"
c = { "conform": {
"street": {
"function": "remove_prefix",
"field": "ADDRESS",
"field_to_remove": "PREFIX"
}
} }
d = { "ADDRESS": "123 MAPLE ST", "PREFIX": "123" }
e = copy.deepcopy(d)
e.update({ "OA:street": "MAPLE ST" })
<|code_end|>
with the help of current file imports:
import os
import copy
import json
import csv
import re
import unittest
import tempfile
import shutil
from ..conform import (
GEOM_FIELDNAME, X_FIELDNAME, Y_FIELDNAME,
csv_source_to_csv, find_source_path, row_transform_and_convert,
row_fxn_regexp, row_smash_case, row_round_lat_lon, row_merge,
row_extract_and_reproject, row_convert_to_out, row_fxn_join, row_fxn_format,
row_fxn_prefixed_number, row_fxn_postfixed_street,
row_fxn_postfixed_unit,
row_fxn_remove_prefix, row_fxn_remove_postfix, row_fxn_chain,
row_fxn_first_non_empty,
row_fxn_get_from_array_string,
row_canonicalize_unit_and_number, conform_smash_case, conform_cli,
convert_regexp_replace, conform_license,
conform_attribution, conform_sharealike, normalize_ogr_filename_case,
OPENADDR_CSV_SCHEMA, is_in, geojson_source_to_csv, check_source_tests
)
and context from other files:
# Path: openaddr/conform.py
# import logging; _L = logging.getLogger('openaddr.conform')
# OPENADDR_CSV_SCHEMA = ['LON', 'LAT', 'NUMBER', 'STREET', 'UNIT', 'CITY',
# 'DISTRICT', 'REGION', 'POSTCODE', 'ID', 'HASH']
# GEOM_FIELDNAME = 'OA:geom'
# X_FIELDNAME, Y_FIELDNAME = 'OA:x', 'OA:y'
# UNZIPPED_DIRNAME = 'unzipped'
# def gdal_error_handler(err_class, err_num, err_msg):
# def mkdirsp(path):
# def __init__(self, processed, sample, website, license, geometry_type,
# address_count, path, elapsed, sharealike_flag,
# attribution_flag, attribution_name):
# def empty():
# def todict(self):
# def from_format_string(clz, format_string):
# def decompress(self, source_paths):
# def decompress(self, source_paths, workdir, filenames):
# def is_in(path, names):
# def decompress(self, source_paths, workdir, filenames):
# def excerpt(self, source_paths, workdir, conform):
# def _get_known_paths(source_paths, workdir, conform, known_types):
# def _make_csv_path(csv_path):
# def _sample_geojson_file(data_path):
# def _excerpt_csv_file(data_path, encoding, csvsplit):
# def elaborate_filenames(filename):
# def guess_source_encoding(datasource, layer):
# def find_source_path(source_definition, source_paths):
# def convert(self, source_definition, source_paths, workdir):
# def convert_regexp_replace(replace):
# def normalize_ogr_filename_case(source_path):
# def ogr_source_to_csv(source_definition, source_path, dest_path):
# def csv_source_to_csv(source_definition, source_path, dest_path):
# def geojson_source_to_csv(source_path, dest_path):
# def _transform_to_4326(srs):
# def row_extract_and_reproject(source_definition, source_row):
# def row_function(sd, row, key, fxn):
# def row_transform_and_convert(sd, row):
# def fxn_smash_case(fxn):
# def conform_smash_case(source_definition):
# def row_smash_case(sd, input):
# def row_merge(sd, row, key):
# def row_fxn_join(sd, row, key, fxn):
# def row_fxn_regexp(sd, row, key, fxn):
# def row_fxn_prefixed_number(sd, row, key, fxn):
# def row_fxn_postfixed_street(sd, row, key, fxn):
# def row_fxn_postfixed_unit(sd, row, key, fxn):
# def row_fxn_remove_prefix(sd, row, key, fxn):
# def row_fxn_remove_postfix(sd, row, key, fxn):
# def row_fxn_format(sd, row, key, fxn):
# def row_fxn_chain(sd, row, key, fxn):
# def row_fxn_first_non_empty(sd, row, key, fxn):
# def row_fxn_get_from_array_string(sd, row, key, fxn):
# def row_canonicalize_unit_and_number(sd, row):
# def _round_wgs84_to_7(n):
# def row_round_lat_lon(sd, row):
# def row_calculate_hash(cache_fingerprint, row):
# def row_convert_to_out(sd, row):
# def extract_to_source_csv(source_definition, source_path, extract_path):
# def transform_to_out_csv(source_definition, extract_path, dest_path):
# def conform_cli(source_definition, source_path, dest_path):
# def conform_license(license):
# def conform_attribution(license, attribution):
# def conform_sharealike(license):
# def check_source_tests(raw_source):
# class ConformResult:
# class DecompressionError(Exception):
# class DecompressionTask(object):
# class GuessDecompressTask(DecompressionTask):
# class ZipDecompressTask(DecompressionTask):
# class ExcerptDataTask(object):
# class ConvertToCsvTask(object):
, which may contain function names, class names, or code. Output only the next line. | 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 = { "ADDRESS": "123 MAPLE ST", "PREFIX": "" }
e = copy.deepcopy(d)
e.update({ "OA:street": "123 MAPLE ST" })
d = row_fxn_remove_prefix(c, d, "street", c["conform"]["street"])
self.assertEqual(e, d)
def test_row_fxn_remove_postfix(self):
"remove_postfix - field_to_remove is a postfix"
c = { "conform": {
"street": {
"function": "remove_postfix",
"field": "ADDRESS",
"field_to_remove": "POSTFIX"
}
} }
d = { "ADDRESS": "MAPLE ST UNIT 5", "POSTFIX": "UNIT 5" }
e = copy.deepcopy(d)
e.update({ "OA:street": "MAPLE ST" })
<|code_end|>
. Write the next line using the current file imports:
import os
import copy
import json
import csv
import re
import unittest
import tempfile
import shutil
from ..conform import (
GEOM_FIELDNAME, X_FIELDNAME, Y_FIELDNAME,
csv_source_to_csv, find_source_path, row_transform_and_convert,
row_fxn_regexp, row_smash_case, row_round_lat_lon, row_merge,
row_extract_and_reproject, row_convert_to_out, row_fxn_join, row_fxn_format,
row_fxn_prefixed_number, row_fxn_postfixed_street,
row_fxn_postfixed_unit,
row_fxn_remove_prefix, row_fxn_remove_postfix, row_fxn_chain,
row_fxn_first_non_empty,
row_fxn_get_from_array_string,
row_canonicalize_unit_and_number, conform_smash_case, conform_cli,
convert_regexp_replace, conform_license,
conform_attribution, conform_sharealike, normalize_ogr_filename_case,
OPENADDR_CSV_SCHEMA, is_in, geojson_source_to_csv, check_source_tests
)
and context from other files:
# Path: openaddr/conform.py
# import logging; _L = logging.getLogger('openaddr.conform')
# OPENADDR_CSV_SCHEMA = ['LON', 'LAT', 'NUMBER', 'STREET', 'UNIT', 'CITY',
# 'DISTRICT', 'REGION', 'POSTCODE', 'ID', 'HASH']
# GEOM_FIELDNAME = 'OA:geom'
# X_FIELDNAME, Y_FIELDNAME = 'OA:x', 'OA:y'
# UNZIPPED_DIRNAME = 'unzipped'
# def gdal_error_handler(err_class, err_num, err_msg):
# def mkdirsp(path):
# def __init__(self, processed, sample, website, license, geometry_type,
# address_count, path, elapsed, sharealike_flag,
# attribution_flag, attribution_name):
# def empty():
# def todict(self):
# def from_format_string(clz, format_string):
# def decompress(self, source_paths):
# def decompress(self, source_paths, workdir, filenames):
# def is_in(path, names):
# def decompress(self, source_paths, workdir, filenames):
# def excerpt(self, source_paths, workdir, conform):
# def _get_known_paths(source_paths, workdir, conform, known_types):
# def _make_csv_path(csv_path):
# def _sample_geojson_file(data_path):
# def _excerpt_csv_file(data_path, encoding, csvsplit):
# def elaborate_filenames(filename):
# def guess_source_encoding(datasource, layer):
# def find_source_path(source_definition, source_paths):
# def convert(self, source_definition, source_paths, workdir):
# def convert_regexp_replace(replace):
# def normalize_ogr_filename_case(source_path):
# def ogr_source_to_csv(source_definition, source_path, dest_path):
# def csv_source_to_csv(source_definition, source_path, dest_path):
# def geojson_source_to_csv(source_path, dest_path):
# def _transform_to_4326(srs):
# def row_extract_and_reproject(source_definition, source_row):
# def row_function(sd, row, key, fxn):
# def row_transform_and_convert(sd, row):
# def fxn_smash_case(fxn):
# def conform_smash_case(source_definition):
# def row_smash_case(sd, input):
# def row_merge(sd, row, key):
# def row_fxn_join(sd, row, key, fxn):
# def row_fxn_regexp(sd, row, key, fxn):
# def row_fxn_prefixed_number(sd, row, key, fxn):
# def row_fxn_postfixed_street(sd, row, key, fxn):
# def row_fxn_postfixed_unit(sd, row, key, fxn):
# def row_fxn_remove_prefix(sd, row, key, fxn):
# def row_fxn_remove_postfix(sd, row, key, fxn):
# def row_fxn_format(sd, row, key, fxn):
# def row_fxn_chain(sd, row, key, fxn):
# def row_fxn_first_non_empty(sd, row, key, fxn):
# def row_fxn_get_from_array_string(sd, row, key, fxn):
# def row_canonicalize_unit_and_number(sd, row):
# def _round_wgs84_to_7(n):
# def row_round_lat_lon(sd, row):
# def row_calculate_hash(cache_fingerprint, row):
# def row_convert_to_out(sd, row):
# def extract_to_source_csv(source_definition, source_path, extract_path):
# def transform_to_out_csv(source_definition, extract_path, dest_path):
# def conform_cli(source_definition, source_path, dest_path):
# def conform_license(license):
# def conform_attribution(license, attribution):
# def conform_sharealike(license):
# def check_source_tests(raw_source):
# class ConformResult:
# class DecompressionError(Exception):
# class DecompressionTask(object):
# class GuessDecompressTask(DecompressionTask):
# class ZipDecompressTask(DecompressionTask):
# class ExcerptDataTask(object):
# class ConvertToCsvTask(object):
, which may include functions, classes, or code. Output only the next line. | 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.assertEqual(d.get("OA:street", ""), "foo 1B bar")
def test_row_fxn_chain(self):
c = { "conform": {
"number": {
"function": "chain",
"functions": [
{
"function": "format",
"fields": ["a1", "a2", "a3"],
"format": "$1-$2-$3"
},
{
"function": "remove_postfix",
"field": "OA:number",
"field_to_remove": "b1"
}
]
}
} }
d = {"a1": "12", "a2": "34", "a3": "56 UNIT 5", "b1": "UNIT 5"}
e = copy.deepcopy(d)
<|code_end|>
, generate the next line using the imports in this file:
import os
import copy
import json
import csv
import re
import unittest
import tempfile
import shutil
from ..conform import (
GEOM_FIELDNAME, X_FIELDNAME, Y_FIELDNAME,
csv_source_to_csv, find_source_path, row_transform_and_convert,
row_fxn_regexp, row_smash_case, row_round_lat_lon, row_merge,
row_extract_and_reproject, row_convert_to_out, row_fxn_join, row_fxn_format,
row_fxn_prefixed_number, row_fxn_postfixed_street,
row_fxn_postfixed_unit,
row_fxn_remove_prefix, row_fxn_remove_postfix, row_fxn_chain,
row_fxn_first_non_empty,
row_fxn_get_from_array_string,
row_canonicalize_unit_and_number, conform_smash_case, conform_cli,
convert_regexp_replace, conform_license,
conform_attribution, conform_sharealike, normalize_ogr_filename_case,
OPENADDR_CSV_SCHEMA, is_in, geojson_source_to_csv, check_source_tests
)
and context (functions, classes, or occasionally code) from other files:
# Path: openaddr/conform.py
# import logging; _L = logging.getLogger('openaddr.conform')
# OPENADDR_CSV_SCHEMA = ['LON', 'LAT', 'NUMBER', 'STREET', 'UNIT', 'CITY',
# 'DISTRICT', 'REGION', 'POSTCODE', 'ID', 'HASH']
# GEOM_FIELDNAME = 'OA:geom'
# X_FIELDNAME, Y_FIELDNAME = 'OA:x', 'OA:y'
# UNZIPPED_DIRNAME = 'unzipped'
# def gdal_error_handler(err_class, err_num, err_msg):
# def mkdirsp(path):
# def __init__(self, processed, sample, website, license, geometry_type,
# address_count, path, elapsed, sharealike_flag,
# attribution_flag, attribution_name):
# def empty():
# def todict(self):
# def from_format_string(clz, format_string):
# def decompress(self, source_paths):
# def decompress(self, source_paths, workdir, filenames):
# def is_in(path, names):
# def decompress(self, source_paths, workdir, filenames):
# def excerpt(self, source_paths, workdir, conform):
# def _get_known_paths(source_paths, workdir, conform, known_types):
# def _make_csv_path(csv_path):
# def _sample_geojson_file(data_path):
# def _excerpt_csv_file(data_path, encoding, csvsplit):
# def elaborate_filenames(filename):
# def guess_source_encoding(datasource, layer):
# def find_source_path(source_definition, source_paths):
# def convert(self, source_definition, source_paths, workdir):
# def convert_regexp_replace(replace):
# def normalize_ogr_filename_case(source_path):
# def ogr_source_to_csv(source_definition, source_path, dest_path):
# def csv_source_to_csv(source_definition, source_path, dest_path):
# def geojson_source_to_csv(source_path, dest_path):
# def _transform_to_4326(srs):
# def row_extract_and_reproject(source_definition, source_row):
# def row_function(sd, row, key, fxn):
# def row_transform_and_convert(sd, row):
# def fxn_smash_case(fxn):
# def conform_smash_case(source_definition):
# def row_smash_case(sd, input):
# def row_merge(sd, row, key):
# def row_fxn_join(sd, row, key, fxn):
# def row_fxn_regexp(sd, row, key, fxn):
# def row_fxn_prefixed_number(sd, row, key, fxn):
# def row_fxn_postfixed_street(sd, row, key, fxn):
# def row_fxn_postfixed_unit(sd, row, key, fxn):
# def row_fxn_remove_prefix(sd, row, key, fxn):
# def row_fxn_remove_postfix(sd, row, key, fxn):
# def row_fxn_format(sd, row, key, fxn):
# def row_fxn_chain(sd, row, key, fxn):
# def row_fxn_first_non_empty(sd, row, key, fxn):
# def row_fxn_get_from_array_string(sd, row, key, fxn):
# def row_canonicalize_unit_and_number(sd, row):
# def _round_wgs84_to_7(n):
# def row_round_lat_lon(sd, row):
# def row_calculate_hash(cache_fingerprint, row):
# def row_convert_to_out(sd, row):
# def extract_to_source_csv(source_definition, source_path, extract_path):
# def transform_to_out_csv(source_definition, extract_path, dest_path):
# def conform_cli(source_definition, source_path, dest_path):
# def conform_license(license):
# def conform_attribution(license, attribution):
# def conform_sharealike(license):
# def check_source_tests(raw_source):
# class ConformResult:
# class DecompressionError(Exception):
# class DecompressionTask(object):
# class GuessDecompressTask(DecompressionTask):
# class ZipDecompressTask(DecompressionTask):
# class ExcerptDataTask(object):
# class ConvertToCsvTask(object):
. Output only the next line. | 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",
"field": "ADDRESS",
"field_to_remove": "POSTFIX"
}
} }
d = { "ADDRESS": "123 MAPLE ST", "POSTFIX": "" }
e = copy.deepcopy(d)
e.update({ "OA:street": "123 MAPLE ST" })
d = row_fxn_remove_postfix(c, d, "street", c["conform"]["street"])
self.assertEqual(e, d)
def test_row_first_non_empty(self):
"first_non_empty - fields array is empty"
c = { "conform": {
"street": {
"function": "first_non_empty",
"fields": []
}
} }
d = { }
e = copy.deepcopy(d)
e.update({ })
<|code_end|>
, generate the next line using the imports in this file:
import os
import copy
import json
import csv
import re
import unittest
import tempfile
import shutil
from ..conform import (
GEOM_FIELDNAME, X_FIELDNAME, Y_FIELDNAME,
csv_source_to_csv, find_source_path, row_transform_and_convert,
row_fxn_regexp, row_smash_case, row_round_lat_lon, row_merge,
row_extract_and_reproject, row_convert_to_out, row_fxn_join, row_fxn_format,
row_fxn_prefixed_number, row_fxn_postfixed_street,
row_fxn_postfixed_unit,
row_fxn_remove_prefix, row_fxn_remove_postfix, row_fxn_chain,
row_fxn_first_non_empty,
row_fxn_get_from_array_string,
row_canonicalize_unit_and_number, conform_smash_case, conform_cli,
convert_regexp_replace, conform_license,
conform_attribution, conform_sharealike, normalize_ogr_filename_case,
OPENADDR_CSV_SCHEMA, is_in, geojson_source_to_csv, check_source_tests
)
and context (functions, classes, or occasionally code) from other files:
# Path: openaddr/conform.py
# import logging; _L = logging.getLogger('openaddr.conform')
# OPENADDR_CSV_SCHEMA = ['LON', 'LAT', 'NUMBER', 'STREET', 'UNIT', 'CITY',
# 'DISTRICT', 'REGION', 'POSTCODE', 'ID', 'HASH']
# GEOM_FIELDNAME = 'OA:geom'
# X_FIELDNAME, Y_FIELDNAME = 'OA:x', 'OA:y'
# UNZIPPED_DIRNAME = 'unzipped'
# def gdal_error_handler(err_class, err_num, err_msg):
# def mkdirsp(path):
# def __init__(self, processed, sample, website, license, geometry_type,
# address_count, path, elapsed, sharealike_flag,
# attribution_flag, attribution_name):
# def empty():
# def todict(self):
# def from_format_string(clz, format_string):
# def decompress(self, source_paths):
# def decompress(self, source_paths, workdir, filenames):
# def is_in(path, names):
# def decompress(self, source_paths, workdir, filenames):
# def excerpt(self, source_paths, workdir, conform):
# def _get_known_paths(source_paths, workdir, conform, known_types):
# def _make_csv_path(csv_path):
# def _sample_geojson_file(data_path):
# def _excerpt_csv_file(data_path, encoding, csvsplit):
# def elaborate_filenames(filename):
# def guess_source_encoding(datasource, layer):
# def find_source_path(source_definition, source_paths):
# def convert(self, source_definition, source_paths, workdir):
# def convert_regexp_replace(replace):
# def normalize_ogr_filename_case(source_path):
# def ogr_source_to_csv(source_definition, source_path, dest_path):
# def csv_source_to_csv(source_definition, source_path, dest_path):
# def geojson_source_to_csv(source_path, dest_path):
# def _transform_to_4326(srs):
# def row_extract_and_reproject(source_definition, source_row):
# def row_function(sd, row, key, fxn):
# def row_transform_and_convert(sd, row):
# def fxn_smash_case(fxn):
# def conform_smash_case(source_definition):
# def row_smash_case(sd, input):
# def row_merge(sd, row, key):
# def row_fxn_join(sd, row, key, fxn):
# def row_fxn_regexp(sd, row, key, fxn):
# def row_fxn_prefixed_number(sd, row, key, fxn):
# def row_fxn_postfixed_street(sd, row, key, fxn):
# def row_fxn_postfixed_unit(sd, row, key, fxn):
# def row_fxn_remove_prefix(sd, row, key, fxn):
# def row_fxn_remove_postfix(sd, row, key, fxn):
# def row_fxn_format(sd, row, key, fxn):
# def row_fxn_chain(sd, row, key, fxn):
# def row_fxn_first_non_empty(sd, row, key, fxn):
# def row_fxn_get_from_array_string(sd, row, key, fxn):
# def row_canonicalize_unit_and_number(sd, row):
# def _round_wgs84_to_7(n):
# def row_round_lat_lon(sd, row):
# def row_calculate_hash(cache_fingerprint, row):
# def row_convert_to_out(sd, row):
# def extract_to_source_csv(source_definition, source_path, extract_path):
# def transform_to_out_csv(source_definition, extract_path, dest_path):
# def conform_cli(source_definition, source_path, dest_path):
# def conform_license(license):
# def conform_attribution(license, attribution):
# def conform_sharealike(license):
# def check_source_tests(raw_source):
# class ConformResult:
# class DecompressionError(Exception):
# class DecompressionTask(object):
# class GuessDecompressTask(DecompressionTask):
# class ZipDecompressTask(DecompressionTask):
# class ExcerptDataTask(object):
# class ConvertToCsvTask(object):
. Output only the next line. | 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", "FIELD2"]
}
} }
d = { "FIELD1": " \t ", "FIELD2": " \t " }
e = copy.deepcopy(d)
e.update({ })
d = row_fxn_first_non_empty(c, d, "street", c["conform"]["street"])
self.assertEqual(e, d)
def test_row_fxn_get_from_array_string(self):
"Parse array value from GDAL that arrives as an encoded string"
c = {
"conform": {
"region": {
"function": "get",
"field": "jednostkaAdministracyjna",
"index": 1
}
}}
d = {"jednostkaAdministracyjna": "['Polska', 'kujawsko-pomorskie','brodnicki', 'Bartnicza']" }
e = copy.deepcopy(d)
e.update({"OA:region": "kujawsko-pomorskie"})
<|code_end|>
, predict the next line using imports from the current file:
import os
import copy
import json
import csv
import re
import unittest
import tempfile
import shutil
from ..conform import (
GEOM_FIELDNAME, X_FIELDNAME, Y_FIELDNAME,
csv_source_to_csv, find_source_path, row_transform_and_convert,
row_fxn_regexp, row_smash_case, row_round_lat_lon, row_merge,
row_extract_and_reproject, row_convert_to_out, row_fxn_join, row_fxn_format,
row_fxn_prefixed_number, row_fxn_postfixed_street,
row_fxn_postfixed_unit,
row_fxn_remove_prefix, row_fxn_remove_postfix, row_fxn_chain,
row_fxn_first_non_empty,
row_fxn_get_from_array_string,
row_canonicalize_unit_and_number, conform_smash_case, conform_cli,
convert_regexp_replace, conform_license,
conform_attribution, conform_sharealike, normalize_ogr_filename_case,
OPENADDR_CSV_SCHEMA, is_in, geojson_source_to_csv, check_source_tests
)
and context including class names, function names, and sometimes code from other files:
# Path: openaddr/conform.py
# import logging; _L = logging.getLogger('openaddr.conform')
# OPENADDR_CSV_SCHEMA = ['LON', 'LAT', 'NUMBER', 'STREET', 'UNIT', 'CITY',
# 'DISTRICT', 'REGION', 'POSTCODE', 'ID', 'HASH']
# GEOM_FIELDNAME = 'OA:geom'
# X_FIELDNAME, Y_FIELDNAME = 'OA:x', 'OA:y'
# UNZIPPED_DIRNAME = 'unzipped'
# def gdal_error_handler(err_class, err_num, err_msg):
# def mkdirsp(path):
# def __init__(self, processed, sample, website, license, geometry_type,
# address_count, path, elapsed, sharealike_flag,
# attribution_flag, attribution_name):
# def empty():
# def todict(self):
# def from_format_string(clz, format_string):
# def decompress(self, source_paths):
# def decompress(self, source_paths, workdir, filenames):
# def is_in(path, names):
# def decompress(self, source_paths, workdir, filenames):
# def excerpt(self, source_paths, workdir, conform):
# def _get_known_paths(source_paths, workdir, conform, known_types):
# def _make_csv_path(csv_path):
# def _sample_geojson_file(data_path):
# def _excerpt_csv_file(data_path, encoding, csvsplit):
# def elaborate_filenames(filename):
# def guess_source_encoding(datasource, layer):
# def find_source_path(source_definition, source_paths):
# def convert(self, source_definition, source_paths, workdir):
# def convert_regexp_replace(replace):
# def normalize_ogr_filename_case(source_path):
# def ogr_source_to_csv(source_definition, source_path, dest_path):
# def csv_source_to_csv(source_definition, source_path, dest_path):
# def geojson_source_to_csv(source_path, dest_path):
# def _transform_to_4326(srs):
# def row_extract_and_reproject(source_definition, source_row):
# def row_function(sd, row, key, fxn):
# def row_transform_and_convert(sd, row):
# def fxn_smash_case(fxn):
# def conform_smash_case(source_definition):
# def row_smash_case(sd, input):
# def row_merge(sd, row, key):
# def row_fxn_join(sd, row, key, fxn):
# def row_fxn_regexp(sd, row, key, fxn):
# def row_fxn_prefixed_number(sd, row, key, fxn):
# def row_fxn_postfixed_street(sd, row, key, fxn):
# def row_fxn_postfixed_unit(sd, row, key, fxn):
# def row_fxn_remove_prefix(sd, row, key, fxn):
# def row_fxn_remove_postfix(sd, row, key, fxn):
# def row_fxn_format(sd, row, key, fxn):
# def row_fxn_chain(sd, row, key, fxn):
# def row_fxn_first_non_empty(sd, row, key, fxn):
# def row_fxn_get_from_array_string(sd, row, key, fxn):
# def row_canonicalize_unit_and_number(sd, row):
# def _round_wgs84_to_7(n):
# def row_round_lat_lon(sd, row):
# def row_calculate_hash(cache_fingerprint, row):
# def row_convert_to_out(sd, row):
# def extract_to_source_csv(source_definition, source_path, extract_path):
# def transform_to_out_csv(source_definition, extract_path, dest_path):
# def conform_cli(source_definition, source_path, dest_path):
# def conform_license(license):
# def conform_attribution(license, attribution):
# def conform_sharealike(license):
# def check_source_tests(raw_source):
# class ConformResult:
# class DecompressionError(Exception):
# class DecompressionTask(object):
# class GuessDecompressTask(DecompressionTask):
# class ZipDecompressTask(DecompressionTask):
# class ExcerptDataTask(object):
# class ConvertToCsvTask(object):
. Output only the next line. | 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": "mixed"})
self.assertEqual({"upper": "foo", "lower": "bar", "mixed": "mixed"}, r)
def test_conform_smash_case(self):
d = { "conform": { "street": [ "U", "l", "MiXeD" ], "number": "U", "lat": "Y", "lon": "x",
"city": { "function": "join", "fields": ["ThIs","FiELd"], "separator": "-" },
"district": { "function": "regexp", "field": "ThaT", "pattern": ""},
"postcode": { "function": "join", "fields": ["MiXeD", "UPPER"], "separator": "-" } } }
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import copy
import json
import csv
import re
import unittest
import tempfile
import shutil
from ..conform import (
GEOM_FIELDNAME, X_FIELDNAME, Y_FIELDNAME,
csv_source_to_csv, find_source_path, row_transform_and_convert,
row_fxn_regexp, row_smash_case, row_round_lat_lon, row_merge,
row_extract_and_reproject, row_convert_to_out, row_fxn_join, row_fxn_format,
row_fxn_prefixed_number, row_fxn_postfixed_street,
row_fxn_postfixed_unit,
row_fxn_remove_prefix, row_fxn_remove_postfix, row_fxn_chain,
row_fxn_first_non_empty,
row_fxn_get_from_array_string,
row_canonicalize_unit_and_number, conform_smash_case, conform_cli,
convert_regexp_replace, conform_license,
conform_attribution, conform_sharealike, normalize_ogr_filename_case,
OPENADDR_CSV_SCHEMA, is_in, geojson_source_to_csv, check_source_tests
)
and context:
# Path: openaddr/conform.py
# import logging; _L = logging.getLogger('openaddr.conform')
# OPENADDR_CSV_SCHEMA = ['LON', 'LAT', 'NUMBER', 'STREET', 'UNIT', 'CITY',
# 'DISTRICT', 'REGION', 'POSTCODE', 'ID', 'HASH']
# GEOM_FIELDNAME = 'OA:geom'
# X_FIELDNAME, Y_FIELDNAME = 'OA:x', 'OA:y'
# UNZIPPED_DIRNAME = 'unzipped'
# def gdal_error_handler(err_class, err_num, err_msg):
# def mkdirsp(path):
# def __init__(self, processed, sample, website, license, geometry_type,
# address_count, path, elapsed, sharealike_flag,
# attribution_flag, attribution_name):
# def empty():
# def todict(self):
# def from_format_string(clz, format_string):
# def decompress(self, source_paths):
# def decompress(self, source_paths, workdir, filenames):
# def is_in(path, names):
# def decompress(self, source_paths, workdir, filenames):
# def excerpt(self, source_paths, workdir, conform):
# def _get_known_paths(source_paths, workdir, conform, known_types):
# def _make_csv_path(csv_path):
# def _sample_geojson_file(data_path):
# def _excerpt_csv_file(data_path, encoding, csvsplit):
# def elaborate_filenames(filename):
# def guess_source_encoding(datasource, layer):
# def find_source_path(source_definition, source_paths):
# def convert(self, source_definition, source_paths, workdir):
# def convert_regexp_replace(replace):
# def normalize_ogr_filename_case(source_path):
# def ogr_source_to_csv(source_definition, source_path, dest_path):
# def csv_source_to_csv(source_definition, source_path, dest_path):
# def geojson_source_to_csv(source_path, dest_path):
# def _transform_to_4326(srs):
# def row_extract_and_reproject(source_definition, source_row):
# def row_function(sd, row, key, fxn):
# def row_transform_and_convert(sd, row):
# def fxn_smash_case(fxn):
# def conform_smash_case(source_definition):
# def row_smash_case(sd, input):
# def row_merge(sd, row, key):
# def row_fxn_join(sd, row, key, fxn):
# def row_fxn_regexp(sd, row, key, fxn):
# def row_fxn_prefixed_number(sd, row, key, fxn):
# def row_fxn_postfixed_street(sd, row, key, fxn):
# def row_fxn_postfixed_unit(sd, row, key, fxn):
# def row_fxn_remove_prefix(sd, row, key, fxn):
# def row_fxn_remove_postfix(sd, row, key, fxn):
# def row_fxn_format(sd, row, key, fxn):
# def row_fxn_chain(sd, row, key, fxn):
# def row_fxn_first_non_empty(sd, row, key, fxn):
# def row_fxn_get_from_array_string(sd, row, key, fxn):
# def row_canonicalize_unit_and_number(sd, row):
# def _round_wgs84_to_7(n):
# def row_round_lat_lon(sd, row):
# def row_calculate_hash(cache_fingerprint, row):
# def row_convert_to_out(sd, row):
# def extract_to_source_csv(source_definition, source_path, extract_path):
# def transform_to_out_csv(source_definition, extract_path, dest_path):
# def conform_cli(source_definition, source_path, dest_path):
# def conform_license(license):
# def conform_attribution(license, attribution):
# def conform_sharealike(license):
# def check_source_tests(raw_source):
# class ConformResult:
# class DecompressionError(Exception):
# class DecompressionTask(object):
# class GuessDecompressTask(DecompressionTask):
# class ZipDecompressTask(DecompressionTask):
# class ExcerptDataTask(object):
# class ConvertToCsvTask(object):
which might include code, classes, or functions. Output only the next line. | 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 django.conf import settings
from django.template.response import TemplateResponse
from django.contrib.auth.decorators import login_required
from zircon.datastores.influx import InfluxDatastore
import json
and context from other files:
# Path: zircon/datastores/influx.py
# class InfluxDatastore(BaseDatastore):
#
# # Try default database configuration if none provided
# DEFAULT_DB_INFO = {
# 'host': 'localhost',
# 'port': 8086,
# 'username': 'root',
# 'password': 'root'
# }
#
# DEFAULT_DB_NAME = 'zircon'
#
# def __init__(self, db_info=None, db_name=None):
#
# self.db_info = db_info or self.DEFAULT_DB_INFO
# self.db_name = db_name or self.DEFAULT_DB_NAME
#
# self.db = influxdb.InfluxDBClient(
# host=self.db_info['host'],
# port=self.db_info['port'],
# username=self.db_info['username'],
# password=self.db_info['password']
# )
#
# if self.db_name not in self.list_databases():
# self.create_database(self.db_name)
#
# self.switch_database(self.db_name)
#
# print('Using InfluxDB datastore with db name {}'.format(self.db_name))
#
# def create_database(self, db_name):
# self.db.create_database(db_name)
#
# def delete_database(self, db_name):
# self.db.delete_database(db_name)
#
# def switch_database(self, db_name):
# self.db_name = db_name
# self.db.switch_db(db_name)
# return True
#
# def get_database_name(self):
# return self.db_name
#
# def list_databases(self):
# return [d['name'] for d in self.db.get_database_list()]
#
# def list_signals(self):
#
# r = self.db.query('list series')
#
# try:
# return [s[1] for s in r[0]['points']]
# except(IndexError, KeyError):
# return None
#
# def delete_signal(self, signal_name):
# self.db.delete_series(signal_name)
#
# def write_points(self, data):
#
# return self.db.write_points_with_precision(data, time_precision='u')
#
# def query(self, query):
#
# print('[QUERY] {}'.format(query))
# return self.db.query(query, time_precision='u')
#
# def insert(self, data):
#
# # print('[INSERTED] {}'.format(data))
#
# insert_data = [{
# 'name': signal_name,
# 'columns': ['time', 'val'],
# 'points': points
# } for signal_name, points in data.items()]
#
# now = time.time()
#
# result = self.write_points(insert_data)
#
# if not result:
# return False
#
# for signal in data:
# print('[{}] Saved {} points'.format(
# signal,
# len(data[signal])
# ))
#
# print('Saved total {} points in {} ms, success: {}'.format(
# sum([len(s) for s in data.values()]),
# (time.time() - now) * 1000,
# result
# ))
#
# return True
#
# def get_last_points(self, signals, num=1):
#
# all_signals = self.list_signals()
# query_signals = [s for s in signals if s in all_signals]
#
# if not query_signals:
# return {}
#
# query_str = 'select * from {} limit {}'.format(
# ', '.join(['{}'.format(s) for s in query_signals]),
# num
# )
#
# r = self.query(query_str)
#
# try:
# return {r_s['name']: [[p[0], p[2]]
# for p in r_s['points']] for r_s in r}
# except Exception, e:
# print(e)
# return None
#
# def get_timeseries(self, signals, t0, t1,
# dt=100000, aggregate='last', limit=1000):
#
# all_signals = self.list_signals()
# query_signals = [s for s in signals if s in all_signals]
#
# if not query_signals:
# return {}
#
# q = 'select {}(val) from {} where time > {}u and time < {}u ' \
# 'group by time({}u) limit {}'.format(
# aggregate,
# ', '.join(query_signals),
# int(t0),
# int(t1),
# int(dt),
# int(limit)
# )
#
# r = self.query(q)
#
# try:
# return {r_s['name']: r_s['points'] for r_s in r}
# except Exception, e:
# print(e)
# return None
, which may contain function names, class names, or code. Output only the next line. | 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*x/2.8) + gauss(0, 0.3),
'IMU_X_FILTERED': lambda x: 1.0 * sin(2*pi*(x/3.0 + 1)),
'IMU_Y_FILTERED': lambda x: 1.5 * sin(2*pi*x/2.5),
'IMU_Z_FILTERED': lambda x: 1.3 * sin(2*pi*x/2.8),
},
dt=0.01,
),
transformers=[
Splitter(),
TimedCombiner(dt=0.1),
Pickler(),
Compressor()
],
<|code_end|>
. Use current file imports:
(from zircon.transceivers.dummy_multiple import DummyMultipleTransceiver
from zircon.publishers.zeromq import ZMQPublisher
from zircon.reporters.base import Reporter
from zircon.transformers.common import *
from math import sin, pi
from random import gauss)
and context including class names, function names, or small code snippets from other files:
# Path: zircon/transceivers/dummy_multiple.py
# class DummyMultipleTransceiver(BaseTransceiver):
#
# def __init__(self, signals=None, dt=0.1):
#
# self.dt = dt
# self.t = 0
# self.t_real = time.time()
#
# self.signals = signals
# if not self.signals:
# self.signals = {'sin': math.sin}
#
# self.time = time.time()
#
# def open(self):
# return True
#
# def close(self):
# return True
#
# def read(self):
#
# now = time.time()
# dt_real = now - self.time - self.dt
# to_wait = max(min(self.dt - dt_real, self.dt), 0)
#
# # Update sample time
# self.t += now - self.time
#
# self.time = now
# time.sleep(to_wait)
#
# timestamp = int(now * 1e6)
# data = [(timestamp, name, func(self.t)) for name, func in self.signals.items()]
#
# return data
#
# def write(self, data):
# print('[WRITE] {}'.format(data))
# return True
#
# Path: zircon/publishers/zeromq.py
# class ZMQPublisher(BasePublisher):
#
# def __init__(self, host='*', port=8811, zmq_type=zmq.PUB):
#
# self.host = host
# self.port = port
# self.zmq_type = zmq_type
# self.URI = 'tcp://{}:{}'.format(self.host, self.port)
#
# self.context = zmq.Context()
# self.sock = self.context.socket(self.zmq_type)
#
# self.count = 0
#
# def open(self):
# self.sock.bind(self.URI)
# return True
#
# def close(self):
# self.sock.close()
# return True
#
# def send(self, msg):
#
# try:
# self.sock.send(msg)
# self.count += 1
# print('[SENT] {}'.format(self.count))
# except TypeError:
# print('[ERROR] Message fed to Publisher must be serialized!')
# return False
#
# return True
#
# Path: zircon/reporters/base.py
# class Reporter():
# """ A Reporter continuously reads data from a Transceiver, feeds it through
# a row of Transformers, and broadcasts the result using a Publisher.
#
# 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(),
# transformers=[MyDecoder(), MyCompressor(), ...],
# publisher=MyPublisher()
# )
#
# A Reporter can be run as its own process::
#
# reporter.run()
#
# Or stepped through by an external engine::
#
# reporter.open()
# while not done:
# reporter.step()
# """
#
# def __init__(self, transceiver, transformers=None, publisher=None):
#
# self.transceiver = transceiver
#
# if transformers:
# self.transformers = transformers
# else:
# self.transformers = [Pickler()]
#
# if publisher:
# self.publisher = publisher
# else:
# self.publisher = ZMQPublisher()
#
# for i in range(len(self.transformers) - 1):
# self.transformers[i].set_callback(self.transformers[i+1].push)
#
# self.transformers[-1].set_callback(self.publisher.send)
#
# def open(self):
# """ Initialize the Transceiver and Publisher.
# """
#
# success = self.transceiver.open()
# if not success:
# return False
#
# success = self.publisher.open()
# if not success:
# return False
#
# return True
#
# def step(self):
# """ Read data and feed it into the first Transformer.
# """
#
# raw_data = self.transceiver.read()
#
# if raw_data is not None:
# self.transformers[0].push(raw_data)
#
# def run(self):
# """ Initialize components and start broadcasting.
# """
#
# success = self.open()
# if not success:
# print('Failed to initialize!')
# return
#
# while True:
# self.step()
. Output only the next line. | 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_name', None)
<|code_end|>
. Use current file imports:
import time
from django.conf import settings
from socketio.namespace import BaseNamespace
from socketio.mixins import RoomsMixin, BroadcastMixin
from socketio.sdjango import namespace
from zircon.datastores.influx import InfluxDatastore
and context (classes, functions, or code) from other files:
# Path: zircon/datastores/influx.py
# class InfluxDatastore(BaseDatastore):
#
# # Try default database configuration if none provided
# DEFAULT_DB_INFO = {
# 'host': 'localhost',
# 'port': 8086,
# 'username': 'root',
# 'password': 'root'
# }
#
# DEFAULT_DB_NAME = 'zircon'
#
# def __init__(self, db_info=None, db_name=None):
#
# self.db_info = db_info or self.DEFAULT_DB_INFO
# self.db_name = db_name or self.DEFAULT_DB_NAME
#
# self.db = influxdb.InfluxDBClient(
# host=self.db_info['host'],
# port=self.db_info['port'],
# username=self.db_info['username'],
# password=self.db_info['password']
# )
#
# if self.db_name not in self.list_databases():
# self.create_database(self.db_name)
#
# self.switch_database(self.db_name)
#
# print('Using InfluxDB datastore with db name {}'.format(self.db_name))
#
# def create_database(self, db_name):
# self.db.create_database(db_name)
#
# def delete_database(self, db_name):
# self.db.delete_database(db_name)
#
# def switch_database(self, db_name):
# self.db_name = db_name
# self.db.switch_db(db_name)
# return True
#
# def get_database_name(self):
# return self.db_name
#
# def list_databases(self):
# return [d['name'] for d in self.db.get_database_list()]
#
# def list_signals(self):
#
# r = self.db.query('list series')
#
# try:
# return [s[1] for s in r[0]['points']]
# except(IndexError, KeyError):
# return None
#
# def delete_signal(self, signal_name):
# self.db.delete_series(signal_name)
#
# def write_points(self, data):
#
# return self.db.write_points_with_precision(data, time_precision='u')
#
# def query(self, query):
#
# print('[QUERY] {}'.format(query))
# return self.db.query(query, time_precision='u')
#
# def insert(self, data):
#
# # print('[INSERTED] {}'.format(data))
#
# insert_data = [{
# 'name': signal_name,
# 'columns': ['time', 'val'],
# 'points': points
# } for signal_name, points in data.items()]
#
# now = time.time()
#
# result = self.write_points(insert_data)
#
# if not result:
# return False
#
# for signal in data:
# print('[{}] Saved {} points'.format(
# signal,
# len(data[signal])
# ))
#
# print('Saved total {} points in {} ms, success: {}'.format(
# sum([len(s) for s in data.values()]),
# (time.time() - now) * 1000,
# result
# ))
#
# return True
#
# def get_last_points(self, signals, num=1):
#
# all_signals = self.list_signals()
# query_signals = [s for s in signals if s in all_signals]
#
# if not query_signals:
# return {}
#
# query_str = 'select * from {} limit {}'.format(
# ', '.join(['{}'.format(s) for s in query_signals]),
# num
# )
#
# r = self.query(query_str)
#
# try:
# return {r_s['name']: [[p[0], p[2]]
# for p in r_s['points']] for r_s in r}
# except Exception, e:
# print(e)
# return None
#
# def get_timeseries(self, signals, t0, t1,
# dt=100000, aggregate='last', limit=1000):
#
# all_signals = self.list_signals()
# query_signals = [s for s in signals if s in all_signals]
#
# if not query_signals:
# return {}
#
# q = 'select {}(val) from {} where time > {}u and time < {}u ' \
# 'group by time({}u) limit {}'.format(
# aggregate,
# ', '.join(query_signals),
# int(t0),
# int(t1),
# int(dt),
# int(limit)
# )
#
# r = self.query(q)
#
# try:
# return {r_s['name']: r_s['points'] for r_s in r}
# except Exception, e:
# print(e)
# return None
. Output only the next line. | 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.zeromq import ZMQPublisher
from zircon.reporters.base import Reporter
from zircon.transformers.common import *
from math import sin, pi
and context from other files:
# Path: zircon/transceivers/dummy.py
# class DummyTransceiver(BaseTransceiver):
#
# def __init__(self, signal_name='dummy', data_gen=lambda t: sin(t), dt=0.1):
#
# self.dt = dt
# self.signal_name = signal_name
# self.data_gen = data_gen
#
# self.t = 0
# self.last = time.time()
#
# def open(self):
# return True
#
# def close(self):
# return True
#
# def pause(self):
#
# now = time.time()
# dt_real = now - self.last - self.dt
# self.t += now - self.last
# self.last = now
#
# to_wait = max(min(self.dt - dt_real, self.dt), 0)
# time.sleep(to_wait)
#
# def read(self):
#
# self.pause()
#
# timestamp = int(time.time() * 1e6)
# val = self.data_gen(self.t)
# return timestamp, self.signal_name, val
#
# def write(self, data):
# print('[WRITE] {}'.format(data))
# return True
#
# Path: zircon/publishers/zeromq.py
# class ZMQPublisher(BasePublisher):
#
# def __init__(self, host='*', port=8811, zmq_type=zmq.PUB):
#
# self.host = host
# self.port = port
# self.zmq_type = zmq_type
# self.URI = 'tcp://{}:{}'.format(self.host, self.port)
#
# self.context = zmq.Context()
# self.sock = self.context.socket(self.zmq_type)
#
# self.count = 0
#
# def open(self):
# self.sock.bind(self.URI)
# return True
#
# def close(self):
# self.sock.close()
# return True
#
# def send(self, msg):
#
# try:
# self.sock.send(msg)
# self.count += 1
# print('[SENT] {}'.format(self.count))
# except TypeError:
# print('[ERROR] Message fed to Publisher must be serialized!')
# return False
#
# return True
#
# Path: zircon/reporters/base.py
# class Reporter():
# """ A Reporter continuously reads data from a Transceiver, feeds it through
# a row of Transformers, and broadcasts the result using a Publisher.
#
# 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(),
# transformers=[MyDecoder(), MyCompressor(), ...],
# publisher=MyPublisher()
# )
#
# A Reporter can be run as its own process::
#
# reporter.run()
#
# Or stepped through by an external engine::
#
# reporter.open()
# while not done:
# reporter.step()
# """
#
# def __init__(self, transceiver, transformers=None, publisher=None):
#
# self.transceiver = transceiver
#
# if transformers:
# self.transformers = transformers
# else:
# self.transformers = [Pickler()]
#
# if publisher:
# self.publisher = publisher
# else:
# self.publisher = ZMQPublisher()
#
# for i in range(len(self.transformers) - 1):
# self.transformers[i].set_callback(self.transformers[i+1].push)
#
# self.transformers[-1].set_callback(self.publisher.send)
#
# def open(self):
# """ Initialize the Transceiver and Publisher.
# """
#
# success = self.transceiver.open()
# if not success:
# return False
#
# success = self.publisher.open()
# if not success:
# return False
#
# return True
#
# def step(self):
# """ Read data and feed it into the first Transformer.
# """
#
# raw_data = self.transceiver.read()
#
# if raw_data is not None:
# self.transformers[0].push(raw_data)
#
# def run(self):
# """ Initialize components and start broadcasting.
# """
#
# success = self.open()
# if not success:
# print('Failed to initialize!')
# return
#
# while True:
# self.step()
, which may contain function names, class names, or code. Output only the next line. | 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
),
transformers=[
TimedCombiner(dt=0.1),
Pickler(),
Compressor()
],
<|code_end|>
with the help of current file imports:
from zircon.transceivers.dummy import DummyTransceiver
from zircon.publishers.zeromq import ZMQPublisher
from zircon.reporters.base import Reporter
from zircon.transformers.common import *
from math import sin, pi
and context from other files:
# Path: zircon/transceivers/dummy.py
# class DummyTransceiver(BaseTransceiver):
#
# def __init__(self, signal_name='dummy', data_gen=lambda t: sin(t), dt=0.1):
#
# self.dt = dt
# self.signal_name = signal_name
# self.data_gen = data_gen
#
# self.t = 0
# self.last = time.time()
#
# def open(self):
# return True
#
# def close(self):
# return True
#
# def pause(self):
#
# now = time.time()
# dt_real = now - self.last - self.dt
# self.t += now - self.last
# self.last = now
#
# to_wait = max(min(self.dt - dt_real, self.dt), 0)
# time.sleep(to_wait)
#
# def read(self):
#
# self.pause()
#
# timestamp = int(time.time() * 1e6)
# val = self.data_gen(self.t)
# return timestamp, self.signal_name, val
#
# def write(self, data):
# print('[WRITE] {}'.format(data))
# return True
#
# Path: zircon/publishers/zeromq.py
# class ZMQPublisher(BasePublisher):
#
# def __init__(self, host='*', port=8811, zmq_type=zmq.PUB):
#
# self.host = host
# self.port = port
# self.zmq_type = zmq_type
# self.URI = 'tcp://{}:{}'.format(self.host, self.port)
#
# self.context = zmq.Context()
# self.sock = self.context.socket(self.zmq_type)
#
# self.count = 0
#
# def open(self):
# self.sock.bind(self.URI)
# return True
#
# def close(self):
# self.sock.close()
# return True
#
# def send(self, msg):
#
# try:
# self.sock.send(msg)
# self.count += 1
# print('[SENT] {}'.format(self.count))
# except TypeError:
# print('[ERROR] Message fed to Publisher must be serialized!')
# return False
#
# return True
#
# Path: zircon/reporters/base.py
# class Reporter():
# """ A Reporter continuously reads data from a Transceiver, feeds it through
# a row of Transformers, and broadcasts the result using a Publisher.
#
# 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(),
# transformers=[MyDecoder(), MyCompressor(), ...],
# publisher=MyPublisher()
# )
#
# A Reporter can be run as its own process::
#
# reporter.run()
#
# Or stepped through by an external engine::
#
# reporter.open()
# while not done:
# reporter.step()
# """
#
# def __init__(self, transceiver, transformers=None, publisher=None):
#
# self.transceiver = transceiver
#
# if transformers:
# self.transformers = transformers
# else:
# self.transformers = [Pickler()]
#
# if publisher:
# self.publisher = publisher
# else:
# self.publisher = ZMQPublisher()
#
# for i in range(len(self.transformers) - 1):
# self.transformers[i].set_callback(self.transformers[i+1].push)
#
# self.transformers[-1].set_callback(self.publisher.send)
#
# def open(self):
# """ Initialize the Transceiver and Publisher.
# """
#
# success = self.transceiver.open()
# if not success:
# return False
#
# success = self.publisher.open()
# if not success:
# return False
#
# return True
#
# def step(self):
# """ Read data and feed it into the first Transformer.
# """
#
# raw_data = self.transceiver.read()
#
# if raw_data is not None:
# self.transformers[0].push(raw_data)
#
# def run(self):
# """ Initialize components and start broadcasting.
# """
#
# success = self.open()
# if not success:
# print('Failed to initialize!')
# return
#
# while True:
# self.step()
, which may contain function names, class names, or code. Output only the next line. | 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 ZMQPublisher
from zircon.reporters.base import Reporter
from zircon.transformers.common import *
from math import sin, pi
and context:
# Path: zircon/transceivers/dummy.py
# class DummyTransceiver(BaseTransceiver):
#
# def __init__(self, signal_name='dummy', data_gen=lambda t: sin(t), dt=0.1):
#
# self.dt = dt
# self.signal_name = signal_name
# self.data_gen = data_gen
#
# self.t = 0
# self.last = time.time()
#
# def open(self):
# return True
#
# def close(self):
# return True
#
# def pause(self):
#
# now = time.time()
# dt_real = now - self.last - self.dt
# self.t += now - self.last
# self.last = now
#
# to_wait = max(min(self.dt - dt_real, self.dt), 0)
# time.sleep(to_wait)
#
# def read(self):
#
# self.pause()
#
# timestamp = int(time.time() * 1e6)
# val = self.data_gen(self.t)
# return timestamp, self.signal_name, val
#
# def write(self, data):
# print('[WRITE] {}'.format(data))
# return True
#
# Path: zircon/publishers/zeromq.py
# class ZMQPublisher(BasePublisher):
#
# def __init__(self, host='*', port=8811, zmq_type=zmq.PUB):
#
# self.host = host
# self.port = port
# self.zmq_type = zmq_type
# self.URI = 'tcp://{}:{}'.format(self.host, self.port)
#
# self.context = zmq.Context()
# self.sock = self.context.socket(self.zmq_type)
#
# self.count = 0
#
# def open(self):
# self.sock.bind(self.URI)
# return True
#
# def close(self):
# self.sock.close()
# return True
#
# def send(self, msg):
#
# try:
# self.sock.send(msg)
# self.count += 1
# print('[SENT] {}'.format(self.count))
# except TypeError:
# print('[ERROR] Message fed to Publisher must be serialized!')
# return False
#
# return True
#
# Path: zircon/reporters/base.py
# class Reporter():
# """ A Reporter continuously reads data from a Transceiver, feeds it through
# a row of Transformers, and broadcasts the result using a Publisher.
#
# 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(),
# transformers=[MyDecoder(), MyCompressor(), ...],
# publisher=MyPublisher()
# )
#
# A Reporter can be run as its own process::
#
# reporter.run()
#
# Or stepped through by an external engine::
#
# reporter.open()
# while not done:
# reporter.step()
# """
#
# def __init__(self, transceiver, transformers=None, publisher=None):
#
# self.transceiver = transceiver
#
# if transformers:
# self.transformers = transformers
# else:
# self.transformers = [Pickler()]
#
# if publisher:
# self.publisher = publisher
# else:
# self.publisher = ZMQPublisher()
#
# for i in range(len(self.transformers) - 1):
# self.transformers[i].set_callback(self.transformers[i+1].push)
#
# self.transformers[-1].set_callback(self.publisher.send)
#
# def open(self):
# """ Initialize the Transceiver and Publisher.
# """
#
# success = self.transceiver.open()
# if not success:
# return False
#
# success = self.publisher.open()
# if not success:
# return False
#
# return True
#
# def step(self):
# """ Read data and feed it into the first Transformer.
# """
#
# raw_data = self.transceiver.read()
#
# if raw_data is not None:
# self.transformers[0].push(raw_data)
#
# def run(self):
# """ Initialize components and start broadcasting.
# """
#
# success = self.open()
# if not success:
# print('Failed to initialize!')
# return
#
# while True:
# self.step()
which might include code, classes, or functions. Output only the next line. | 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(),
transformers=[MyDecoder(), MyCompressor(), ...],
publisher=MyPublisher()
)
A Reporter can be run as its own process::
reporter.run()
Or stepped through by an external engine::
reporter.open()
while not done:
reporter.step()
"""
def __init__(self, transceiver, transformers=None, publisher=None):
self.transceiver = transceiver
if transformers:
self.transformers = transformers
else:
<|code_end|>
. Write the next line using the current file imports:
from zircon.transformers.common import Pickler
from zircon.publishers.zeromq import ZMQPublisher
and context from other files:
# Path: zircon/transformers/common.py
# class Pickler(Transformer):
# """ Pickle messages with the latest protocol.
# """
# def push(self, msg):
# serialized_msg = pickle.dumps(msg)
# from pympler.asizeof import asizeof
# print('unpickled: {}, pickled: {}'.format(
# asizeof(msg),
# asizeof(serialized_msg)
# ))
# self.output(serialized_msg)
#
# Path: zircon/publishers/zeromq.py
# class ZMQPublisher(BasePublisher):
#
# def __init__(self, host='*', port=8811, zmq_type=zmq.PUB):
#
# self.host = host
# self.port = port
# self.zmq_type = zmq_type
# self.URI = 'tcp://{}:{}'.format(self.host, self.port)
#
# self.context = zmq.Context()
# self.sock = self.context.socket(self.zmq_type)
#
# self.count = 0
#
# def open(self):
# self.sock.bind(self.URI)
# return True
#
# def close(self):
# self.sock.close()
# return True
#
# def send(self, msg):
#
# try:
# self.sock.send(msg)
# self.count += 1
# print('[SENT] {}'.format(self.count))
# except TypeError:
# print('[ERROR] Message fed to Publisher must be serialized!')
# return False
#
# return True
, which may include functions, classes, or code. Output only the next line. | 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 external engine::
reporter.open()
while not done:
reporter.step()
"""
def __init__(self, transceiver, transformers=None, publisher=None):
self.transceiver = transceiver
if transformers:
self.transformers = transformers
else:
self.transformers = [Pickler()]
if publisher:
self.publisher = publisher
else:
<|code_end|>
. Use current file imports:
from zircon.transformers.common import Pickler
from zircon.publishers.zeromq import ZMQPublisher
and context (classes, functions, or code) from other files:
# Path: zircon/transformers/common.py
# class Pickler(Transformer):
# """ Pickle messages with the latest protocol.
# """
# def push(self, msg):
# serialized_msg = pickle.dumps(msg)
# from pympler.asizeof import asizeof
# print('unpickled: {}, pickled: {}'.format(
# asizeof(msg),
# asizeof(serialized_msg)
# ))
# self.output(serialized_msg)
#
# Path: zircon/publishers/zeromq.py
# class ZMQPublisher(BasePublisher):
#
# def __init__(self, host='*', port=8811, zmq_type=zmq.PUB):
#
# self.host = host
# self.port = port
# self.zmq_type = zmq_type
# self.URI = 'tcp://{}:{}'.format(self.host, self.port)
#
# self.context = zmq.Context()
# self.sock = self.context.socket(self.zmq_type)
#
# self.count = 0
#
# def open(self):
# self.sock.bind(self.URI)
# return True
#
# def close(self):
# self.sock.close()
# return True
#
# def send(self, msg):
#
# try:
# self.sock.send(msg)
# self.count += 1
# print('[SENT] {}'.format(self.count))
# except TypeError:
# print('[ERROR] Message fed to Publisher must be serialized!')
# return False
#
# return True
. Output only the next line. | 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),
)
# Complex form
# volumes:
# /foo:
# hostpath: /host/foo
# options: ro,z
if isinstance(node, dict):
hpath = node.get('hostpath')
if hpath is None:
raise ConfigError("Volume {} must have a 'hostpath' subkey".format(cpath))
return cls(
container_path = cpath,
host_path = _expand_path(hpath),
options = _get_delimited_str_list(node, 'options', ','),
)
raise ConfigError("{}: must be string or dict".format(cpath))
def get_vol_opt(self):
if not self.host_path:
raise NotImplementedError("No anonymous volumes for now")
<|code_end|>
, predict the next line using imports from the current file:
import collections
import os
import yaml
import re
import shlex
from .constants import *
from .utils import *
from .dockerutil import make_vol_opt
and context including class names, function names, and sometimes code from other files:
# Path: scuba/dockerutil.py
# def make_vol_opt(hostdir, contdir, options=None):
# '''Generate a docker volume option'''
# vol = '--volume={}:{}'.format(hostdir, contdir)
# if options != None:
# if isinstance(options, str):
# options = (options,)
# vol += ':' + ','.join(options)
# return vol
. Output only the next line. | 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(self.temp_path)
return self
def __exit__(self, *exc_info):
# Restore the working dir and cleanup the temp one
os.chdir(self.orig_path)
if self.delete:
shutil.rmtree(self.temp_path)
def test1():
with InTempDir(prefix='scuba-systest'):
with open('.scuba.yml', 'w+t') as f:
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import sys
import subprocess
import tempfile
import shutil
from tests.const import DOCKER_IMAGE
and context (classes, functions, sometimes code) from other files:
# Path: tests/const.py
# DOCKER_IMAGE = 'debian:10'
. Output only the next line. | 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)
stdout_data = stdout.read()
stderr_data = stderr.read()
logging.info('scuba stdout:\n' + stdout_data)
logging.info('scuba stderr:\n' + stderr_data)
# Verify the return value was as expected
assert exp_retval == retcode
return stdout_data, stderr_data
finally:
sys.stdin = old_stdin
sys.stdout = old_stdout
sys.stderr = old_stderr
def test_basic(self):
'''Verify basic scuba functionality'''
with open('.scuba.yml', 'w') as f:
<|code_end|>
, predict the immediate next line with the help of imports:
from .utils import *
from unittest import mock
from pathlib import Path
from tempfile import TemporaryFile, NamedTemporaryFile
from pwd import getpwuid
from grp import getgrgid
from .const import DOCKER_IMAGE
import pytest
import warnings
import logging
import os
import sys
import subprocess
import shlex
import scuba.__main__ as main
import scuba.constants
import scuba.dockerutil
import scuba
import re
and context (classes, functions, sometimes code) from other files:
# Path: tests/const.py
# DOCKER_IMAGE = 'debian:10'
. Output only the next line. | 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 scuba.config import ScubaConfig, ConfigError, OverrideStr
from scuba.scuba import ScubaContext
and context (classes, functions, or code) from other files:
# Path: scuba/config.py
# class ScubaConfig:
# def __init__(self, **data):
# optional_nodes = (
# 'image', 'aliases', 'hooks', 'entrypoint', 'environment', 'shell',
# 'docker_args', 'volumes',
# )
#
# # Check for unrecognized nodes
# extra = [n for n in data if not n in optional_nodes]
# if extra:
# raise ConfigError('{}: Unrecognized node{}: {}'.format(SCUBA_YML,
# 's' if len(extra) > 1 else '', ', '.join(extra)))
#
# self._image = data.get('image')
# self.shell = data.get('shell', DEFAULT_SHELL)
# self.entrypoint = _get_entrypoint(data)
# self.docker_args = _get_docker_args(data)
# self.volumes = _get_volumes(data)
# self._load_aliases(data)
# self._load_hooks(data)
# self._load_environment(data)
#
#
# def _load_aliases(self, data):
# self.aliases = {}
#
# for name, node in data.get('aliases', {}).items():
# if ' ' in name:
# raise ConfigError('Alias names cannot contain spaces')
# self.aliases[name] = ScubaAlias.from_dict(name, node)
#
# def _load_hooks(self, data):
# self.hooks = {}
#
# for name in ('user', 'root',):
# node = data.get('hooks', {}).get(name)
# if node:
# hook = _process_script_node(node, name)
# self.hooks[name] = hook
#
# def _load_environment(self, data):
# self.environment = _process_environment(data.get('environment'), 'environment')
#
#
# @property
# def image(self):
# if not self._image:
# raise ConfigError("Top-level 'image' not set")
# return self._image
#
# class ConfigError(Exception):
# pass
#
# class OverrideStr(str, OverrideMixin):
# pass
#
# Path: scuba/scuba.py
# class ScubaContext:
# def __init__(self, image=None, script=None, entrypoint=None, environment=None, shell=None, docker_args=None, volumes=None):
# self.image = image
# self.script = script
# self.as_root = False
# self.entrypoint = entrypoint
# self.environment = environment
# self.shell = shell
# self.docker_args = docker_args
# self.volumes = volumes or {}
#
# @classmethod
# def process_command(cls, cfg, command, image=None, shell=None):
# '''Processes a user command using aliases
#
# Arguments:
# cfg ScubaConfig object
# command A user command list (e.g. argv)
# image Override the image from .scuba.yml
# shell Override the shell from .scuba.yml
#
# Returns: A ScubaContext object with the following attributes:
# script: a list of command line strings
# image: the docker image name to use
# '''
# result = cls(
# entrypoint = cfg.entrypoint,
# environment = cfg.environment.copy(),
# shell = cfg.shell,
# docker_args = cfg.docker_args,
# volumes = cfg.volumes,
# )
#
# if command:
# alias = cfg.aliases.get(command[0])
# if not alias:
# # Command is not an alias; use it as-is.
# result.script = [shell_quote_cmd(command)]
# else:
# # Using an alias
# # Does this alias override the image and/or entrypoint?
# if alias.image:
# result.image = alias.image
# if alias.entrypoint is not None:
# result.entrypoint = alias.entrypoint
# if alias.shell is not None:
# result.shell = alias.shell
# if alias.as_root:
# result.as_root = True
#
# if isinstance(alias.docker_args, OverrideMixin) or result.docker_args is None:
# result.docker_args = alias.docker_args
# elif alias.docker_args is not None:
# result.docker_args.extend(alias.docker_args)
#
# if alias.volumes is not None:
# result.volumes.update(alias.volumes)
#
# # Merge/override the environment
# if alias.environment:
# result.environment.update(alias.environment)
#
# if len(alias.script) > 1:
# # Alias is a multiline script; no additional
# # arguments are allowed in the scuba invocation.
# if len(command) > 1:
# raise ConfigError('Additional arguments not allowed with multi-line aliases')
# result.script = alias.script
#
# else:
# # Alias is a single-line script; perform substituion
# # and add user arguments.
# command.pop(0)
# result.script = [alias.script[0] + ' ' + shell_quote_cmd(command)]
#
# result.script = flatten_list(result.script)
#
# # If a shell was given on the CLI, it should override the shell set by
# # the alias or top-level config
# if shell:
# result.shell = shell
#
# # If an image was given, it overrides what might have been set by an alias
# if image:
# result.image = image
#
# # If the image was still not set, then try to get it from the confg,
# # which will raise a ConfigError if it is not set
# if not result.image:
# result.image = cfg.image
#
# return result
. Output only the next line. | 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',
aliases = dict(
apple = dict(
script = [
'banana cherry "pie is good"',
],
docker_args = '-v /tmp/:/tmp/',
),
),
)
result = ScubaContext.process_command(cfg, ['apple'])
assert result.docker_args == ['--privileged', '-v', '/tmp/:/tmp/']
def test_process_command_alias_overrides_docker_args(self):
'''aliases can override the docker_args'''
cfg = ScubaConfig(
image = 'default',
docker_args = '--privileged',
aliases = dict(
apple = dict(
script = [
'banana cherry "pie is good"',
],
<|code_end|>
. Use current file imports:
import pytest
import shlex
from scuba.config import ScubaConfig, ConfigError, OverrideStr
from scuba.scuba import ScubaContext
and context (classes, functions, or code) from other files:
# Path: scuba/config.py
# class ScubaConfig:
# def __init__(self, **data):
# optional_nodes = (
# 'image', 'aliases', 'hooks', 'entrypoint', 'environment', 'shell',
# 'docker_args', 'volumes',
# )
#
# # Check for unrecognized nodes
# extra = [n for n in data if not n in optional_nodes]
# if extra:
# raise ConfigError('{}: Unrecognized node{}: {}'.format(SCUBA_YML,
# 's' if len(extra) > 1 else '', ', '.join(extra)))
#
# self._image = data.get('image')
# self.shell = data.get('shell', DEFAULT_SHELL)
# self.entrypoint = _get_entrypoint(data)
# self.docker_args = _get_docker_args(data)
# self.volumes = _get_volumes(data)
# self._load_aliases(data)
# self._load_hooks(data)
# self._load_environment(data)
#
#
# def _load_aliases(self, data):
# self.aliases = {}
#
# for name, node in data.get('aliases', {}).items():
# if ' ' in name:
# raise ConfigError('Alias names cannot contain spaces')
# self.aliases[name] = ScubaAlias.from_dict(name, node)
#
# def _load_hooks(self, data):
# self.hooks = {}
#
# for name in ('user', 'root',):
# node = data.get('hooks', {}).get(name)
# if node:
# hook = _process_script_node(node, name)
# self.hooks[name] = hook
#
# def _load_environment(self, data):
# self.environment = _process_environment(data.get('environment'), 'environment')
#
#
# @property
# def image(self):
# if not self._image:
# raise ConfigError("Top-level 'image' not set")
# return self._image
#
# class ConfigError(Exception):
# pass
#
# class OverrideStr(str, OverrideMixin):
# pass
#
# Path: scuba/scuba.py
# class ScubaContext:
# def __init__(self, image=None, script=None, entrypoint=None, environment=None, shell=None, docker_args=None, volumes=None):
# self.image = image
# self.script = script
# self.as_root = False
# self.entrypoint = entrypoint
# self.environment = environment
# self.shell = shell
# self.docker_args = docker_args
# self.volumes = volumes or {}
#
# @classmethod
# def process_command(cls, cfg, command, image=None, shell=None):
# '''Processes a user command using aliases
#
# Arguments:
# cfg ScubaConfig object
# command A user command list (e.g. argv)
# image Override the image from .scuba.yml
# shell Override the shell from .scuba.yml
#
# Returns: A ScubaContext object with the following attributes:
# script: a list of command line strings
# image: the docker image name to use
# '''
# result = cls(
# entrypoint = cfg.entrypoint,
# environment = cfg.environment.copy(),
# shell = cfg.shell,
# docker_args = cfg.docker_args,
# volumes = cfg.volumes,
# )
#
# if command:
# alias = cfg.aliases.get(command[0])
# if not alias:
# # Command is not an alias; use it as-is.
# result.script = [shell_quote_cmd(command)]
# else:
# # Using an alias
# # Does this alias override the image and/or entrypoint?
# if alias.image:
# result.image = alias.image
# if alias.entrypoint is not None:
# result.entrypoint = alias.entrypoint
# if alias.shell is not None:
# result.shell = alias.shell
# if alias.as_root:
# result.as_root = True
#
# if isinstance(alias.docker_args, OverrideMixin) or result.docker_args is None:
# result.docker_args = alias.docker_args
# elif alias.docker_args is not None:
# result.docker_args.extend(alias.docker_args)
#
# if alias.volumes is not None:
# result.volumes.update(alias.volumes)
#
# # Merge/override the environment
# if alias.environment:
# result.environment.update(alias.environment)
#
# if len(alias.script) > 1:
# # Alias is a multiline script; no additional
# # arguments are allowed in the scuba invocation.
# if len(command) > 1:
# raise ConfigError('Additional arguments not allowed with multi-line aliases')
# result.script = alias.script
#
# else:
# # Alias is a single-line script; perform substituion
# # and add user arguments.
# command.pop(0)
# result.script = [alias.script[0] + ' ' + shell_quote_cmd(command)]
#
# result.script = flatten_list(result.script)
#
# # If a shell was given on the CLI, it should override the shell set by
# # the alias or top-level config
# if shell:
# result.shell = shell
#
# # If an image was given, it overrides what might have been set by an alias
# if image:
# result.image = image
#
# # If the image was still not set, then try to get it from the confg,
# # which will raise a ConfigError if it is not set
# if not result.image:
# result.image = cfg.image
#
# return result
. Output only the next line. | 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,
entrypoint = entrypoint,
)
<|code_end|>
. Use current file imports:
(import pytest
import shlex
from scuba.config import ScubaConfig, ConfigError, OverrideStr
from scuba.scuba import ScubaContext)
and context including class names, function names, or small code snippets from other files:
# Path: scuba/config.py
# class ScubaConfig:
# def __init__(self, **data):
# optional_nodes = (
# 'image', 'aliases', 'hooks', 'entrypoint', 'environment', 'shell',
# 'docker_args', 'volumes',
# )
#
# # Check for unrecognized nodes
# extra = [n for n in data if not n in optional_nodes]
# if extra:
# raise ConfigError('{}: Unrecognized node{}: {}'.format(SCUBA_YML,
# 's' if len(extra) > 1 else '', ', '.join(extra)))
#
# self._image = data.get('image')
# self.shell = data.get('shell', DEFAULT_SHELL)
# self.entrypoint = _get_entrypoint(data)
# self.docker_args = _get_docker_args(data)
# self.volumes = _get_volumes(data)
# self._load_aliases(data)
# self._load_hooks(data)
# self._load_environment(data)
#
#
# def _load_aliases(self, data):
# self.aliases = {}
#
# for name, node in data.get('aliases', {}).items():
# if ' ' in name:
# raise ConfigError('Alias names cannot contain spaces')
# self.aliases[name] = ScubaAlias.from_dict(name, node)
#
# def _load_hooks(self, data):
# self.hooks = {}
#
# for name in ('user', 'root',):
# node = data.get('hooks', {}).get(name)
# if node:
# hook = _process_script_node(node, name)
# self.hooks[name] = hook
#
# def _load_environment(self, data):
# self.environment = _process_environment(data.get('environment'), 'environment')
#
#
# @property
# def image(self):
# if not self._image:
# raise ConfigError("Top-level 'image' not set")
# return self._image
#
# class ConfigError(Exception):
# pass
#
# class OverrideStr(str, OverrideMixin):
# pass
#
# Path: scuba/scuba.py
# class ScubaContext:
# def __init__(self, image=None, script=None, entrypoint=None, environment=None, shell=None, docker_args=None, volumes=None):
# self.image = image
# self.script = script
# self.as_root = False
# self.entrypoint = entrypoint
# self.environment = environment
# self.shell = shell
# self.docker_args = docker_args
# self.volumes = volumes or {}
#
# @classmethod
# def process_command(cls, cfg, command, image=None, shell=None):
# '''Processes a user command using aliases
#
# Arguments:
# cfg ScubaConfig object
# command A user command list (e.g. argv)
# image Override the image from .scuba.yml
# shell Override the shell from .scuba.yml
#
# Returns: A ScubaContext object with the following attributes:
# script: a list of command line strings
# image: the docker image name to use
# '''
# result = cls(
# entrypoint = cfg.entrypoint,
# environment = cfg.environment.copy(),
# shell = cfg.shell,
# docker_args = cfg.docker_args,
# volumes = cfg.volumes,
# )
#
# if command:
# alias = cfg.aliases.get(command[0])
# if not alias:
# # Command is not an alias; use it as-is.
# result.script = [shell_quote_cmd(command)]
# else:
# # Using an alias
# # Does this alias override the image and/or entrypoint?
# if alias.image:
# result.image = alias.image
# if alias.entrypoint is not None:
# result.entrypoint = alias.entrypoint
# if alias.shell is not None:
# result.shell = alias.shell
# if alias.as_root:
# result.as_root = True
#
# if isinstance(alias.docker_args, OverrideMixin) or result.docker_args is None:
# result.docker_args = alias.docker_args
# elif alias.docker_args is not None:
# result.docker_args.extend(alias.docker_args)
#
# if alias.volumes is not None:
# result.volumes.update(alias.volumes)
#
# # Merge/override the environment
# if alias.environment:
# result.environment.update(alias.environment)
#
# if len(alias.script) > 1:
# # Alias is a multiline script; no additional
# # arguments are allowed in the scuba invocation.
# if len(command) > 1:
# raise ConfigError('Additional arguments not allowed with multi-line aliases')
# result.script = alias.script
#
# else:
# # Alias is a single-line script; perform substituion
# # and add user arguments.
# command.pop(0)
# result.script = [alias.script[0] + ' ' + shell_quote_cmd(command)]
#
# result.script = flatten_list(result.script)
#
# # If a shell was given on the CLI, it should override the shell set by
# # the alias or top-level config
# if shell:
# result.shell = shell
#
# # If an image was given, it overrides what might have been set by an alias
# if image:
# result.image = image
#
# # If the image was still not set, then try to get it from the confg,
# # which will raise a ConfigError if it is not set
# if not result.image:
# result.image = cfg.image
#
# return result
. Output only the next line. | 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:{}".format(instance.id))
if full_rollback:
# The first uninstall is because a bug in the uninstall workflow:
# if node in `configured` state the uninstall try's to run stop so
# until then we need rollback always to `deleted`.
ctx.logger.debug("Start full rollback")
uninstall_node_instances(ctx.graph_mode(),
node_instances=set(unresolved_node_instances),
related_nodes=intact_nodes,
ignore_failure=True,
name_prefix='uninstall-a'
)
# For older than 5.1 Cloudify versions.
ctx.refresh_node_instances()
uninstall_node_instances(
graph=ctx.graph_mode(),
node_instances=ctx.node_instances,
ignore_failure=False,
name_prefix='uninstall-b')
# Build rollback graph and execute
else:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from cloudify.decorators import workflow
from cloudify.workflows.tasks_graph import make_or_get_graph
from cloudify.plugins.lifecycle import uninstall_node_instances, \
set_send_node_event_on_error_handler
from cloudify_rollback_workflow import lifecycle as utilitieslifecycle
and context:
# Path: cloudify_rollback_workflow/lifecycle.py
# def rollback_node_instances(graph,
# node_instances,
# related_nodes=None,
# name_prefix=''):
# def __init__(self,
# graph,
# node_instances=None,
# related_nodes=None,
# modified_relationship_ids=None,
# ignore_failure=False,
# name_prefix=''):
# def rollback(self):
# def _process_node_instances(self,
# ctx,
# node_instance_subgraph_func,
# graph_finisher_func):
# def _finish_uninstall(self, graph, subgraphs):
# def _finish_subgraphs(self, graph, subgraphs, intact_op, install):
# def intact_on_dependency_added(instance, rel, source_task_sequence):
# def _handle_dependency_creation(source_subgraph, target_subgraph,
# operation, target_id, graph):
# def _add_dependencies(self, graph, subgraphs, instances, install,
# on_dependency_added=None):
# def set_send_node_event_on_error_handler(task, instance):
# def _skip_nop_operations(task, pre=None, post=None):
# def _relationships_operations(graph,
# node_instance,
# operation,
# reverse=False,
# modified_relationship_ids=None):
# def _relationship_operations(relationship, operation):
# def is_host_node(node_instance):
# def _host_pre_stop(host_node_instance):
# def __init__(self, instance=None, instance_id=None):
# def dump(self):
# def __call__(self, tsk):
# def _relationship_subgraph_on_failure(subgraph):
# def _node_get_state_handler(tsk):
# def rollback_node_instance_subgraph(instance, graph, ignore_failure):
# def set_ignore_handlers(_subgraph):
# class UtilitiesLifecycleProcessor(object):
# class _SendNodeEventHandler(object):
which might include code, classes, or functions. Output only the next line. | 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': {
'test1': 'test',
'test2': ['a', 'b']
}
}
properties = {
'entries': {
first_key: first_value,
second_key: second_value,
third_key: third_value,
fourth_key: fourth_value
},
'variant': 'lab1',
'separator': '---'
}
# when
<|code_end|>
, generate the next line using the imports in this file:
import json
import unittest
import mock
from cloudify_secrets.sdk import SecretsSDK
and context (functions, classes, or occasionally code) from other files:
# Path: cloudify_secrets/sdk.py
# class SecretsSDK(object):
#
# DEFAULT_SEPARATOR = '__'
#
# @staticmethod
# def _try_to_serialize(value):
# if isinstance(value, (dict, list, tuple)):
# return json.dumps(value)
#
# return str(value)
#
# @staticmethod
# def _try_to_parse(value):
# try:
# return json.loads(value)
# except ValueError:
# return value
#
# def __init__(self, logger, rest_client, separator=DEFAULT_SEPARATOR, **_):
# self._logger = logger
# self._rest_client = rest_client
# self._separator = separator
#
# def _handle_variant(self, key, variant=None):
# if variant:
# return '{0}{1}{2}'.format(key, self._separator, variant)
#
# return key
#
# def _write(self, rest_client_method, entries, variant=None):
# result = {}
#
# for key, value in entries.items():
# self._logger.debug(
# 'Creating secret "{0}" with value: {1}'
# .format(key, value)
# )
#
# result[key] = rest_client_method(
# key=self._handle_variant(key, variant),
# value=self._try_to_serialize(value)
# )
#
# return result
#
# def create(self, entries, variant=None, **_):
# return self._write(self._rest_client.secrets.create, entries, variant)
#
# def update(self, entries, variant=None, **_):
# return self._write(self._rest_client.secrets.patch, entries, variant)
#
# def delete(self, secrets, variant=None, **_):
# for key in secrets.keys():
# self._logger.debug(
# 'Deleting secret "{0}" ...'.format(key)
# )
#
# self._rest_client.secrets.delete(
# key=self._handle_variant(key, variant)
# )
#
# def read(self, keys, variant=None, **_):
# result = {}
#
# for key in keys:
# self._logger.debug('Reading secret "{0}" ...'.format(key))
#
# response = self._rest_client.secrets.get(
# key=self._handle_variant(key, variant)
# )
#
# response['value'] = self._try_to_parse(response['value'])
# result[key] = response
#
# return result
. Output only the next line. | 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 express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
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()
@operation(resumable=True)
def create_list(ctx, **kwargs):
resource_config = ctx.node.properties.get('resource_config', None)
if not isinstance(resource_config, list):
raise NonRecoverableError(
'The "resource_config" property must be of type: list')
ctx.logger.debug('Initializing resources list...')
<|code_end|>
, predict the next line using imports from the current file:
from cloudify.decorators import operation
from cloudify.exceptions import NonRecoverableError
from .constants import (
RESOURCES_LIST_PROPERTY,
FREE_RESOURCES_LIST_PROPERTY,
RESERVATIONS_PROPERTY,
SINGLE_RESERVATION_PROPERTY
)
and context including class names, function names, and sometimes code from other files:
# Path: cloudify_resources/constants.py
# RESOURCES_LIST_PROPERTY = 'resource_config'
#
# FREE_RESOURCES_LIST_PROPERTY = 'free_resources'
#
# RESERVATIONS_PROPERTY = 'reservations'
#
# SINGLE_RESERVATION_PROPERTY = 'reservation'
. Output only the next line. | 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 language governing permissions and
# limitations under the License.
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()
@operation(resumable=True)
def create_list(ctx, **kwargs):
resource_config = ctx.node.properties.get('resource_config', None)
if not isinstance(resource_config, list):
raise NonRecoverableError(
'The "resource_config" property must be of type: list')
ctx.logger.debug('Initializing resources list...')
ctx.instance.runtime_properties[RESOURCES_LIST_PROPERTY] = resource_config
<|code_end|>
, predict the next line using imports from the current file:
from cloudify.decorators import operation
from cloudify.exceptions import NonRecoverableError
from .constants import (
RESOURCES_LIST_PROPERTY,
FREE_RESOURCES_LIST_PROPERTY,
RESERVATIONS_PROPERTY,
SINGLE_RESERVATION_PROPERTY
)
and context including class names, function names, and sometimes code from other files:
# Path: cloudify_resources/constants.py
# RESOURCES_LIST_PROPERTY = 'resource_config'
#
# FREE_RESOURCES_LIST_PROPERTY = 'free_resources'
#
# RESERVATIONS_PROPERTY = 'reservations'
#
# SINGLE_RESERVATION_PROPERTY = 'reservation'
. Output only the next line. | 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_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()
@operation(resumable=True)
def create_list(ctx, **kwargs):
resource_config = ctx.node.properties.get('resource_config', None)
if not isinstance(resource_config, list):
raise NonRecoverableError(
'The "resource_config" property must be of type: list')
ctx.logger.debug('Initializing resources list...')
ctx.instance.runtime_properties[RESOURCES_LIST_PROPERTY] = resource_config
ctx.instance.runtime_properties[FREE_RESOURCES_LIST_PROPERTY] = \
resource_config
<|code_end|>
, determine the next line of code. You have imports:
from cloudify.decorators import operation
from cloudify.exceptions import NonRecoverableError
from .constants import (
RESOURCES_LIST_PROPERTY,
FREE_RESOURCES_LIST_PROPERTY,
RESERVATIONS_PROPERTY,
SINGLE_RESERVATION_PROPERTY
)
and context (class names, function names, or code) available:
# Path: cloudify_resources/constants.py
# RESOURCES_LIST_PROPERTY = 'resource_config'
#
# FREE_RESOURCES_LIST_PROPERTY = 'free_resources'
#
# RESERVATIONS_PROPERTY = 'reservations'
#
# SINGLE_RESERVATION_PROPERTY = 'reservation'
. Output only the next line. | 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()
@operation(resumable=True)
def create_list(ctx, **kwargs):
resource_config = ctx.node.properties.get('resource_config', None)
if not isinstance(resource_config, list):
raise NonRecoverableError(
'The "resource_config" property must be of type: list')
ctx.logger.debug('Initializing resources list...')
ctx.instance.runtime_properties[RESOURCES_LIST_PROPERTY] = resource_config
ctx.instance.runtime_properties[FREE_RESOURCES_LIST_PROPERTY] = \
resource_config
ctx.instance.runtime_properties[RESERVATIONS_PROPERTY] = {}
@operation(resumable=True)
def create_list_item(ctx, **kwargs):
ctx.logger.debug('Initializing list item...')
<|code_end|>
with the help of current file imports:
from cloudify.decorators import operation
from cloudify.exceptions import NonRecoverableError
from .constants import (
RESOURCES_LIST_PROPERTY,
FREE_RESOURCES_LIST_PROPERTY,
RESERVATIONS_PROPERTY,
SINGLE_RESERVATION_PROPERTY
)
and context from other files:
# Path: cloudify_resources/constants.py
# RESOURCES_LIST_PROPERTY = 'resource_config'
#
# FREE_RESOURCES_LIST_PROPERTY = 'free_resources'
#
# RESERVATIONS_PROPERTY = 'reservations'
#
# SINGLE_RESERVATION_PROPERTY = 'reservation'
, which may contain function names, class names, or code. Output only the next line. | 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.relationships.resources.reserve_list_item',
target=tar_rel_subject_ctx
)
# source
src_ctx = MockCloudifyContext(
node_id='test_item_123456',
node_type='cloudify.nodes.resources.ListItem',
source=self,
target=tar_rel_subject_ctx,
relationships=rel_ctx
)
current_ctx.set(src_ctx)
return src_ctx
def test_create_delete_resources_list(self):
ctx = self._mock_resource_list_ctx()
# when (create)
<|code_end|>
, determine the next line of code. You have imports:
import unittest
from cloudify.state import current_ctx
from cloudify.mocks import (
MockCloudifyContext,
MockNodeContext,
MockNodeInstanceContext,
MockRelationshipContext,
MockRelationshipSubjectContext
)
from cloudify_resources import tasks
from cloudify_resources.constants import (
RESOURCES_LIST_PROPERTY,
FREE_RESOURCES_LIST_PROPERTY,
RESERVATIONS_PROPERTY,
SINGLE_RESERVATION_PROPERTY
)
and context (class names, function names, or code) available:
# Path: cloudify_resources/tasks.py
# def _refresh_source_and_target_runtime_props(ctx, **kwargs):
# def _update_source_and_target_runtime_props(ctx, **kwargs):
# def create_list(ctx, **kwargs):
# def create_list_item(ctx, **kwargs):
# def delete_list_item(ctx, **kwargs):
# def delete_list(ctx, **kwargs):
# def reserve_list_item(ctx, **kwargs):
# def return_list_item(ctx, **kwargs):
#
# Path: cloudify_resources/constants.py
# RESOURCES_LIST_PROPERTY = 'resource_config'
#
# FREE_RESOURCES_LIST_PROPERTY = 'free_resources'
#
# RESERVATIONS_PROPERTY = 'reservations'
#
# SINGLE_RESERVATION_PROPERTY = 'reservation'
. Output only the next line. | 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
)
# source
src_ctx = MockCloudifyContext(
node_id='test_item_123456',
node_type='cloudify.nodes.resources.ListItem',
source=self,
target=tar_rel_subject_ctx,
relationships=rel_ctx
)
current_ctx.set(src_ctx)
return src_ctx
def test_create_delete_resources_list(self):
ctx = self._mock_resource_list_ctx()
# when (create)
tasks.create_list(ctx)
# then (create)
self.assertTrue(
<|code_end|>
. Use current file imports:
(import unittest
from cloudify.state import current_ctx
from cloudify.mocks import (
MockCloudifyContext,
MockNodeContext,
MockNodeInstanceContext,
MockRelationshipContext,
MockRelationshipSubjectContext
)
from cloudify_resources import tasks
from cloudify_resources.constants import (
RESOURCES_LIST_PROPERTY,
FREE_RESOURCES_LIST_PROPERTY,
RESERVATIONS_PROPERTY,
SINGLE_RESERVATION_PROPERTY
))
and context including class names, function names, or small code snippets from other files:
# Path: cloudify_resources/tasks.py
# def _refresh_source_and_target_runtime_props(ctx, **kwargs):
# def _update_source_and_target_runtime_props(ctx, **kwargs):
# def create_list(ctx, **kwargs):
# def create_list_item(ctx, **kwargs):
# def delete_list_item(ctx, **kwargs):
# def delete_list(ctx, **kwargs):
# def reserve_list_item(ctx, **kwargs):
# def return_list_item(ctx, **kwargs):
#
# Path: cloudify_resources/constants.py
# RESOURCES_LIST_PROPERTY = 'resource_config'
#
# FREE_RESOURCES_LIST_PROPERTY = 'free_resources'
#
# RESERVATIONS_PROPERTY = 'reservations'
#
# SINGLE_RESERVATION_PROPERTY = 'reservation'
. Output only the next line. | 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',
node_type='cloudify.nodes.resources.ListItem',
source=self,
target=tar_rel_subject_ctx,
relationships=rel_ctx
)
current_ctx.set(src_ctx)
return src_ctx
def test_create_delete_resources_list(self):
ctx = self._mock_resource_list_ctx()
# when (create)
tasks.create_list(ctx)
# then (create)
self.assertTrue(
RESOURCES_LIST_PROPERTY in ctx.instance.runtime_properties)
self.assertTrue(
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
from cloudify.state import current_ctx
from cloudify.mocks import (
MockCloudifyContext,
MockNodeContext,
MockNodeInstanceContext,
MockRelationshipContext,
MockRelationshipSubjectContext
)
from cloudify_resources import tasks
from cloudify_resources.constants import (
RESOURCES_LIST_PROPERTY,
FREE_RESOURCES_LIST_PROPERTY,
RESERVATIONS_PROPERTY,
SINGLE_RESERVATION_PROPERTY
)
and context (classes, functions, sometimes code) from other files:
# Path: cloudify_resources/tasks.py
# def _refresh_source_and_target_runtime_props(ctx, **kwargs):
# def _update_source_and_target_runtime_props(ctx, **kwargs):
# def create_list(ctx, **kwargs):
# def create_list_item(ctx, **kwargs):
# def delete_list_item(ctx, **kwargs):
# def delete_list(ctx, **kwargs):
# def reserve_list_item(ctx, **kwargs):
# def return_list_item(ctx, **kwargs):
#
# Path: cloudify_resources/constants.py
# RESOURCES_LIST_PROPERTY = 'resource_config'
#
# FREE_RESOURCES_LIST_PROPERTY = 'free_resources'
#
# RESERVATIONS_PROPERTY = 'reservations'
#
# SINGLE_RESERVATION_PROPERTY = 'reservation'
. Output only the next line. | 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.