code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from flask import (
Blueprint,
abort,
current_app,
jsonify,
redirect,
render_template,
request,
session,
url_for,
)
from flask_user import roles_required
from ..database import db
from ..date_tools import localize_datetime
from ..extensions import oauth, recaptcha
from ..models.app_text import (
AboutATMA,
PrivacyATMA,
Terms_ATMA,
VersionedResource,
WebsiteDeclarationForm_ATMA,
app_text,
get_terms,
)
from ..models.client import validate_origin
from ..models.coredata import Coredata
from ..models.intervention import Intervention
from ..models.message import EmailMessage
from ..models.organization import Organization
from ..models.role import ROLE
from ..models.user import current_user, get_user
from ..views.auth import next_after_login
from ..views.external_assets import (
asset_by_uuid,
get_all_tag_data,
get_any_tag_data,
)
eproms = Blueprint(
'eproms', __name__, template_folder='templates', static_folder='static',
static_url_path='/eproms/static')
@eproms.errorhandler(404)
def page_not_found(e):
return render_template(
'eproms/404.html', no_nav="true", user=current_user()), 404
@eproms.errorhandler(500)
def server_error(e): # pragma: no cover
# NB - this is only hit if app.debug == False
# exception is automatically sent to log by framework
return render_template(
'eproms/500.html', no_nav="true", user=current_user()), 500
@eproms.route('/')
def landing():
"""landing page view function - present register / login options"""
if current_user():
current_app.logger.debug("landing (found user) -> next_after_login")
return next_after_login()
timed_out = request.args.get('timed_out', False)
init_login_modal = False
if 'pending_authorize_args' in session:
init_login_modal = True
return render_template(
'eproms/landing.html', user=None, no_nav="true",
timed_out=timed_out,
init_login_modal=init_login_modal)
def assessment_engine_view(user):
"""View like function for this very special intervention
Most interventions maintain a small block of HTML in the interventions
or (when customized per user) in the user_interventions table.
The assessment engine is special, as much of the state used to determine
logic switches within the displayed HTML only lives within the portal
and not with the intervention. Furthermore, the displayed HTML exceeds
the "card" model, is significantly more complex (i.e. modal use) and
therefore gets this function to render the "main well" of the page used
to display intervention cards.
NB - not a real flask view method, as the returned HTML needs to be
embedded within another page, not made into a response object.
"""
from datetime import datetime
from ..models.overall_status import OverallStatus
from ..models.qb_status import QB_Status, patient_research_study_status
from ..models.research_study import BASE_RS_ID, EMPRO_RS_ID, ResearchStudy
now = datetime.utcnow()
research_study_status = patient_research_study_status(user)
assessment_status = QB_Status(
user=user,
research_study_id=BASE_RS_ID,
as_of_date=now)
unstarted_indefinite_instruments = (
assessment_status.instruments_needing_full_assessment(
classification='indefinite'))
unfinished_indefinite_instruments = (
assessment_status.instruments_in_progress(
classification='indefinite'))
# variables needed for the templates
due_date = (
localize_datetime(assessment_status.target_date, user)
if assessment_status.target_date else None)
expired_date = (
localize_datetime(assessment_status.expired_date, user)
if assessment_status.expired_date else None)
comp_date = (
localize_datetime(assessment_status.completed_date, user)
if assessment_status.completed_date else None)
assessment_is_due = (
research_study_status.get(BASE_RS_ID, {}).get('ready', False))
enrolled_in_indefinite = assessment_status.enrolled_in_classification(
"indefinite")
substudy_assessment_status = QB_Status(
user=user,
research_study_id=EMPRO_RS_ID,
as_of_date=now)
enrolled_in_substudy = EMPRO_RS_ID in research_study_status
substudy_due_date = (
localize_datetime(substudy_assessment_status.target_date, user)
if substudy_assessment_status.target_date else None)
substudy_comp_date = (
localize_datetime(substudy_assessment_status.completed_date, user)
if substudy_assessment_status.completed_date else None)
substudy_assessment_is_due = (
enrolled_in_substudy and research_study_status[EMPRO_RS_ID]['ready'])
substudy_assessment_is_ready = (
enrolled_in_substudy and research_study_status[EMPRO_RS_ID]['ready'])
substudy_assessment_errors = (
enrolled_in_substudy and research_study_status[EMPRO_RS_ID]['errors'])
return render_template(
"eproms/assessment_engine.html",
user=user,
research_study_status=research_study_status,
assessment_status=assessment_status,
enrolled_in_indefinite=enrolled_in_indefinite,
unstarted_indefinite_instruments=unstarted_indefinite_instruments,
unfinished_indefinite_instruments=unfinished_indefinite_instruments,
OverallStatus=OverallStatus,
full_name=user.display_name,
registry=assessment_status.assigning_authority,
due_date=due_date,
expired_date=expired_date,
assessment_is_due=assessment_is_due,
comp_date=comp_date,
enrolled_in_substudy=enrolled_in_substudy,
substudy_assessment_status=substudy_assessment_status,
substudy_assessment_is_due=substudy_assessment_is_due,
substudy_due_date=substudy_due_date,
substudy_comp_date=substudy_comp_date,
substudy_assessment_is_ready=substudy_assessment_is_ready,
substudy_assessment_errors=substudy_assessment_errors
)
@eproms.route('/home')
def home():
"""home page view function
Present user with appropriate view dependent on roles.
The initial flow through authentication and data collection is
controlled by next_after_login(). Only expecting requests
here after login and intermediate steps have been handled, and then
only if the login didn't include a 'next' target.
Raising server error (500) if unexpected state is found to assist in
finding problems.
"""
user = current_user()
# Enforce flow - expect authorized user for this view
if not user:
return redirect(url_for('eproms.landing'))
# Possible user attempted to avoid flow via browser back
# and needs to be sent immediately back to appropriate page
if (not Coredata().initial_obtained(user) or
'next' in session and session['next']):
return next_after_login()
# All checks passed - present appropriate view for user role
if user.has_role(ROLE.STAFF_ADMIN.value):
return redirect(url_for('staff.staff_index'))
if user.has_role(
ROLE.INTERVENTION_STAFF.value,
ROLE.STAFF.value):
return redirect(url_for('patients.patients_root'))
if user.has_role(ROLE.CLINICIAN.value):
return redirect(url_for('patients.patients_substudy'))
if user.has_role(ROLE.RESEARCHER.value):
return redirect(url_for('portal.research_dashboard'))
if not user.has_role(ROLE.PATIENT.value):
abort(404, "no /home view for user with roles: {}".format(
str([r.name for r in user.roles])))
interventions = Intervention.query.order_by(
Intervention.display_rank).all()
consent_agreements = {}
return render_template(
'eproms/portal.html',
user=user,
assessment_engine_view=assessment_engine_view,
interventions=interventions,
consent_agreements=consent_agreements)
@eproms.route('/privacy')
def privacy():
""" privacy use page"""
user = current_user()
if user:
organization = user.first_top_organization()
# EPROMS only has privacy docs for staff and patient
# Give all roles besides patient the staff version
role = ROLE.STAFF.value
if user.has_role(ROLE.PATIENT.value):
role = ROLE.PATIENT.value
# only include role and organization if both are defined
if not all((role, organization)):
role, organization = None, None
privacy_resource = VersionedResource(app_text(
PrivacyATMA.name_key(role=role, organization=organization)),
locale_code=user.locale_code)
else:
abort(400, "No publicly viewable privacy policy page available")
return render_template(
'eproms/privacy.html',
content=privacy_resource.asset, user=user,
editorUrl=privacy_resource.editor_url)
@eproms.route('/terms')
def terms_and_conditions():
""" terms-and-conditions of use page"""
user = current_user()
if user:
organization = user.first_top_organization()
role = None
if user.has_role(ROLE.STAFF.value, ROLE.STAFF_ADMIN.value):
role = ROLE.STAFF.value
elif user.has_role(ROLE.PATIENT.value):
role = ROLE.PATIENT.value
if not all((role, organization)):
role, organization = None, None
terms = VersionedResource(app_text(Terms_ATMA.name_key(
role=role, organization=organization)),
locale_code=user.locale_code)
else:
terms = VersionedResource(
app_text(Terms_ATMA.name_key()), locale_code=None)
return render_template(
'eproms/terms.html', content=terms.asset, editorUrl=terms.editor_url,
user=user)
@eproms.route('/about')
def about():
"""main TrueNTH about page"""
user = current_user()
locale_code = user.locale_code if user else None
about_tnth = VersionedResource(
app_text(AboutATMA.name_key(subject='TrueNTH')),
locale_code=locale_code)
return render_template(
'eproms/about.html',
about_tnth=about_tnth.asset,
about_tnth_editorUrl=about_tnth.editor_url,
user=user)
@eproms.route('/contact', methods=('GET', 'POST'))
def contact():
"""main TrueNTH contact page"""
user = current_user()
if request.method == 'GET':
sendername = user.display_name if user else ''
email = user.email if user else ''
recipient_types = []
for org in Organization.query.filter(Organization.email.isnot(None)):
if '@' in org.email:
recipient_types.append((org.name, org.email))
config_recipients = current_app.config.get('CONTACT_RECIPIENTS')
if config_recipients:
recipient_types = recipient_types + config_recipients
return render_template(
'eproms/contact.html', sendername=sendername, email=email,
user=user,
types=recipient_types)
if (not user and
current_app.config.get('RECAPTCHA_SITE_KEY', None) and
current_app.config.get('RECAPTCHA_SECRET_KEY', None) and
not recaptcha.verify()):
abort(400, "Recaptcha verification failed")
sender = request.form.get('email')
if not sender or ('@' not in sender):
abort(400, "No valid sender email address provided")
sendername = request.form.get('sendername')
subject = "{server} contact request: {subject}".format(
server=current_app.config['SERVER_NAME'],
subject=request.form.get('subject'))
if len(sendername) > 255:
abort(400, "Sender name max character length exceeded")
if len(subject) > 255:
abort(400, "Subject max character length exceeded")
formbody = request.form.get('body')
if not formbody:
abort(400, "No contact request body provided")
body = "From: {sendername}<br />Email: {sender}<br /><br />{body}".format(
sendername=sendername, sender=sender, body=formbody)
recipient = request.form.get('type')
recipient = recipient or current_app.config['CONTACT_SENDTO_EMAIL']
if not recipient:
abort(400, "No recipient found")
user_id = user.id if user else None
email = EmailMessage(subject=subject, body=body, recipients=recipient,
sender=sender, user_id=user_id)
email.send_message()
db.session.add(email)
db.session.commit()
return jsonify(msgid=email.id)
@eproms.route('/website-consent-script/<int:patient_id>', methods=['GET'])
@roles_required([ROLE.STAFF.value, ROLE.STAFF_ADMIN.value])
@oauth.require_oauth()
def website_consent_script(patient_id):
entry_method = request.args.get('entry_method', None)
redirect_url = request.args.get('redirect_url', None)
if redirect_url:
"""
redirect url here is the patient's assessment link
/api/present-assessment, so validate against local origin
"""
validate_origin(redirect_url)
user = current_user()
patient = get_user(patient_id, 'view')
org = patient.first_top_organization()
"""
NOTE, we are getting PATIENT's website consent terms here
as STAFF member needs to read the terms to the patient
"""
terms = get_terms(user.locale_code, org, ROLE.PATIENT.value)
top_org = patient.first_top_organization()
declaration_form = VersionedResource(
app_text(WebsiteDeclarationForm_ATMA.name_key(organization=top_org)),
locale_code=user.locale_code)
return render_template(
'eproms/website_consent_script.html', user=user,
terms=terms, top_organization=top_org,
entry_method=entry_method, redirect_url=redirect_url,
declaration_form=declaration_form, patient_id=patient_id)
@eproms.route('/resources', methods=['GET'])
@roles_required([ROLE.STAFF.value, ROLE.STAFF_ADMIN.value])
@oauth.require_oauth()
def resources():
user = current_user()
org = user.first_top_organization()
if not org:
abort(400, 'user must belong to an organization')
asset_title = '{} work instruction'.format(org.name.lower())
resources_data = get_any_tag_data(asset_title)
results = resources_data['results']
if (len(results) > 0):
demo_content = []
for asset in results:
if 'demo' in asset['tags']:
demo_content.append(asset_by_uuid(asset['uuid']))
# filter for topic tag for the work instruction
asset['topics'] = [tag for tag in asset['tags'] if tag not in (
asset_title, 'individual work instruction')]
return render_template('eproms/resources.html',
results=results, demo_content=demo_content)
else:
abort(400, 'no resources found')
@eproms.route('/empro-resources', methods=['GET'])
@roles_required([ROLE.STAFF.value, ROLE.STAFF_ADMIN.value, ROLE.CLINICIAN.value])
@oauth.require_oauth()
def empro_resources():
user = current_user()
org = user.first_top_organization()
if not org:
abort(400, 'user must belong to an organization')
resources_data = get_any_tag_data("empro-training-material")
results = resources_data['results']
if len(results) == 0:
abort(400, 'resources not found')
for item in results:
content = asset_by_uuid(item['uuid'])
item['content'] = content
return render_template('eproms/empro_resources.html',
results=results)
@eproms.route('/resources/work-instruction/<string:tag>', methods=['GET'])
@roles_required([ROLE.STAFF.value, ROLE.STAFF_ADMIN.value])
@oauth.require_oauth()
def work_instruction(tag):
user = current_user()
org = user.first_top_organization()
if not tag:
abort(400, 'work instruction tag is required')
if not org:
abort(400, 'user must belong to an organization')
work_instruction_data = get_all_tag_data(tag, '{} work instruction'.
format(org.name.lower()))
results = work_instruction_data['results']
if len(results) > 0:
content = asset_by_uuid(results[0]['uuid'])
return render_template('eproms/work_instruction.html',
content=content, title=tag)
else:
abort(400, 'work instruction not found') | portal/eproms/views.py | from flask import (
Blueprint,
abort,
current_app,
jsonify,
redirect,
render_template,
request,
session,
url_for,
)
from flask_user import roles_required
from ..database import db
from ..date_tools import localize_datetime
from ..extensions import oauth, recaptcha
from ..models.app_text import (
AboutATMA,
PrivacyATMA,
Terms_ATMA,
VersionedResource,
WebsiteDeclarationForm_ATMA,
app_text,
get_terms,
)
from ..models.client import validate_origin
from ..models.coredata import Coredata
from ..models.intervention import Intervention
from ..models.message import EmailMessage
from ..models.organization import Organization
from ..models.role import ROLE
from ..models.user import current_user, get_user
from ..views.auth import next_after_login
from ..views.external_assets import (
asset_by_uuid,
get_all_tag_data,
get_any_tag_data,
)
eproms = Blueprint(
'eproms', __name__, template_folder='templates', static_folder='static',
static_url_path='/eproms/static')
@eproms.errorhandler(404)
def page_not_found(e):
return render_template(
'eproms/404.html', no_nav="true", user=current_user()), 404
@eproms.errorhandler(500)
def server_error(e): # pragma: no cover
# NB - this is only hit if app.debug == False
# exception is automatically sent to log by framework
return render_template(
'eproms/500.html', no_nav="true", user=current_user()), 500
@eproms.route('/')
def landing():
"""landing page view function - present register / login options"""
if current_user():
current_app.logger.debug("landing (found user) -> next_after_login")
return next_after_login()
timed_out = request.args.get('timed_out', False)
init_login_modal = False
if 'pending_authorize_args' in session:
init_login_modal = True
return render_template(
'eproms/landing.html', user=None, no_nav="true",
timed_out=timed_out,
init_login_modal=init_login_modal)
def assessment_engine_view(user):
"""View like function for this very special intervention
Most interventions maintain a small block of HTML in the interventions
or (when customized per user) in the user_interventions table.
The assessment engine is special, as much of the state used to determine
logic switches within the displayed HTML only lives within the portal
and not with the intervention. Furthermore, the displayed HTML exceeds
the "card" model, is significantly more complex (i.e. modal use) and
therefore gets this function to render the "main well" of the page used
to display intervention cards.
NB - not a real flask view method, as the returned HTML needs to be
embedded within another page, not made into a response object.
"""
from datetime import datetime
from ..models.overall_status import OverallStatus
from ..models.qb_status import QB_Status, patient_research_study_status
from ..models.research_study import BASE_RS_ID, EMPRO_RS_ID, ResearchStudy
now = datetime.utcnow()
research_study_status = patient_research_study_status(user)
assessment_status = QB_Status(
user=user,
research_study_id=BASE_RS_ID,
as_of_date=now)
unstarted_indefinite_instruments = (
assessment_status.instruments_needing_full_assessment(
classification='indefinite'))
unfinished_indefinite_instruments = (
assessment_status.instruments_in_progress(
classification='indefinite'))
# variables needed for the templates
due_date = (
localize_datetime(assessment_status.target_date, user)
if assessment_status.target_date else None)
expired_date = (
localize_datetime(assessment_status.expired_date, user)
if assessment_status.expired_date else None)
comp_date = (
localize_datetime(assessment_status.completed_date, user)
if assessment_status.completed_date else None)
assessment_is_due = (
research_study_status.get(BASE_RS_ID, {}).get('ready', False))
enrolled_in_indefinite = assessment_status.enrolled_in_classification(
"indefinite")
substudy_assessment_status = QB_Status(
user=user,
research_study_id=EMPRO_RS_ID,
as_of_date=now)
enrolled_in_substudy = EMPRO_RS_ID in research_study_status
substudy_due_date = (
localize_datetime(substudy_assessment_status.target_date, user)
if substudy_assessment_status.target_date else None)
substudy_comp_date = (
localize_datetime(substudy_assessment_status.completed_date, user)
if substudy_assessment_status.completed_date else None)
substudy_assessment_is_due = (
enrolled_in_substudy and research_study_status[EMPRO_RS_ID]['ready'])
substudy_assessment_is_ready = (
enrolled_in_substudy and research_study_status[EMPRO_RS_ID]['ready'])
substudy_assessment_errors = (
enrolled_in_substudy and research_study_status[EMPRO_RS_ID]['errors'])
return render_template(
"eproms/assessment_engine.html",
user=user,
research_study_status=research_study_status,
assessment_status=assessment_status,
enrolled_in_indefinite=enrolled_in_indefinite,
unstarted_indefinite_instruments=unstarted_indefinite_instruments,
unfinished_indefinite_instruments=unfinished_indefinite_instruments,
OverallStatus=OverallStatus,
full_name=user.display_name,
registry=assessment_status.assigning_authority,
due_date=due_date,
expired_date=expired_date,
assessment_is_due=assessment_is_due,
comp_date=comp_date,
enrolled_in_substudy=enrolled_in_substudy,
substudy_assessment_status=substudy_assessment_status,
substudy_assessment_is_due=substudy_assessment_is_due,
substudy_due_date=substudy_due_date,
substudy_comp_date=substudy_comp_date,
substudy_assessment_is_ready=substudy_assessment_is_ready,
substudy_assessment_errors=substudy_assessment_errors
)
@eproms.route('/home')
def home():
"""home page view function
Present user with appropriate view dependent on roles.
The initial flow through authentication and data collection is
controlled by next_after_login(). Only expecting requests
here after login and intermediate steps have been handled, and then
only if the login didn't include a 'next' target.
Raising server error (500) if unexpected state is found to assist in
finding problems.
"""
user = current_user()
# Enforce flow - expect authorized user for this view
if not user:
return redirect(url_for('eproms.landing'))
# Possible user attempted to avoid flow via browser back
# and needs to be sent immediately back to appropriate page
if (not Coredata().initial_obtained(user) or
'next' in session and session['next']):
return next_after_login()
# All checks passed - present appropriate view for user role
if user.has_role(ROLE.STAFF_ADMIN.value):
return redirect(url_for('staff.staff_index'))
if user.has_role(
ROLE.INTERVENTION_STAFF.value,
ROLE.STAFF.value):
return redirect(url_for('patients.patients_root'))
if user.has_role(ROLE.CLINICIAN.value):
return redirect(url_for('patients.patients_substudy'))
if user.has_role(ROLE.RESEARCHER.value):
return redirect(url_for('portal.research_dashboard'))
if not user.has_role(ROLE.PATIENT.value):
abort(404, "no /home view for user with roles: {}".format(
str([r.name for r in user.roles])))
interventions = Intervention.query.order_by(
Intervention.display_rank).all()
consent_agreements = {}
return render_template(
'eproms/portal.html',
user=user,
assessment_engine_view=assessment_engine_view,
interventions=interventions,
consent_agreements=consent_agreements)
@eproms.route('/privacy')
def privacy():
""" privacy use page"""
user = current_user()
if user:
organization = user.first_top_organization()
# EPROMS only has privacy docs for staff and patient
# Give all roles besides patient the staff version
role = ROLE.STAFF.value
if user.has_role(ROLE.PATIENT.value):
role = ROLE.PATIENT.value
# only include role and organization if both are defined
if not all((role, organization)):
role, organization = None, None
privacy_resource = VersionedResource(app_text(
PrivacyATMA.name_key(role=role, organization=organization)),
locale_code=user.locale_code)
else:
abort(400, "No publicly viewable privacy policy page available")
return render_template(
'eproms/privacy.html',
content=privacy_resource.asset, user=user,
editorUrl=privacy_resource.editor_url)
@eproms.route('/terms')
def terms_and_conditions():
""" terms-and-conditions of use page"""
user = current_user()
if user:
organization = user.first_top_organization()
role = None
if user.has_role(ROLE.STAFF.value, ROLE.STAFF_ADMIN.value):
role = ROLE.STAFF.value
elif user.has_role(ROLE.PATIENT.value):
role = ROLE.PATIENT.value
if not all((role, organization)):
role, organization = None, None
terms = VersionedResource(app_text(Terms_ATMA.name_key(
role=role, organization=organization)),
locale_code=user.locale_code)
else:
terms = VersionedResource(
app_text(Terms_ATMA.name_key()), locale_code=None)
return render_template(
'eproms/terms.html', content=terms.asset, editorUrl=terms.editor_url,
user=user)
@eproms.route('/about')
def about():
"""main TrueNTH about page"""
user = current_user()
locale_code = user.locale_code if user else None
about_tnth = VersionedResource(
app_text(AboutATMA.name_key(subject='TrueNTH')),
locale_code=locale_code)
return render_template(
'eproms/about.html',
about_tnth=about_tnth.asset,
about_tnth_editorUrl=about_tnth.editor_url,
user=user)
@eproms.route('/contact', methods=('GET', 'POST'))
def contact():
"""main TrueNTH contact page"""
user = current_user()
if request.method == 'GET':
sendername = user.display_name if user else ''
email = user.email if user else ''
recipient_types = []
for org in Organization.query.filter(Organization.email.isnot(None)):
if '@' in org.email:
recipient_types.append((org.name, org.email))
config_recipients = current_app.config.get('CONTACT_RECIPIENTS')
if config_recipients:
recipient_types = recipient_types + config_recipients
return render_template(
'eproms/contact.html', sendername=sendername, email=email,
user=user,
types=recipient_types)
if (not user and
current_app.config.get('RECAPTCHA_SITE_KEY', None) and
current_app.config.get('RECAPTCHA_SECRET_KEY', None) and
not recaptcha.verify()):
abort(400, "Recaptcha verification failed")
sender = request.form.get('email')
if not sender or ('@' not in sender):
abort(400, "No valid sender email address provided")
sendername = request.form.get('sendername')
subject = "{server} contact request: {subject}".format(
server=current_app.config['SERVER_NAME'],
subject=request.form.get('subject'))
if len(sendername) > 255:
abort(400, "Sender name max character length exceeded")
if len(subject) > 255:
abort(400, "Subject max character length exceeded")
formbody = request.form.get('body')
if not formbody:
abort(400, "No contact request body provided")
body = "From: {sendername}<br />Email: {sender}<br /><br />{body}".format(
sendername=sendername, sender=sender, body=formbody)
recipient = request.form.get('type')
recipient = recipient or current_app.config['CONTACT_SENDTO_EMAIL']
if not recipient:
abort(400, "No recipient found")
user_id = user.id if user else None
email = EmailMessage(subject=subject, body=body, recipients=recipient,
sender=sender, user_id=user_id)
email.send_message()
db.session.add(email)
db.session.commit()
return jsonify(msgid=email.id)
@eproms.route('/website-consent-script/<int:patient_id>', methods=['GET'])
@roles_required([ROLE.STAFF.value, ROLE.STAFF_ADMIN.value])
@oauth.require_oauth()
def website_consent_script(patient_id):
entry_method = request.args.get('entry_method', None)
redirect_url = request.args.get('redirect_url', None)
if redirect_url:
"""
redirect url here is the patient's assessment link
/api/present-assessment, so validate against local origin
"""
validate_origin(redirect_url)
user = current_user()
patient = get_user(patient_id, 'view')
org = patient.first_top_organization()
"""
NOTE, we are getting PATIENT's website consent terms here
as STAFF member needs to read the terms to the patient
"""
terms = get_terms(user.locale_code, org, ROLE.PATIENT.value)
top_org = patient.first_top_organization()
declaration_form = VersionedResource(
app_text(WebsiteDeclarationForm_ATMA.name_key(organization=top_org)),
locale_code=user.locale_code)
return render_template(
'eproms/website_consent_script.html', user=user,
terms=terms, top_organization=top_org,
entry_method=entry_method, redirect_url=redirect_url,
declaration_form=declaration_form, patient_id=patient_id)
@eproms.route('/resources', methods=['GET'])
@roles_required([ROLE.STAFF.value, ROLE.STAFF_ADMIN.value])
@oauth.require_oauth()
def resources():
user = current_user()
org = user.first_top_organization()
if not org:
abort(400, 'user must belong to an organization')
asset_title = '{} work instruction'.format(org.name.lower())
resources_data = get_any_tag_data(asset_title)
results = resources_data['results']
if (len(results) > 0):
demo_content = []
for asset in results:
if 'demo' in asset['tags']:
demo_content.append(asset_by_uuid(asset['uuid']))
# filter for topic tag for the work instruction
asset['topics'] = [tag for tag in asset['tags'] if tag not in (
asset_title, 'individual work instruction')]
return render_template('eproms/resources.html',
results=results, demo_content=demo_content)
else:
abort(400, 'no resources found')
@eproms.route('/empro-resources', methods=['GET'])
@roles_required([ROLE.STAFF.value, ROLE.STAFF_ADMIN.value, ROLE.CLINICIAN.value])
@oauth.require_oauth()
def empro_resources():
user = current_user()
org = user.first_top_organization()
if not org:
abort(400, 'user must belong to an organization')
resources_data = get_any_tag_data("empro-training-material")
results = resources_data['results']
if len(results) == 0:
abort(400, 'resources not found')
for item in results:
content = asset_by_uuid(item['uuid'])
item['content'] = content
return render_template('eproms/empro_resources.html',
results=results)
@eproms.route('/resources/work-instruction/<string:tag>', methods=['GET'])
@roles_required([ROLE.STAFF.value, ROLE.STAFF_ADMIN.value])
@oauth.require_oauth()
def work_instruction(tag):
user = current_user()
org = user.first_top_organization()
if not tag:
abort(400, 'work instruction tag is required')
if not org:
abort(400, 'user must belong to an organization')
work_instruction_data = get_all_tag_data(tag, '{} work instruction'.
format(org.name.lower()))
results = work_instruction_data['results']
if len(results) > 0:
content = asset_by_uuid(results[0]['uuid'])
return render_template('eproms/work_instruction.html',
content=content, title=tag)
else:
abort(400, 'work instruction not found') | 0.488771 | 0.108992 |
from django.contrib.auth.forms import UserCreationForm
from django.test import TestCase
from django.contrib.auth.models import User
# Create your tests here.
from django.urls import reverse,resolve
from ..views import signup
from ..forms import SignUpForm
class SignUpTests(TestCase):
def setUp(self):
url = reverse('signup')
self.response = self.client.get(url)
def test_signup_status_code(self):
self.assertEquals(self.response.status_code,200)
def test_signup_url_resolves_signup_view(self):
view = resolve('/signup/')
self.assertEquals(view.func,signup)
def test_csrf(self):
self.assertContains(self.response,'csrfmiddlewaretoken')
def test_contains_form(self):
form = self.response.context.get('form')
self.assertIsInstance(form,SignUpForm)
def test_form_inputs(self):
self.assertContains(self.response,'<input',5)
self.assertContains(self.response,'type="text"',1)
self.assertContains(self.response,'type="email"',1)
self.assertContains(self.response,'type="password"',2)
class SucessfulSignUpTests(TestCase):
def setUp(self) -> None:
url =reverse('signup')
data = {
'username':'john',
'email':'<EMAIL>',
'password1':'<PASSWORD>',
'password2':'<PASSWORD>'
}
self.response = self.client.post(url,data)
self.home_url = reverse('home')
def test_redirection(self):
self.assertRedirects(self.response,self.home_url)
def test_user_creation(self):
self.assertTrue(User.objects.exists())
def test_user_authentication(self):
response = self.client.get(self.home_url)
user = response.context.get('user')
self.assertTrue(user.is_authenticated)
class InvalidSignUpTests(TestCase):
def setUp(self) -> None:
url = reverse('signup')
self.response = self.client.post(url,{})
def test_signup_status_code(self):
self.assertEquals(self.response.status_code,200)
def test_form_errors(self):
form = self.response.context.get('form')
self.assertTrue(form.errors)
def test_dont_create_user(self):
self.assertFalse(User.objects.exists()) | accounts/tests/test_view_signup.py | from django.contrib.auth.forms import UserCreationForm
from django.test import TestCase
from django.contrib.auth.models import User
# Create your tests here.
from django.urls import reverse,resolve
from ..views import signup
from ..forms import SignUpForm
class SignUpTests(TestCase):
def setUp(self):
url = reverse('signup')
self.response = self.client.get(url)
def test_signup_status_code(self):
self.assertEquals(self.response.status_code,200)
def test_signup_url_resolves_signup_view(self):
view = resolve('/signup/')
self.assertEquals(view.func,signup)
def test_csrf(self):
self.assertContains(self.response,'csrfmiddlewaretoken')
def test_contains_form(self):
form = self.response.context.get('form')
self.assertIsInstance(form,SignUpForm)
def test_form_inputs(self):
self.assertContains(self.response,'<input',5)
self.assertContains(self.response,'type="text"',1)
self.assertContains(self.response,'type="email"',1)
self.assertContains(self.response,'type="password"',2)
class SucessfulSignUpTests(TestCase):
def setUp(self) -> None:
url =reverse('signup')
data = {
'username':'john',
'email':'<EMAIL>',
'password1':'<PASSWORD>',
'password2':'<PASSWORD>'
}
self.response = self.client.post(url,data)
self.home_url = reverse('home')
def test_redirection(self):
self.assertRedirects(self.response,self.home_url)
def test_user_creation(self):
self.assertTrue(User.objects.exists())
def test_user_authentication(self):
response = self.client.get(self.home_url)
user = response.context.get('user')
self.assertTrue(user.is_authenticated)
class InvalidSignUpTests(TestCase):
def setUp(self) -> None:
url = reverse('signup')
self.response = self.client.post(url,{})
def test_signup_status_code(self):
self.assertEquals(self.response.status_code,200)
def test_form_errors(self):
form = self.response.context.get('form')
self.assertTrue(form.errors)
def test_dont_create_user(self):
self.assertFalse(User.objects.exists()) | 0.443118 | 0.306161 |
import tensorflow as tf
import tensorflow_text as tf_text
import numpy as np
from tensorflow.keras.layers.experimental import preprocessing
def load_data(path):
# path = Path lib object (not string)
text = path.read_text(encoding='utf-8')
lines = text.splitlines()
pairs = [line.split('\t') for line in lines]
inp = [inp for targ, inp in pairs]
targ = [targ for targ, inp in pairs]
return targ, inp
def create_dataset(inputs, targets, BATCH_SIZE=64):
BUFFER_SIZE = len(inputs)
dataset = tf.data.Dataset.from_tensor_slices((inputs, targets)).shuffle(BUFFER_SIZE)
dataset = dataset.batch(BATCH_SIZE)
return dataset
def print_examples(dataset, n=5):
for example_input_batch, example_target_batch in dataset.take(1):
for ex_in, ex_ta in zip(example_input_batch[:n], example_target_batch[:n]):
print(ex_in.numpy().decode())
print(ex_ta.numpy().decode())
print("--------------------")
break
def print_example_tokens(dataset, input_text_processor, target_text_processor):
for example_input_batch, example_target_batch in dataset.take(1):
print("Example input token sequences (indices):")
example_tokens = input_text_processor(example_input_batch)
print(example_tokens[:3, :10])
def tf_lower_and_split_punct(text):
"""
pre-processing of text string
removes punctuation, removes accents from characters, normalises whitespace, adds [START] and [END] tokens
:param text:
:return: a tf tensor of the normalised string
"""
# Split accented characters. - NB this will see accents stripped out later on
text = tf_text.normalize_utf8(text, 'NFKD') # NFKD re: http://unicode.org/reports/tr15/ like ICU
text = tf.strings.lower(text) # does tf lower work ok for unicode accented chars?
# Keep space, a to z, and strip punctuation and accents if NFKD is used.
text = tf.strings.regex_replace(text, r'[^\w\s]', '') # we don't need punctuation, accents though?
# compress multiple spaces.
text = tf.strings.regex_replace(text, r'\s+', r' ')
# Strip whitespace.
text = tf.strings.strip(text)
text = tf.strings.join(['[START]', text, '[END]'], separator=' ')
return text
def create_text_processor(samples, max_vocab_size):
text_processor = preprocessing.TextVectorization(
standardize=tf_lower_and_split_punct,
max_tokens=max_vocab_size)
text_processor.adapt(samples)
return text_processor
def index_to_string(text_processor, tokens):
input_vocab = np.array(text_processor.get_vocabulary())
tokens = input_vocab[tokens[0].numpy()]
return ' '.join(tokens)
def plot_mask(tokens):
plt.subplot(1, 2, 1)
plt.pcolormesh(tokens)
plt.title('Token IDs')
plt.subplot(1, 2, 2)
plt.pcolormesh(tokens != 0)
plt.title('Mask') | src/disfluency_generator/data_preparation.py | import tensorflow as tf
import tensorflow_text as tf_text
import numpy as np
from tensorflow.keras.layers.experimental import preprocessing
def load_data(path):
# path = Path lib object (not string)
text = path.read_text(encoding='utf-8')
lines = text.splitlines()
pairs = [line.split('\t') for line in lines]
inp = [inp for targ, inp in pairs]
targ = [targ for targ, inp in pairs]
return targ, inp
def create_dataset(inputs, targets, BATCH_SIZE=64):
BUFFER_SIZE = len(inputs)
dataset = tf.data.Dataset.from_tensor_slices((inputs, targets)).shuffle(BUFFER_SIZE)
dataset = dataset.batch(BATCH_SIZE)
return dataset
def print_examples(dataset, n=5):
for example_input_batch, example_target_batch in dataset.take(1):
for ex_in, ex_ta in zip(example_input_batch[:n], example_target_batch[:n]):
print(ex_in.numpy().decode())
print(ex_ta.numpy().decode())
print("--------------------")
break
def print_example_tokens(dataset, input_text_processor, target_text_processor):
for example_input_batch, example_target_batch in dataset.take(1):
print("Example input token sequences (indices):")
example_tokens = input_text_processor(example_input_batch)
print(example_tokens[:3, :10])
def tf_lower_and_split_punct(text):
"""
pre-processing of text string
removes punctuation, removes accents from characters, normalises whitespace, adds [START] and [END] tokens
:param text:
:return: a tf tensor of the normalised string
"""
# Split accented characters. - NB this will see accents stripped out later on
text = tf_text.normalize_utf8(text, 'NFKD') # NFKD re: http://unicode.org/reports/tr15/ like ICU
text = tf.strings.lower(text) # does tf lower work ok for unicode accented chars?
# Keep space, a to z, and strip punctuation and accents if NFKD is used.
text = tf.strings.regex_replace(text, r'[^\w\s]', '') # we don't need punctuation, accents though?
# compress multiple spaces.
text = tf.strings.regex_replace(text, r'\s+', r' ')
# Strip whitespace.
text = tf.strings.strip(text)
text = tf.strings.join(['[START]', text, '[END]'], separator=' ')
return text
def create_text_processor(samples, max_vocab_size):
text_processor = preprocessing.TextVectorization(
standardize=tf_lower_and_split_punct,
max_tokens=max_vocab_size)
text_processor.adapt(samples)
return text_processor
def index_to_string(text_processor, tokens):
input_vocab = np.array(text_processor.get_vocabulary())
tokens = input_vocab[tokens[0].numpy()]
return ' '.join(tokens)
def plot_mask(tokens):
plt.subplot(1, 2, 1)
plt.pcolormesh(tokens)
plt.title('Token IDs')
plt.subplot(1, 2, 2)
plt.pcolormesh(tokens != 0)
plt.title('Mask') | 0.661595 | 0.465327 |
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class BiosVfCbsDfCmnDramNpsConsts:
VP_CBS_DF_CMN_DRAM_NPS_AUTO = "Auto"
VP_CBS_DF_CMN_DRAM_NPS_NPS0 = "NPS0"
VP_CBS_DF_CMN_DRAM_NPS_NPS1 = "NPS1"
VP_CBS_DF_CMN_DRAM_NPS_NPS2 = "NPS2"
VP_CBS_DF_CMN_DRAM_NPS_NPS4 = "NPS4"
VP_CBS_DF_CMN_DRAM_NPS_PLATFORM_DEFAULT = "platform-default"
class BiosVfCbsDfCmnDramNps(ManagedObject):
"""This is BiosVfCbsDfCmnDramNps class."""
consts = BiosVfCbsDfCmnDramNpsConsts()
naming_props = set([])
mo_meta = {
"classic": MoMeta("BiosVfCbsDfCmnDramNps", "biosVfCbsDfCmnDramNps", "nodes-per-socket", VersionMeta.Version421a, "InputOutput", 0x1f, [], ["admin"], ['biosPlatformDefaults', 'biosSettings'], [], [None]),
}
prop_meta = {
"classic": {
"child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version421a, MoPropertyMeta.INTERNAL, None, None, None, None, [], []),
"dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x2, 0, 255, None, [], []),
"rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x4, 0, 255, None, [], []),
"status": MoPropertyMeta("status", "status", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x8, None, None, None, ["", "created", "deleted", "modified", "removed"], []),
"vp_cbs_df_cmn_dram_nps": MoPropertyMeta("vp_cbs_df_cmn_dram_nps", "vpCbsDfCmnDramNps", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x10, None, None, None, ["Auto", "NPS0", "NPS1", "NPS2", "NPS4", "platform-default"], []),
},
}
prop_map = {
"classic": {
"childAction": "child_action",
"dn": "dn",
"rn": "rn",
"status": "status",
"vpCbsDfCmnDramNps": "vp_cbs_df_cmn_dram_nps",
},
}
def __init__(self, parent_mo_or_dn, **kwargs):
self._dirty_mask = 0
self.child_action = None
self.status = None
self.vp_cbs_df_cmn_dram_nps = None
ManagedObject.__init__(self, "BiosVfCbsDfCmnDramNps", parent_mo_or_dn, **kwargs) | imcsdk/mometa/bios/BiosVfCbsDfCmnDramNps.py |
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class BiosVfCbsDfCmnDramNpsConsts:
VP_CBS_DF_CMN_DRAM_NPS_AUTO = "Auto"
VP_CBS_DF_CMN_DRAM_NPS_NPS0 = "NPS0"
VP_CBS_DF_CMN_DRAM_NPS_NPS1 = "NPS1"
VP_CBS_DF_CMN_DRAM_NPS_NPS2 = "NPS2"
VP_CBS_DF_CMN_DRAM_NPS_NPS4 = "NPS4"
VP_CBS_DF_CMN_DRAM_NPS_PLATFORM_DEFAULT = "platform-default"
class BiosVfCbsDfCmnDramNps(ManagedObject):
"""This is BiosVfCbsDfCmnDramNps class."""
consts = BiosVfCbsDfCmnDramNpsConsts()
naming_props = set([])
mo_meta = {
"classic": MoMeta("BiosVfCbsDfCmnDramNps", "biosVfCbsDfCmnDramNps", "nodes-per-socket", VersionMeta.Version421a, "InputOutput", 0x1f, [], ["admin"], ['biosPlatformDefaults', 'biosSettings'], [], [None]),
}
prop_meta = {
"classic": {
"child_action": MoPropertyMeta("child_action", "childAction", "string", VersionMeta.Version421a, MoPropertyMeta.INTERNAL, None, None, None, None, [], []),
"dn": MoPropertyMeta("dn", "dn", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x2, 0, 255, None, [], []),
"rn": MoPropertyMeta("rn", "rn", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x4, 0, 255, None, [], []),
"status": MoPropertyMeta("status", "status", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x8, None, None, None, ["", "created", "deleted", "modified", "removed"], []),
"vp_cbs_df_cmn_dram_nps": MoPropertyMeta("vp_cbs_df_cmn_dram_nps", "vpCbsDfCmnDramNps", "string", VersionMeta.Version421a, MoPropertyMeta.READ_WRITE, 0x10, None, None, None, ["Auto", "NPS0", "NPS1", "NPS2", "NPS4", "platform-default"], []),
},
}
prop_map = {
"classic": {
"childAction": "child_action",
"dn": "dn",
"rn": "rn",
"status": "status",
"vpCbsDfCmnDramNps": "vp_cbs_df_cmn_dram_nps",
},
}
def __init__(self, parent_mo_or_dn, **kwargs):
self._dirty_mask = 0
self.child_action = None
self.status = None
self.vp_cbs_df_cmn_dram_nps = None
ManagedObject.__init__(self, "BiosVfCbsDfCmnDramNps", parent_mo_or_dn, **kwargs) | 0.414425 | 0.223525 |
import sys
sys.path.append('/home/cai/Documents/PyDMD/')
import numpy as np
import matplotlib.pyplot as plt
from read_dcm import DcmRead
import dicom
import SimpleITK as sitk
import os
image_dir = None #the results dir
"""
Input: iamge_sequence: the dce-mri data. the size is mn*t. m and n are related to the row and col of the image.
T is for pixel position and image_size is the size of the single dcm image
function: get curve data from image sequence
"""
def get_data(image_sequence = None, T = None, image_size = None):
[x, y] = [T[0], T[1]]
[pixels ,num] = np.shape(image_sequence)
Data = []
for i in range(0,num):
a1 = image_sequence[T[0]*image_size[1] + T[1],i]
a2 = image_sequence[(T[0]+1)*image_size[1] + T[1],i]
a3 = image_sequence[(T[0]-1)*image_size[1] + T[1],i]
a4 = image_sequence[T[0]*image_size[1] + (T[1]+1),i]
a5 = image_sequence[(T[0]+1)*image_size[1] + (T[1]-1),i]
a6 = image_sequence[(T[0]-1)*image_size[1] + T[1],i]
a7 = image_sequence[T[0]*image_size[1] + T[1],i]
a8 = image_sequence[(T[0]+1)*image_size[1] + (T[1]+1),i]
a9 = image_sequence[(T[0]-1)*image_size[1] + (T[1]-1),i]
pixel_data = (a1+a2+a3+a4+a5+a6+a7+a8+a9)/9
Data.append(pixel_data)
curve_data = np.array(Data)
return curve_data
"""
for each col is the intensities of image sequences at one pixel location.
each row indicates the curve is obtained from different sequences at the same pixel location
each curve will be shown in different color
"""
def draw(Data = None, lable_name=None,save_loc = None):
x = np.linspace(1,np.shape(Data)[0],np.shape(Data)[0])
plt.figure()
plt.xlabel('time point')
plt.ylabel('pixel value')
for i in range(0, np.shape(Data)[1]):
# draw curve
y = Data[:, i]
plt.plot(x,y,"x-",label=lable_name[i])
plt.legend(bbox_to_anchor=(1.0, 1), loc=1, borderaxespad=0.)
plt.savefig(save_loc)
def getDataFrom_mhd(image_dir,key,mask):
file_names = os.listdir(image_dir)
file_names.sort(key = str.lower)
flag = 0
data = []
for fi in file_names:
if key in fi and 'mhd' in fi:
#print("read file sequence:"+fi)
file_name = os.path.join(image_dir,fi) #setting the fixed image
image_data = sitk.GetArrayFromImage(sitk.ReadImage(file_name))
image_data = image_data*mask
image_data = image_data[118:169,67:125]
data.append(np.reshape(image_data,[image_data.shape[0]*image_data.shape[1],1]))
array_data = np.array(data)[:,:,0].T
return array_data
def save_curve(input_dir = None,T_point = None):
Data = getDataFrom_mhd(input_dir,key='moving')
curve_data.append(get_data(Data,T = T_point,image_size=[256,256]))
lable_name.append('moving')
Data = getDataFrom_mhd(input_dir,key='result')
curve_data.append(get_data(Data,T = [141,98],image_size=[256,256]))
lable_name.append('IM_1026')
def draw_hist(input_array = None):
i = 1
if __name__=="__main__":
input_dir = "/home/cai/Documents/registration/test/out/lung/my_method/images"
curve_data = []
lable_name = []
save_loc = "../../1.png"
input_dir = "/home/cai/Documents/registration/test/out/lung/IM_1021/images"
Data = getDataFrom_mhd(input_dir,key='moving')
curve_data.append(get_data(Data,T = [141,97],image_size=[256,256]))
lable_name.append('moving')
# Data = getDataFrom_mhd(input_dir,key='result')
# curve_data.append(get_data(Data,T = [141,97],image_size=[256,256]))
# lable_name.append('IM_1021')
input_dir = "/home/cai/Documents/registration/test/out/lung/my_method/images"
Data = getDataFrom_mhd(input_dir,key='result')
curve_data.append(get_data(Data,T = [141,97],image_size=[256,256]))
lable_name.append('my_method')
# input_dir = "/home/cai/Documents/registration/test/out/lung/IM_1046/images"
# Data = getDataFrom_mhd(input_dir,key='result')
# curve_data.append(get_data(Data,T = [141,97],image_size=[256,256]))
# lable_name.append('IM_1046')
input_dir = "/home/cai/Documents/registration/test/out/lung/IM_1076/images"
Data = getDataFrom_mhd(input_dir,key='result')
curve_data.append(get_data(Data,T = [141,97],image_size=[256,256]))
lable_name.append('IM_1076')
# input_dir = "/home/cai/Documents/registration/test/out/lung/IM_1066/images"
# Data = getDataFrom_mhd(input_dir,key='result')
# curve_data.append(get_data(Data,T = [141,97],image_size=[256,256]))
# lable_name.append('IM_1066')
draw(np.array(curve_data).T,lable_name,save_loc='bijiao12.png') | PyDMD/DCE_tools/ti_curve.py | import sys
sys.path.append('/home/cai/Documents/PyDMD/')
import numpy as np
import matplotlib.pyplot as plt
from read_dcm import DcmRead
import dicom
import SimpleITK as sitk
import os
image_dir = None #the results dir
"""
Input: iamge_sequence: the dce-mri data. the size is mn*t. m and n are related to the row and col of the image.
T is for pixel position and image_size is the size of the single dcm image
function: get curve data from image sequence
"""
def get_data(image_sequence = None, T = None, image_size = None):
[x, y] = [T[0], T[1]]
[pixels ,num] = np.shape(image_sequence)
Data = []
for i in range(0,num):
a1 = image_sequence[T[0]*image_size[1] + T[1],i]
a2 = image_sequence[(T[0]+1)*image_size[1] + T[1],i]
a3 = image_sequence[(T[0]-1)*image_size[1] + T[1],i]
a4 = image_sequence[T[0]*image_size[1] + (T[1]+1),i]
a5 = image_sequence[(T[0]+1)*image_size[1] + (T[1]-1),i]
a6 = image_sequence[(T[0]-1)*image_size[1] + T[1],i]
a7 = image_sequence[T[0]*image_size[1] + T[1],i]
a8 = image_sequence[(T[0]+1)*image_size[1] + (T[1]+1),i]
a9 = image_sequence[(T[0]-1)*image_size[1] + (T[1]-1),i]
pixel_data = (a1+a2+a3+a4+a5+a6+a7+a8+a9)/9
Data.append(pixel_data)
curve_data = np.array(Data)
return curve_data
"""
for each col is the intensities of image sequences at one pixel location.
each row indicates the curve is obtained from different sequences at the same pixel location
each curve will be shown in different color
"""
def draw(Data = None, lable_name=None,save_loc = None):
x = np.linspace(1,np.shape(Data)[0],np.shape(Data)[0])
plt.figure()
plt.xlabel('time point')
plt.ylabel('pixel value')
for i in range(0, np.shape(Data)[1]):
# draw curve
y = Data[:, i]
plt.plot(x,y,"x-",label=lable_name[i])
plt.legend(bbox_to_anchor=(1.0, 1), loc=1, borderaxespad=0.)
plt.savefig(save_loc)
def getDataFrom_mhd(image_dir,key,mask):
file_names = os.listdir(image_dir)
file_names.sort(key = str.lower)
flag = 0
data = []
for fi in file_names:
if key in fi and 'mhd' in fi:
#print("read file sequence:"+fi)
file_name = os.path.join(image_dir,fi) #setting the fixed image
image_data = sitk.GetArrayFromImage(sitk.ReadImage(file_name))
image_data = image_data*mask
image_data = image_data[118:169,67:125]
data.append(np.reshape(image_data,[image_data.shape[0]*image_data.shape[1],1]))
array_data = np.array(data)[:,:,0].T
return array_data
def save_curve(input_dir = None,T_point = None):
Data = getDataFrom_mhd(input_dir,key='moving')
curve_data.append(get_data(Data,T = T_point,image_size=[256,256]))
lable_name.append('moving')
Data = getDataFrom_mhd(input_dir,key='result')
curve_data.append(get_data(Data,T = [141,98],image_size=[256,256]))
lable_name.append('IM_1026')
def draw_hist(input_array = None):
i = 1
if __name__=="__main__":
input_dir = "/home/cai/Documents/registration/test/out/lung/my_method/images"
curve_data = []
lable_name = []
save_loc = "../../1.png"
input_dir = "/home/cai/Documents/registration/test/out/lung/IM_1021/images"
Data = getDataFrom_mhd(input_dir,key='moving')
curve_data.append(get_data(Data,T = [141,97],image_size=[256,256]))
lable_name.append('moving')
# Data = getDataFrom_mhd(input_dir,key='result')
# curve_data.append(get_data(Data,T = [141,97],image_size=[256,256]))
# lable_name.append('IM_1021')
input_dir = "/home/cai/Documents/registration/test/out/lung/my_method/images"
Data = getDataFrom_mhd(input_dir,key='result')
curve_data.append(get_data(Data,T = [141,97],image_size=[256,256]))
lable_name.append('my_method')
# input_dir = "/home/cai/Documents/registration/test/out/lung/IM_1046/images"
# Data = getDataFrom_mhd(input_dir,key='result')
# curve_data.append(get_data(Data,T = [141,97],image_size=[256,256]))
# lable_name.append('IM_1046')
input_dir = "/home/cai/Documents/registration/test/out/lung/IM_1076/images"
Data = getDataFrom_mhd(input_dir,key='result')
curve_data.append(get_data(Data,T = [141,97],image_size=[256,256]))
lable_name.append('IM_1076')
# input_dir = "/home/cai/Documents/registration/test/out/lung/IM_1066/images"
# Data = getDataFrom_mhd(input_dir,key='result')
# curve_data.append(get_data(Data,T = [141,97],image_size=[256,256]))
# lable_name.append('IM_1066')
draw(np.array(curve_data).T,lable_name,save_loc='bijiao12.png') | 0.203233 | 0.566198 |
import sys
from zlib import crc32
import numpy as np
import pytest
from distributed.protocol import (
serialize,
deserialize,
decompress,
dumps,
loads,
to_serialize,
msgpack,
)
from distributed.protocol.utils import BIG_BYTES_SHARD_SIZE
from distributed.protocol.numpy import itemsize
from distributed.protocol.compression import maybe_compress
from distributed.system import MEMORY_LIMIT
from distributed.utils import tmpfile, nbytes
from distributed.utils_test import gen_cluster
def test_serialize():
x = np.ones((5, 5))
header, frames = serialize(x)
assert header["type"]
assert len(frames) == 1
if "compression" in header:
frames = decompress(header, frames)
result = deserialize(header, frames)
assert (result == x).all()
@pytest.mark.parametrize(
"x",
[
np.ones(5),
np.array(5),
np.random.random((5, 5)),
np.random.random((5, 5))[::2, :],
np.random.random((5, 5))[:, ::2],
np.asfortranarray(np.random.random((5, 5))),
np.asfortranarray(np.random.random((5, 5)))[::2, :],
np.asfortranarray(np.random.random((5, 5)))[:, ::2],
np.random.random(5).astype("f4"),
np.random.random(5).astype(">i8"),
np.random.random(5).astype("<i8"),
np.arange(5).astype("M8[us]"),
np.arange(5).astype("M8[ms]"),
np.arange(5).astype("m8"),
np.arange(5).astype("m8[s]"),
np.arange(5).astype("c16"),
np.arange(5).astype("c8"),
np.array([True, False, True]),
np.ones(shape=5, dtype=[("a", "i4"), ("b", "M8[us]")]),
np.array(["abc"], dtype="S3"),
np.array(["abc"], dtype="U3"),
np.array(["abc"], dtype=object),
np.ones(shape=(5,), dtype=("f8", 32)),
np.ones(shape=(5,), dtype=[("x", "f8", 32)]),
np.ones(shape=(5,), dtype=np.dtype([("a", "i1"), ("b", "f8")], align=False)),
np.ones(shape=(5,), dtype=np.dtype([("a", "i1"), ("b", "f8")], align=True)),
np.ones(shape=(5,), dtype=np.dtype([("a", "m8[us]")], align=False)),
# this dtype fails unpickling
np.ones(shape=(5,), dtype=np.dtype([("a", "m8")], align=False)),
np.array([(1, "abc")], dtype=[("x", "i4"), ("s", object)]),
np.zeros(5000, dtype=[("x%d" % i, "<f8") for i in range(4)]),
np.zeros(5000, dtype="S32"),
np.zeros((1, 1000, 1000)),
np.arange(12)[::2], # non-contiguous array
np.ones(shape=(5, 6)).astype(dtype=[("total", "<f8"), ("n", "<f8")]),
np.broadcast_to(np.arange(3), shape=(10, 3)), # zero-strided array
],
)
def test_dumps_serialize_numpy(x):
header, frames = serialize(x)
if "compression" in header:
frames = decompress(header, frames)
buffer_interface = memoryview
for frame in frames:
assert isinstance(frame, (bytes, buffer_interface))
y = deserialize(header, frames)
np.testing.assert_equal(x, y)
if x.flags.c_contiguous or x.flags.f_contiguous:
assert x.strides == y.strides
@pytest.mark.parametrize(
"x",
[
np.ma.masked_array([5, 6], mask=[True, False], fill_value=10, dtype="i4"),
np.ma.masked_array([5.0, 6.0], mask=[True, False], fill_value=10, dtype="f4"),
np.ma.masked_array(
[5.0, 6.0], mask=[True, False], fill_value=np.nan, dtype="f8"
),
np.ma.masked_array(
[5.0, 6.0], mask=np.ma.nomask, fill_value=np.nan, dtype="f8"
),
np.ma.masked_array(
[True, False], mask=np.ma.nomask, fill_value=True, dtype="bool"
),
np.ma.masked_array(["a", "b"], mask=[True, False], fill_value="c", dtype="O"),
],
)
def test_serialize_numpy_ma_masked_array(x):
(y,) = loads(dumps([to_serialize(x)]))
assert x.data.dtype == y.data.dtype
np.testing.assert_equal(x.data, y.data)
np.testing.assert_equal(x.mask, y.mask)
np.testing.assert_equal(x.fill_value, y.fill_value)
def test_serialize_numpy_ma_masked():
(y,) = loads(dumps([to_serialize(np.ma.masked)]))
assert y is np.ma.masked
def test_dumps_serialize_numpy_custom_dtype():
import builtins
test_rational = pytest.importorskip("numpy.core.test_rational")
rational = test_rational.rational
try:
builtins.rational = (
rational # Work around https://github.com/numpy/numpy/issues/9160
)
x = np.array([1], dtype=rational)
header, frames = serialize(x)
y = deserialize(header, frames)
np.testing.assert_equal(x, y)
finally:
del builtins.rational
def test_memmap():
with tmpfile("npy") as fn:
with open(fn, "wb") as f: # touch file
pass
x = np.memmap(fn, shape=(5, 5), dtype="i4", mode="readwrite")
x[:] = 5
header, frames = serialize(x)
if "compression" in header:
frames = decompress(header, frames)
y = deserialize(header, frames)
np.testing.assert_equal(x, y)
@pytest.mark.slow
def test_dumps_serialize_numpy_large():
if MEMORY_LIMIT < 2e9:
pytest.skip("insufficient memory")
x = np.random.random(size=int(BIG_BYTES_SHARD_SIZE * 2 // 8)).view("u1")
assert x.nbytes == BIG_BYTES_SHARD_SIZE * 2
frames = dumps([to_serialize(x)])
dtype, shape = x.dtype, x.shape
checksum = crc32(x)
del x
[y] = loads(frames)
assert (y.dtype, y.shape) == (dtype, shape)
assert crc32(y) == checksum, "Arrays are unequal"
@pytest.mark.parametrize(
"dt,size",
[
("f8", 8),
("i4", 4),
("c16", 16),
("b", 1),
("S3", 3),
("M8[us]", 8),
("M8[s]", 8),
("U3", 12),
([("a", "i4"), ("b", "f8")], 12),
(("i4", 100), 4),
([("a", "i4", 100)], 8),
([("a", "i4", 20), ("b", "f8")], 20 * 4 + 8),
([("a", "i4", 200), ("b", "f8")], 8),
],
)
def test_itemsize(dt, size):
assert itemsize(np.dtype(dt)) == size
@pytest.mark.skipif(sys.version_info[0] < 3, reason="numpy doesnt use memoryviews")
def test_compress_numpy():
pytest.importorskip("lz4")
x = np.ones(10000000, dtype="i4")
frames = dumps({"x": to_serialize(x)})
assert sum(map(nbytes, frames)) < x.nbytes
header = msgpack.loads(frames[2], raw=False, use_list=False)
try:
import blosc # noqa: F401
except ImportError:
pass
else:
assert all(c == "blosc" for c in header["headers"][("x",)]["compression"])
def test_compress_memoryview():
mv = memoryview(b"0" * 1000000)
compression, compressed = maybe_compress(mv)
if compression:
assert len(compressed) < len(mv)
@pytest.mark.skip
def test_dont_compress_uncompressable_data():
blosc = pytest.importorskip("blosc")
x = np.random.randint(0, 255, size=100000).astype("uint8")
header, [data] = serialize(x)
assert "compression" not in header
assert data == x.data
x = np.ones(1000000)
header, [data] = serialize(x)
assert header["compression"] == ["blosc"]
assert data != x.data
x = np.ones(100)
header, [data] = serialize(x)
assert "compression" not in header
if isinstance(data, memoryview):
assert data.obj.ctypes.data == x.ctypes.data
@gen_cluster(client=True, timeout=60)
def test_dumps_large_blosc(c, s, a, b):
x = c.submit(np.ones, BIG_BYTES_SHARD_SIZE * 2, dtype="u1")
result = yield x
@pytest.mark.skipif(sys.version_info[0] < 3, reason="numpy doesnt use memoryviews")
def test_compression_takes_advantage_of_itemsize():
pytest.importorskip("lz4")
blosc = pytest.importorskip("blosc")
x = np.arange(1000000, dtype="i8")
assert len(blosc.compress(x.data, typesize=8)) < len(
blosc.compress(x.data, typesize=1)
)
_, a = serialize(x)
aa = [maybe_compress(frame)[1] for frame in a]
_, b = serialize(x.view("u1"))
bb = [maybe_compress(frame)[1] for frame in b]
assert sum(map(nbytes, aa)) < sum(map(nbytes, bb))
def test_large_numpy_array():
x = np.ones((100000000,), dtype="u4")
header, frames = serialize(x)
assert sum(header["lengths"]) == sum(map(nbytes, frames))
@pytest.mark.parametrize(
"x",
[
np.broadcast_to(np.arange(10), (20, 10)), # Some strides are 0
np.broadcast_to(1, (3, 4, 2)), # All strides are 0
np.broadcast_to(np.arange(100)[:1], 5), # x.base is larger than x
np.broadcast_to(np.arange(5), (4, 5))[:, ::-1],
],
)
@pytest.mark.parametrize("writeable", [True, False])
def test_zero_strided_numpy_array(x, writeable):
assert 0 in x.strides
x.setflags(write=writeable)
header, frames = serialize(x)
y = deserialize(header, frames)
np.testing.assert_equal(x, y)
# Ensure we transmit fewer bytes than the full array
assert sum(map(nbytes, frames)) < x.nbytes
# Ensure both x and y are have same write flag
assert x.flags.writeable == y.flags.writeable
def test_non_zero_strided_array():
x = np.arange(10)
header, frames = serialize(x)
assert "broadcast_to" not in header
assert sum(map(nbytes, frames)) == x.nbytes
def test_serialize_writeable_array_readonly_base_object():
# Regression test for https://github.com/dask/distributed/issues/3252
x = np.arange(3)
# Create array which doesn't own it's own memory
y = np.broadcast_to(x, (3, 3))
# Make y writeable and it's base object (x) read-only
y.setflags(write=True)
x.setflags(write=False)
# Serialize / deserialize y
z = deserialize(*serialize(y))
np.testing.assert_equal(z, y)
# Ensure z and y have the same flags (including WRITEABLE)
assert z.flags == y.flags | distributed/protocol/tests/test_numpy.py | import sys
from zlib import crc32
import numpy as np
import pytest
from distributed.protocol import (
serialize,
deserialize,
decompress,
dumps,
loads,
to_serialize,
msgpack,
)
from distributed.protocol.utils import BIG_BYTES_SHARD_SIZE
from distributed.protocol.numpy import itemsize
from distributed.protocol.compression import maybe_compress
from distributed.system import MEMORY_LIMIT
from distributed.utils import tmpfile, nbytes
from distributed.utils_test import gen_cluster
def test_serialize():
x = np.ones((5, 5))
header, frames = serialize(x)
assert header["type"]
assert len(frames) == 1
if "compression" in header:
frames = decompress(header, frames)
result = deserialize(header, frames)
assert (result == x).all()
@pytest.mark.parametrize(
"x",
[
np.ones(5),
np.array(5),
np.random.random((5, 5)),
np.random.random((5, 5))[::2, :],
np.random.random((5, 5))[:, ::2],
np.asfortranarray(np.random.random((5, 5))),
np.asfortranarray(np.random.random((5, 5)))[::2, :],
np.asfortranarray(np.random.random((5, 5)))[:, ::2],
np.random.random(5).astype("f4"),
np.random.random(5).astype(">i8"),
np.random.random(5).astype("<i8"),
np.arange(5).astype("M8[us]"),
np.arange(5).astype("M8[ms]"),
np.arange(5).astype("m8"),
np.arange(5).astype("m8[s]"),
np.arange(5).astype("c16"),
np.arange(5).astype("c8"),
np.array([True, False, True]),
np.ones(shape=5, dtype=[("a", "i4"), ("b", "M8[us]")]),
np.array(["abc"], dtype="S3"),
np.array(["abc"], dtype="U3"),
np.array(["abc"], dtype=object),
np.ones(shape=(5,), dtype=("f8", 32)),
np.ones(shape=(5,), dtype=[("x", "f8", 32)]),
np.ones(shape=(5,), dtype=np.dtype([("a", "i1"), ("b", "f8")], align=False)),
np.ones(shape=(5,), dtype=np.dtype([("a", "i1"), ("b", "f8")], align=True)),
np.ones(shape=(5,), dtype=np.dtype([("a", "m8[us]")], align=False)),
# this dtype fails unpickling
np.ones(shape=(5,), dtype=np.dtype([("a", "m8")], align=False)),
np.array([(1, "abc")], dtype=[("x", "i4"), ("s", object)]),
np.zeros(5000, dtype=[("x%d" % i, "<f8") for i in range(4)]),
np.zeros(5000, dtype="S32"),
np.zeros((1, 1000, 1000)),
np.arange(12)[::2], # non-contiguous array
np.ones(shape=(5, 6)).astype(dtype=[("total", "<f8"), ("n", "<f8")]),
np.broadcast_to(np.arange(3), shape=(10, 3)), # zero-strided array
],
)
def test_dumps_serialize_numpy(x):
header, frames = serialize(x)
if "compression" in header:
frames = decompress(header, frames)
buffer_interface = memoryview
for frame in frames:
assert isinstance(frame, (bytes, buffer_interface))
y = deserialize(header, frames)
np.testing.assert_equal(x, y)
if x.flags.c_contiguous or x.flags.f_contiguous:
assert x.strides == y.strides
@pytest.mark.parametrize(
"x",
[
np.ma.masked_array([5, 6], mask=[True, False], fill_value=10, dtype="i4"),
np.ma.masked_array([5.0, 6.0], mask=[True, False], fill_value=10, dtype="f4"),
np.ma.masked_array(
[5.0, 6.0], mask=[True, False], fill_value=np.nan, dtype="f8"
),
np.ma.masked_array(
[5.0, 6.0], mask=np.ma.nomask, fill_value=np.nan, dtype="f8"
),
np.ma.masked_array(
[True, False], mask=np.ma.nomask, fill_value=True, dtype="bool"
),
np.ma.masked_array(["a", "b"], mask=[True, False], fill_value="c", dtype="O"),
],
)
def test_serialize_numpy_ma_masked_array(x):
(y,) = loads(dumps([to_serialize(x)]))
assert x.data.dtype == y.data.dtype
np.testing.assert_equal(x.data, y.data)
np.testing.assert_equal(x.mask, y.mask)
np.testing.assert_equal(x.fill_value, y.fill_value)
def test_serialize_numpy_ma_masked():
(y,) = loads(dumps([to_serialize(np.ma.masked)]))
assert y is np.ma.masked
def test_dumps_serialize_numpy_custom_dtype():
import builtins
test_rational = pytest.importorskip("numpy.core.test_rational")
rational = test_rational.rational
try:
builtins.rational = (
rational # Work around https://github.com/numpy/numpy/issues/9160
)
x = np.array([1], dtype=rational)
header, frames = serialize(x)
y = deserialize(header, frames)
np.testing.assert_equal(x, y)
finally:
del builtins.rational
def test_memmap():
with tmpfile("npy") as fn:
with open(fn, "wb") as f: # touch file
pass
x = np.memmap(fn, shape=(5, 5), dtype="i4", mode="readwrite")
x[:] = 5
header, frames = serialize(x)
if "compression" in header:
frames = decompress(header, frames)
y = deserialize(header, frames)
np.testing.assert_equal(x, y)
@pytest.mark.slow
def test_dumps_serialize_numpy_large():
if MEMORY_LIMIT < 2e9:
pytest.skip("insufficient memory")
x = np.random.random(size=int(BIG_BYTES_SHARD_SIZE * 2 // 8)).view("u1")
assert x.nbytes == BIG_BYTES_SHARD_SIZE * 2
frames = dumps([to_serialize(x)])
dtype, shape = x.dtype, x.shape
checksum = crc32(x)
del x
[y] = loads(frames)
assert (y.dtype, y.shape) == (dtype, shape)
assert crc32(y) == checksum, "Arrays are unequal"
@pytest.mark.parametrize(
"dt,size",
[
("f8", 8),
("i4", 4),
("c16", 16),
("b", 1),
("S3", 3),
("M8[us]", 8),
("M8[s]", 8),
("U3", 12),
([("a", "i4"), ("b", "f8")], 12),
(("i4", 100), 4),
([("a", "i4", 100)], 8),
([("a", "i4", 20), ("b", "f8")], 20 * 4 + 8),
([("a", "i4", 200), ("b", "f8")], 8),
],
)
def test_itemsize(dt, size):
assert itemsize(np.dtype(dt)) == size
@pytest.mark.skipif(sys.version_info[0] < 3, reason="numpy doesnt use memoryviews")
def test_compress_numpy():
pytest.importorskip("lz4")
x = np.ones(10000000, dtype="i4")
frames = dumps({"x": to_serialize(x)})
assert sum(map(nbytes, frames)) < x.nbytes
header = msgpack.loads(frames[2], raw=False, use_list=False)
try:
import blosc # noqa: F401
except ImportError:
pass
else:
assert all(c == "blosc" for c in header["headers"][("x",)]["compression"])
def test_compress_memoryview():
mv = memoryview(b"0" * 1000000)
compression, compressed = maybe_compress(mv)
if compression:
assert len(compressed) < len(mv)
@pytest.mark.skip
def test_dont_compress_uncompressable_data():
blosc = pytest.importorskip("blosc")
x = np.random.randint(0, 255, size=100000).astype("uint8")
header, [data] = serialize(x)
assert "compression" not in header
assert data == x.data
x = np.ones(1000000)
header, [data] = serialize(x)
assert header["compression"] == ["blosc"]
assert data != x.data
x = np.ones(100)
header, [data] = serialize(x)
assert "compression" not in header
if isinstance(data, memoryview):
assert data.obj.ctypes.data == x.ctypes.data
@gen_cluster(client=True, timeout=60)
def test_dumps_large_blosc(c, s, a, b):
x = c.submit(np.ones, BIG_BYTES_SHARD_SIZE * 2, dtype="u1")
result = yield x
@pytest.mark.skipif(sys.version_info[0] < 3, reason="numpy doesnt use memoryviews")
def test_compression_takes_advantage_of_itemsize():
pytest.importorskip("lz4")
blosc = pytest.importorskip("blosc")
x = np.arange(1000000, dtype="i8")
assert len(blosc.compress(x.data, typesize=8)) < len(
blosc.compress(x.data, typesize=1)
)
_, a = serialize(x)
aa = [maybe_compress(frame)[1] for frame in a]
_, b = serialize(x.view("u1"))
bb = [maybe_compress(frame)[1] for frame in b]
assert sum(map(nbytes, aa)) < sum(map(nbytes, bb))
def test_large_numpy_array():
x = np.ones((100000000,), dtype="u4")
header, frames = serialize(x)
assert sum(header["lengths"]) == sum(map(nbytes, frames))
@pytest.mark.parametrize(
"x",
[
np.broadcast_to(np.arange(10), (20, 10)), # Some strides are 0
np.broadcast_to(1, (3, 4, 2)), # All strides are 0
np.broadcast_to(np.arange(100)[:1], 5), # x.base is larger than x
np.broadcast_to(np.arange(5), (4, 5))[:, ::-1],
],
)
@pytest.mark.parametrize("writeable", [True, False])
def test_zero_strided_numpy_array(x, writeable):
assert 0 in x.strides
x.setflags(write=writeable)
header, frames = serialize(x)
y = deserialize(header, frames)
np.testing.assert_equal(x, y)
# Ensure we transmit fewer bytes than the full array
assert sum(map(nbytes, frames)) < x.nbytes
# Ensure both x and y are have same write flag
assert x.flags.writeable == y.flags.writeable
def test_non_zero_strided_array():
x = np.arange(10)
header, frames = serialize(x)
assert "broadcast_to" not in header
assert sum(map(nbytes, frames)) == x.nbytes
def test_serialize_writeable_array_readonly_base_object():
# Regression test for https://github.com/dask/distributed/issues/3252
x = np.arange(3)
# Create array which doesn't own it's own memory
y = np.broadcast_to(x, (3, 3))
# Make y writeable and it's base object (x) read-only
y.setflags(write=True)
x.setflags(write=False)
# Serialize / deserialize y
z = deserialize(*serialize(y))
np.testing.assert_equal(z, y)
# Ensure z and y have the same flags (including WRITEABLE)
assert z.flags == y.flags | 0.423816 | 0.49231 |
import collections
import numpy as np
import os
import torch
import inference_util
import sis_util
from sufficient_input_subsets import sis
# Function to sort filenames by image index in path.
SR_SORT = lambda s: int(os.path.basename(s).split('_')[-1].split('.')[0])
LoadSISResults = collections.namedtuple(
'LoadSISResults',
[
'sis_results',
'sis_image_idxs',
'sis_pred_class',
'sis_is_correct_class',
'sis_masked_images',
'original_confidences',
],
)
def backselect_mask_from_sis_result(sis_result, features_to_keep):
backselect_mask = np.zeros(sis_result.mask.shape, dtype=bool)
backselect_mask[sis._transform_index_array_into_indexer(
sis_result.ordering_over_entire_backselect[-features_to_keep:])] = True
return backselect_mask
def find_sis_from_backselect_result(sis_result, threshold):
# Assumes SIS exists (initial prediction >= threshold).
backselect_stack = list(zip(
sis_result.ordering_over_entire_backselect,
sis_result.values_over_entire_backselect,
))
sis_idxs = sis._find_sis_from_backselect(backselect_stack, threshold)
mask = ~(sis.make_empty_boolean_mask(sis_result.mask.shape))
mask[sis._transform_index_array_into_indexer(sis_idxs)] = True
new_sis_result = sis.SISResult(
sis=np.array(sis_idxs, dtype=np.int_),
ordering_over_entire_backselect=np.array(
sis_result.ordering_over_entire_backselect, dtype=np.int_),
values_over_entire_backselect=np.array(
sis_result.values_over_entire_backselect, dtype=np.float_),
mask=mask,
)
return new_sis_result
def load_sis_results(dataset, dataset_name, model, sis_results_dir,
fully_masked_image, sis_threshold, max_num=None):
"""Load data and create masks and masked images."""
sis_results = []
sis_image_idxs = []
sis_pred_class = []
sis_is_correct_class = []
sis_masked_images = []
original_confidences = []
num_images = len(dataset)
if max_num:
num_images = min(max_num, len(dataset))
for i in range(num_images):
image, label = dataset[i]
# Check if original prediction >= threshold.
original_preds = inference_util.predict(
model, image.unsqueeze(0).cuda(), add_softmax=True)
original_confidence = float(original_preds.max())
original_label = int(original_preds.argmax())
if original_confidence < sis_threshold:
continue # No SIS exists.
# Compute SIS from backselect data.
sis_file = os.path.join(
sis_results_dir, '%s_%d.npz' % (dataset_name, i))
backselect_sr = sis_util.load_sis_result(sis_file)
sis_result = find_sis_from_backselect_result(
backselect_sr, sis_threshold)
sis_masked_image = sis.produce_masked_inputs(
image.numpy(), fully_masked_image, [sis_result.mask])[0]
sis_results.append(sis_result)
sis_image_idxs.append(i)
sis_pred_class.append(original_label)
sis_is_correct_class.append((original_label == label))
sis_masked_images.append(sis_masked_image)
original_confidences.append(original_confidence)
sis_image_idxs = np.array(sis_image_idxs)
sis_pred_class = np.array(sis_pred_class)
sis_is_correct_class = np.array(sis_is_correct_class)
sis_masked_images = np.array(sis_masked_images)
original_confidences = np.array(original_confidences)
return LoadSISResults(
sis_results=sis_results,
sis_image_idxs=sis_image_idxs,
sis_pred_class=sis_pred_class,
sis_is_correct_class=sis_is_correct_class,
sis_masked_images=sis_masked_images,
original_confidences=original_confidences,
)
def load_backselect_subsets(dataset, dataset_name, pixels_to_keep,
sis_results_dir, fully_masked_image, max_num=None):
bs_masks = []
bs_masked_images = []
num_images = len(dataset)
if max_num:
num_images = min(max_num, len(dataset))
for i in range(num_images):
image, _ = dataset[i]
sis_file = os.path.join(
sis_results_dir, '%s_%d.npz' % (dataset_name, i))
sr = sis_util.load_sis_result(sis_file)
bs_mask = backselect_mask_from_sis_result(sr, pixels_to_keep)
img_masked = sis.produce_masked_inputs(
image.numpy(), fully_masked_image, [bs_mask])[0]
bs_masks.append(bs_mask)
bs_masked_images.append(img_masked)
bs_masks = np.array(bs_masks)
bs_masked_images = np.array(bs_masked_images)
return bs_masks, bs_masked_images | sis_analysis_util.py |
import collections
import numpy as np
import os
import torch
import inference_util
import sis_util
from sufficient_input_subsets import sis
# Function to sort filenames by image index in path.
SR_SORT = lambda s: int(os.path.basename(s).split('_')[-1].split('.')[0])
LoadSISResults = collections.namedtuple(
'LoadSISResults',
[
'sis_results',
'sis_image_idxs',
'sis_pred_class',
'sis_is_correct_class',
'sis_masked_images',
'original_confidences',
],
)
def backselect_mask_from_sis_result(sis_result, features_to_keep):
backselect_mask = np.zeros(sis_result.mask.shape, dtype=bool)
backselect_mask[sis._transform_index_array_into_indexer(
sis_result.ordering_over_entire_backselect[-features_to_keep:])] = True
return backselect_mask
def find_sis_from_backselect_result(sis_result, threshold):
# Assumes SIS exists (initial prediction >= threshold).
backselect_stack = list(zip(
sis_result.ordering_over_entire_backselect,
sis_result.values_over_entire_backselect,
))
sis_idxs = sis._find_sis_from_backselect(backselect_stack, threshold)
mask = ~(sis.make_empty_boolean_mask(sis_result.mask.shape))
mask[sis._transform_index_array_into_indexer(sis_idxs)] = True
new_sis_result = sis.SISResult(
sis=np.array(sis_idxs, dtype=np.int_),
ordering_over_entire_backselect=np.array(
sis_result.ordering_over_entire_backselect, dtype=np.int_),
values_over_entire_backselect=np.array(
sis_result.values_over_entire_backselect, dtype=np.float_),
mask=mask,
)
return new_sis_result
def load_sis_results(dataset, dataset_name, model, sis_results_dir,
fully_masked_image, sis_threshold, max_num=None):
"""Load data and create masks and masked images."""
sis_results = []
sis_image_idxs = []
sis_pred_class = []
sis_is_correct_class = []
sis_masked_images = []
original_confidences = []
num_images = len(dataset)
if max_num:
num_images = min(max_num, len(dataset))
for i in range(num_images):
image, label = dataset[i]
# Check if original prediction >= threshold.
original_preds = inference_util.predict(
model, image.unsqueeze(0).cuda(), add_softmax=True)
original_confidence = float(original_preds.max())
original_label = int(original_preds.argmax())
if original_confidence < sis_threshold:
continue # No SIS exists.
# Compute SIS from backselect data.
sis_file = os.path.join(
sis_results_dir, '%s_%d.npz' % (dataset_name, i))
backselect_sr = sis_util.load_sis_result(sis_file)
sis_result = find_sis_from_backselect_result(
backselect_sr, sis_threshold)
sis_masked_image = sis.produce_masked_inputs(
image.numpy(), fully_masked_image, [sis_result.mask])[0]
sis_results.append(sis_result)
sis_image_idxs.append(i)
sis_pred_class.append(original_label)
sis_is_correct_class.append((original_label == label))
sis_masked_images.append(sis_masked_image)
original_confidences.append(original_confidence)
sis_image_idxs = np.array(sis_image_idxs)
sis_pred_class = np.array(sis_pred_class)
sis_is_correct_class = np.array(sis_is_correct_class)
sis_masked_images = np.array(sis_masked_images)
original_confidences = np.array(original_confidences)
return LoadSISResults(
sis_results=sis_results,
sis_image_idxs=sis_image_idxs,
sis_pred_class=sis_pred_class,
sis_is_correct_class=sis_is_correct_class,
sis_masked_images=sis_masked_images,
original_confidences=original_confidences,
)
def load_backselect_subsets(dataset, dataset_name, pixels_to_keep,
sis_results_dir, fully_masked_image, max_num=None):
bs_masks = []
bs_masked_images = []
num_images = len(dataset)
if max_num:
num_images = min(max_num, len(dataset))
for i in range(num_images):
image, _ = dataset[i]
sis_file = os.path.join(
sis_results_dir, '%s_%d.npz' % (dataset_name, i))
sr = sis_util.load_sis_result(sis_file)
bs_mask = backselect_mask_from_sis_result(sr, pixels_to_keep)
img_masked = sis.produce_masked_inputs(
image.numpy(), fully_masked_image, [bs_mask])[0]
bs_masks.append(bs_mask)
bs_masked_images.append(img_masked)
bs_masks = np.array(bs_masks)
bs_masked_images = np.array(bs_masked_images)
return bs_masks, bs_masked_images | 0.538741 | 0.34183 |
from tkinter import ttk
import tkinter
import webbrowser
import requests
from io import BytesIO
from PIL import Image, ImageTk
from core.compat import IS_WINDOWS
from .threadpool import thread_pool as _thread_pool
from urllib import parse
__author__ = 'zz'
class VarGetSetMixin:
def get(self):
return self.var.get()
def set(self, value):
self.var.set(value=value)
class StringVarMixin(VarGetSetMixin):
def __init__(self, *args, **kwargs):
value = kwargs.pop('value', None)
self.var = tkinter.StringVar(value=value)
kwargs.update(textvariable=self.var)
super().__init__(*args, **kwargs)
class HelpTextMixin:
def __init__(self, *args, **kwargs):
self.help_text = kwargs.pop('help_text','')
super().__init__(*args, **kwargs)
class HyperMixin:
def __init__(self, *args, **kwargs):
self._link = kwargs.pop('link', '')
super().__init__(*args, **kwargs)
self.bind('<1>', self._click)
def _click(self, event):
webbrowser.open(self._get_url())
def _get_url(self):
return self._link
class CheckButton(HelpTextMixin, VarGetSetMixin, ttk.Checkbutton):
def __init__(self, master, value=1, **kwargs):
self.var = tkinter.IntVar(value=value)
kwargs.update(variable=self.var)
super().__init__(master, **kwargs)
class Button(HelpTextMixin, ttk.Button):
pass
class Entry(HelpTextMixin, StringVarMixin, ttk.Entry):
pass
class UrlEntry(Entry):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.var.trace('w', self._unquote_text)
def _unquote_text(self, *args):
self.var.set(parse.unquote(self.var.get()))
class NumberEntry(HelpTextMixin, VarGetSetMixin, ttk.Entry):
def __init__(self, master, value=None, **kwargs):
super().__init__(master, **kwargs)
self.var = tkinter.IntVar(value=value)
vcmd = (self.register(self.validating), '%S')
cf = dict()
cf.update(textvariable=self.var)
cf.update(validatecommand=vcmd)
cf.update(validate='key')
self.configure(**cf)
def validating(self, text):
allow = '0123456789'
if all(c in allow for c in text):
return True
return False
class InfoLabel(HelpTextMixin, StringVarMixin, ttk.Label):
pass
class HyperLabel(HyperMixin, ttk.Label):
pass
class ImageFrame(ttk.Frame):
height = 192
width = 192
def __init__(self, *args, **kwargs):
self.image_url = kwargs.pop('image_url', None)
self.image_fp = kwargs.pop('image_fp', None)
self.save_to = kwargs.pop('save_to', None)
kwargs.update({
'height':self.height,
'width': self.width
})
super().__init__(*args, **kwargs)
self.grid_propagate(0)
if self.image_url:
self.label = ttk.Label(self, text='downloading...')
_thread_pool.submit(self.download_image)
elif self.image_fp:
im = self.image_fp
im.thumbnail((self.width, self.height))
im = ImageTk.PhotoImage(im)
self.label = ttk.Label(self, image=im)
self.label.image = im
else:
self.label = ttk.Label(self, text='No Image')
self.label.grid(column=0, row=0, sticky='W')
def download_image(self):
data = requests.get(self.image_url).content
fp = BytesIO(data)
im = Image.open(fp)
im.thumbnail((self.width, self.height))
if self.save_to:
im.save(self.save_to)
im = ImageTk.PhotoImage(im)
self.label.image = im
self.label.configure(image=im)
class ExtraDataComboBox(HelpTextMixin, ttk.Combobox):
def __init__(self, *args, **kwargs):
values_pair = kwargs.pop('values_pair', [])
values = []
self._maps = dict()
for pair in values_pair:
value, extra = pair
self._maps.update({value:extra})
values.append(value)
kwargs.update(values=values)
super().__init__(*args, **kwargs)
def get(self):
value = super().get()
return self._maps[value]
def retags(w, tag):
w.bindtags((tag, ) + w.bindtags())
class BaseRowFrame(ttk.Frame):
_text_width = 44
_text_wraplength = 345
def __init__(self, master, **kwargs):
self.image_url = kwargs.pop('image_url', None)
self.image_fp = kwargs.pop('image_fp', None)
self.text = kwargs.pop('text', '')
self.link = kwargs.pop('link', '')
self.response_num = int(kwargs.pop('response_num', 0))
self.image_save_to = kwargs.pop('image_save_to', None)
kwargs['class_'] = self.__class__.__name__
super().__init__(master, **kwargs)
self.create_widgets()
for w in self.winfo_children():
retags(w, kwargs['class_'])
def create_widgets(self):
self.image_frame = ImageFrame(self, image_url=self.image_url, image_fp=self.image_fp, save_to=self.image_save_to)
self.link_label = HyperLabel(self, text=self.link, link=self.link, cursor='hand2', foreground='blue')
self.text_label = ttk.Label(self, text=self.text, width=self._text_width, wraplength=self._text_wraplength)
self.response_num_label = ttk.Label(self, text='replies: ' + str(self.response_num))
self.image_frame.grid(column=0, row=0, rowspan=2)
self.link_label.grid(column=1, row=0, sticky='N')
self.response_num_label.grid(column=2, row=0, sticky='NW')
self.text_label.grid(column=1, row=1, sticky='NW', columnspan=2)
self.separator = ttk.Separator(self, orient=tkinter.HORIZONTAL)
self.separator.grid(column=0, row=2, columnspan=3, sticky='we', pady=7, padx=25)
@property
def has_image(self):
return True if self.image_url or self.image_fp else False
class BaseFrame(ttk.Frame):
def __init__(self, master=None, **kwargs):
super().__init__(master, **kwargs)
self._init()
def _init(self):
raise NotImplementedError
class RootTk(tkinter.Tk):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.protocol("WM_DELETE_WINDOW", self.on_closing)
def on_closing(self):
_thread_pool.shutdown(wait=False)
self.destroy()
class ScrollbarCanvasMixin(BaseFrame):
canvas_height = 570
canvas_width = 550
def _init(self):
self.canvas = tkinter.Canvas(self, height=self.canvas_height, width=self.canvas_width)
self.frame = ttk.Frame(self.canvas)
self.vbs = ttk.Scrollbar(self, orient='vertical', command=self.canvas.yview)
self.canvas.configure(yscrollcommand=self.vbs.set)
self.vbs.pack(side='right', fill='y')
self.canvas.pack(side='left', fill='both', expand=True)
self.canvas.create_window((0, 0), window=self.frame, anchor='nw', tag='self.frame')
self.frame.bind('<Configure>', self.on_frame_configure)
# self.canvas.bind_all('<MouseWheel>', self._on_mousewheel)
self.canvas.bind('<MouseWheel>', self._on_mousewheel)
self.frame.bind('<MouseWheel>', self._on_mousewheel)
def on_frame_configure(self, e):
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def _on_mousewheel(self, e):
if IS_WINDOWS:
self.canvas.yview_scroll(-int(e.delta/120), 'units')
else:
self.canvas.yview_scroll(-e.delta, 'units')
def bind_class_mousewheel(self, class_name):
self.bind_class(class_name, '<MouseWheel>', self._on_mousewheel) | gui/widgets.py | from tkinter import ttk
import tkinter
import webbrowser
import requests
from io import BytesIO
from PIL import Image, ImageTk
from core.compat import IS_WINDOWS
from .threadpool import thread_pool as _thread_pool
from urllib import parse
__author__ = 'zz'
class VarGetSetMixin:
def get(self):
return self.var.get()
def set(self, value):
self.var.set(value=value)
class StringVarMixin(VarGetSetMixin):
def __init__(self, *args, **kwargs):
value = kwargs.pop('value', None)
self.var = tkinter.StringVar(value=value)
kwargs.update(textvariable=self.var)
super().__init__(*args, **kwargs)
class HelpTextMixin:
def __init__(self, *args, **kwargs):
self.help_text = kwargs.pop('help_text','')
super().__init__(*args, **kwargs)
class HyperMixin:
def __init__(self, *args, **kwargs):
self._link = kwargs.pop('link', '')
super().__init__(*args, **kwargs)
self.bind('<1>', self._click)
def _click(self, event):
webbrowser.open(self._get_url())
def _get_url(self):
return self._link
class CheckButton(HelpTextMixin, VarGetSetMixin, ttk.Checkbutton):
def __init__(self, master, value=1, **kwargs):
self.var = tkinter.IntVar(value=value)
kwargs.update(variable=self.var)
super().__init__(master, **kwargs)
class Button(HelpTextMixin, ttk.Button):
pass
class Entry(HelpTextMixin, StringVarMixin, ttk.Entry):
pass
class UrlEntry(Entry):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.var.trace('w', self._unquote_text)
def _unquote_text(self, *args):
self.var.set(parse.unquote(self.var.get()))
class NumberEntry(HelpTextMixin, VarGetSetMixin, ttk.Entry):
def __init__(self, master, value=None, **kwargs):
super().__init__(master, **kwargs)
self.var = tkinter.IntVar(value=value)
vcmd = (self.register(self.validating), '%S')
cf = dict()
cf.update(textvariable=self.var)
cf.update(validatecommand=vcmd)
cf.update(validate='key')
self.configure(**cf)
def validating(self, text):
allow = '0123456789'
if all(c in allow for c in text):
return True
return False
class InfoLabel(HelpTextMixin, StringVarMixin, ttk.Label):
pass
class HyperLabel(HyperMixin, ttk.Label):
pass
class ImageFrame(ttk.Frame):
height = 192
width = 192
def __init__(self, *args, **kwargs):
self.image_url = kwargs.pop('image_url', None)
self.image_fp = kwargs.pop('image_fp', None)
self.save_to = kwargs.pop('save_to', None)
kwargs.update({
'height':self.height,
'width': self.width
})
super().__init__(*args, **kwargs)
self.grid_propagate(0)
if self.image_url:
self.label = ttk.Label(self, text='downloading...')
_thread_pool.submit(self.download_image)
elif self.image_fp:
im = self.image_fp
im.thumbnail((self.width, self.height))
im = ImageTk.PhotoImage(im)
self.label = ttk.Label(self, image=im)
self.label.image = im
else:
self.label = ttk.Label(self, text='No Image')
self.label.grid(column=0, row=0, sticky='W')
def download_image(self):
data = requests.get(self.image_url).content
fp = BytesIO(data)
im = Image.open(fp)
im.thumbnail((self.width, self.height))
if self.save_to:
im.save(self.save_to)
im = ImageTk.PhotoImage(im)
self.label.image = im
self.label.configure(image=im)
class ExtraDataComboBox(HelpTextMixin, ttk.Combobox):
def __init__(self, *args, **kwargs):
values_pair = kwargs.pop('values_pair', [])
values = []
self._maps = dict()
for pair in values_pair:
value, extra = pair
self._maps.update({value:extra})
values.append(value)
kwargs.update(values=values)
super().__init__(*args, **kwargs)
def get(self):
value = super().get()
return self._maps[value]
def retags(w, tag):
w.bindtags((tag, ) + w.bindtags())
class BaseRowFrame(ttk.Frame):
_text_width = 44
_text_wraplength = 345
def __init__(self, master, **kwargs):
self.image_url = kwargs.pop('image_url', None)
self.image_fp = kwargs.pop('image_fp', None)
self.text = kwargs.pop('text', '')
self.link = kwargs.pop('link', '')
self.response_num = int(kwargs.pop('response_num', 0))
self.image_save_to = kwargs.pop('image_save_to', None)
kwargs['class_'] = self.__class__.__name__
super().__init__(master, **kwargs)
self.create_widgets()
for w in self.winfo_children():
retags(w, kwargs['class_'])
def create_widgets(self):
self.image_frame = ImageFrame(self, image_url=self.image_url, image_fp=self.image_fp, save_to=self.image_save_to)
self.link_label = HyperLabel(self, text=self.link, link=self.link, cursor='hand2', foreground='blue')
self.text_label = ttk.Label(self, text=self.text, width=self._text_width, wraplength=self._text_wraplength)
self.response_num_label = ttk.Label(self, text='replies: ' + str(self.response_num))
self.image_frame.grid(column=0, row=0, rowspan=2)
self.link_label.grid(column=1, row=0, sticky='N')
self.response_num_label.grid(column=2, row=0, sticky='NW')
self.text_label.grid(column=1, row=1, sticky='NW', columnspan=2)
self.separator = ttk.Separator(self, orient=tkinter.HORIZONTAL)
self.separator.grid(column=0, row=2, columnspan=3, sticky='we', pady=7, padx=25)
@property
def has_image(self):
return True if self.image_url or self.image_fp else False
class BaseFrame(ttk.Frame):
def __init__(self, master=None, **kwargs):
super().__init__(master, **kwargs)
self._init()
def _init(self):
raise NotImplementedError
class RootTk(tkinter.Tk):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.protocol("WM_DELETE_WINDOW", self.on_closing)
def on_closing(self):
_thread_pool.shutdown(wait=False)
self.destroy()
class ScrollbarCanvasMixin(BaseFrame):
canvas_height = 570
canvas_width = 550
def _init(self):
self.canvas = tkinter.Canvas(self, height=self.canvas_height, width=self.canvas_width)
self.frame = ttk.Frame(self.canvas)
self.vbs = ttk.Scrollbar(self, orient='vertical', command=self.canvas.yview)
self.canvas.configure(yscrollcommand=self.vbs.set)
self.vbs.pack(side='right', fill='y')
self.canvas.pack(side='left', fill='both', expand=True)
self.canvas.create_window((0, 0), window=self.frame, anchor='nw', tag='self.frame')
self.frame.bind('<Configure>', self.on_frame_configure)
# self.canvas.bind_all('<MouseWheel>', self._on_mousewheel)
self.canvas.bind('<MouseWheel>', self._on_mousewheel)
self.frame.bind('<MouseWheel>', self._on_mousewheel)
def on_frame_configure(self, e):
self.canvas.configure(scrollregion=self.canvas.bbox("all"))
def _on_mousewheel(self, e):
if IS_WINDOWS:
self.canvas.yview_scroll(-int(e.delta/120), 'units')
else:
self.canvas.yview_scroll(-e.delta, 'units')
def bind_class_mousewheel(self, class_name):
self.bind_class(class_name, '<MouseWheel>', self._on_mousewheel) | 0.439026 | 0.067056 |
import pickle
from typing import List
from morphzero.ai.algorithms.hash_policy import HashPolicy, HashPolicyConfig
from morphzero.ai.base import EvaluationResult, TrainingData
from morphzero.common import board_to_string
from morphzero.games.connectfour.game import ConnectFourRules, ConnectFourState
from morphzero.games.genericgomoku.game import GenericGomokuRules
def debug_tic_tac_toe_hash_policy() -> None:
rules = GenericGomokuRules.create_tic_tac_toe_rules()
engine = rules.create_engine()
model = HashPolicy.factory(
"./../models/tic_tac_toe/hash_policy__tr_i10000_s1__hash_lr0.3_ex0.2",
HashPolicyConfig(learning_rate=0, exploration_rate=0, temperature=1.)
)(rules)
state = engine.new_game()
print(board_to_string(state.board))
print(model.evaluate(state))
for move in [3, 6, 4, 5, 0, ]:
state = engine.play_move(state, move)
print(board_to_string(state.board))
print(model.evaluate(state))
def debug_connect4_hash_policy() -> None:
rules = ConnectFourRules.create_default_rules()
engine = rules.create_engine()
model = HashPolicy.factory(
# "./../models/connect4/hash_policy_mcts__tr_i10_s1__hash_lr0.3_ex0__mcts_sim1000_ex1.4_temp1",
"./../models/connect4/hash_policy_mcts__tr_i400_s1__hash_lr0.1_ex0__mcts_sim1000_ex1.4_temp1",
HashPolicyConfig(learning_rate=0, exploration_rate=0, temperature=1.)
)(rules)
def evaluate(state: ConnectFourState, print_result: bool = False) -> EvaluationResult:
evaluation_result = model.evaluate(state)
if print_result:
print(evaluation_result.win_rate)
moves = [
engine.playable_move_for_column(state, column)
for column in range(rules.board_size.columns)
]
move_policy = [
evaluation_result.move_policy[move.move_index] if move else 0.
for move in moves
]
print(", ".join(f"{policy:.4f}" for policy in move_policy))
return evaluation_result
state = engine.new_game()
print(board_to_string(state.board))
evaluate(state, print_result=True)
for move_column in [5, 3, 2, 6]:
move = engine.playable_move_for_column(state, move_column)
assert move
state = engine.play_move(state, move)
print(board_to_string(state.board))
evaluate(state, print_result=True)
def debug_connect4_training_data() -> None:
with open(
"./../models/connect4/hash_policy_mcts__tr_i10_s1__hash_lr0.3_ex0__mcts_sim1000_ex1.4_temp1_training_data",
"rb") as f:
all_training_data: List[TrainingData] = pickle.load(f)
for training_data in all_training_data:
print()
print("NEW TRAINING DATA")
for state, evaluation_result in training_data.data:
print(board_to_string(state.board))
print(evaluation_result.win_rate)
if __name__ == "__main__":
# debug_tic_tac_toe_hash_policy()
debug_connect4_hash_policy()
# debug_connect4_training_data() | morphzero/debug_main.py | import pickle
from typing import List
from morphzero.ai.algorithms.hash_policy import HashPolicy, HashPolicyConfig
from morphzero.ai.base import EvaluationResult, TrainingData
from morphzero.common import board_to_string
from morphzero.games.connectfour.game import ConnectFourRules, ConnectFourState
from morphzero.games.genericgomoku.game import GenericGomokuRules
def debug_tic_tac_toe_hash_policy() -> None:
rules = GenericGomokuRules.create_tic_tac_toe_rules()
engine = rules.create_engine()
model = HashPolicy.factory(
"./../models/tic_tac_toe/hash_policy__tr_i10000_s1__hash_lr0.3_ex0.2",
HashPolicyConfig(learning_rate=0, exploration_rate=0, temperature=1.)
)(rules)
state = engine.new_game()
print(board_to_string(state.board))
print(model.evaluate(state))
for move in [3, 6, 4, 5, 0, ]:
state = engine.play_move(state, move)
print(board_to_string(state.board))
print(model.evaluate(state))
def debug_connect4_hash_policy() -> None:
rules = ConnectFourRules.create_default_rules()
engine = rules.create_engine()
model = HashPolicy.factory(
# "./../models/connect4/hash_policy_mcts__tr_i10_s1__hash_lr0.3_ex0__mcts_sim1000_ex1.4_temp1",
"./../models/connect4/hash_policy_mcts__tr_i400_s1__hash_lr0.1_ex0__mcts_sim1000_ex1.4_temp1",
HashPolicyConfig(learning_rate=0, exploration_rate=0, temperature=1.)
)(rules)
def evaluate(state: ConnectFourState, print_result: bool = False) -> EvaluationResult:
evaluation_result = model.evaluate(state)
if print_result:
print(evaluation_result.win_rate)
moves = [
engine.playable_move_for_column(state, column)
for column in range(rules.board_size.columns)
]
move_policy = [
evaluation_result.move_policy[move.move_index] if move else 0.
for move in moves
]
print(", ".join(f"{policy:.4f}" for policy in move_policy))
return evaluation_result
state = engine.new_game()
print(board_to_string(state.board))
evaluate(state, print_result=True)
for move_column in [5, 3, 2, 6]:
move = engine.playable_move_for_column(state, move_column)
assert move
state = engine.play_move(state, move)
print(board_to_string(state.board))
evaluate(state, print_result=True)
def debug_connect4_training_data() -> None:
with open(
"./../models/connect4/hash_policy_mcts__tr_i10_s1__hash_lr0.3_ex0__mcts_sim1000_ex1.4_temp1_training_data",
"rb") as f:
all_training_data: List[TrainingData] = pickle.load(f)
for training_data in all_training_data:
print()
print("NEW TRAINING DATA")
for state, evaluation_result in training_data.data:
print(board_to_string(state.board))
print(evaluation_result.win_rate)
if __name__ == "__main__":
# debug_tic_tac_toe_hash_policy()
debug_connect4_hash_policy()
# debug_connect4_training_data() | 0.579043 | 0.323113 |
import tensorflow as tf
from keras.callbacks import TensorBoard
import time
import os
import io
class TensorBoardColab:
def __init__(self, port=6006, graph_path='./Graph', startup_waiting_time=8):
self.port = port
self.graph_path = graph_path
self.writer = None
self.deep_writers = {}
get_ipython().system_raw('npm i -s -q --unsafe-perm -g ngrok') #sudo npm i -s -q --unsafe-perm -g ngrok
setup_passed = False
retry_count = 0
sleep_time = startup_waiting_time / 3.0
while not setup_passed:
get_ipython().system_raw('kill -9 $(sudo lsof -t -i:%d)' % port)
get_ipython().system_raw('rm -Rf ' + graph_path)
print('Wait for %d seconds...' % startup_waiting_time)
time.sleep(sleep_time)
get_ipython().system_raw('tensorboard --logdir %s --host 0.0.0.0 --port %d &' % (graph_path, port))
time.sleep(sleep_time)
get_ipython().system_raw('ngrok http %d &' % port)
time.sleep(sleep_time)
try:
tensorboard_link = get_ipython().getoutput(
'curl -s http://localhost:4040/api/tunnels | python3 -c "import sys, json; print(json.load(sys.stdin))"')[
0]
tensorboard_link = eval(tensorboard_link)['tunnels'][0]['public_url']
setup_passed = True
except:
setup_passed = False
retry_count += 1
print('Initialization failed, retry again (%d)' % retry_count)
print('\n')
print("TensorBoard link:")
print(tensorboard_link)
def get_graph_path(self):
return self.graph_path
def get_writer(self):
if self.writer is None:
self.writer = tf.summary.FileWriter(self.graph_path)
return self.writer
def get_deep_writers(self, name):
if not (name in self.deep_writers):
log_path = os.path.join(self.graph_path, name)
self.deep_writers[name] = tf.summary.FileWriter(log_path)
return self.deep_writers[name]
def save_image(self, title, image):
image_path = os.path.join(self.graph_path, 'images')
summary_op = tf.summary.image(title, image)
with tf.Session() as sess:
summary = sess.run(summary_op)
writer = tf.summary.FileWriter(image_path)
writer.add_summary(summary)
writer.close()
def save_value(self, graph_name, line_name, epoch, value):
summary = tf.Summary()
summary_value = summary.value.add()
summary_value.simple_value = value
summary_value.tag = graph_name
self.get_deep_writers(line_name).add_summary(summary, epoch)
def flush_line(self, line_name):
self.get_deep_writers(line_name).flush()
def close(self):
if self.writer is not None:
self.writer.close()
self.writer = None
for key in self.deep_writers:
self.deep_writers[key].close()
self.deep_writers = {} | quickcnn/setup_tbc.py | import tensorflow as tf
from keras.callbacks import TensorBoard
import time
import os
import io
class TensorBoardColab:
def __init__(self, port=6006, graph_path='./Graph', startup_waiting_time=8):
self.port = port
self.graph_path = graph_path
self.writer = None
self.deep_writers = {}
get_ipython().system_raw('npm i -s -q --unsafe-perm -g ngrok') #sudo npm i -s -q --unsafe-perm -g ngrok
setup_passed = False
retry_count = 0
sleep_time = startup_waiting_time / 3.0
while not setup_passed:
get_ipython().system_raw('kill -9 $(sudo lsof -t -i:%d)' % port)
get_ipython().system_raw('rm -Rf ' + graph_path)
print('Wait for %d seconds...' % startup_waiting_time)
time.sleep(sleep_time)
get_ipython().system_raw('tensorboard --logdir %s --host 0.0.0.0 --port %d &' % (graph_path, port))
time.sleep(sleep_time)
get_ipython().system_raw('ngrok http %d &' % port)
time.sleep(sleep_time)
try:
tensorboard_link = get_ipython().getoutput(
'curl -s http://localhost:4040/api/tunnels | python3 -c "import sys, json; print(json.load(sys.stdin))"')[
0]
tensorboard_link = eval(tensorboard_link)['tunnels'][0]['public_url']
setup_passed = True
except:
setup_passed = False
retry_count += 1
print('Initialization failed, retry again (%d)' % retry_count)
print('\n')
print("TensorBoard link:")
print(tensorboard_link)
def get_graph_path(self):
return self.graph_path
def get_writer(self):
if self.writer is None:
self.writer = tf.summary.FileWriter(self.graph_path)
return self.writer
def get_deep_writers(self, name):
if not (name in self.deep_writers):
log_path = os.path.join(self.graph_path, name)
self.deep_writers[name] = tf.summary.FileWriter(log_path)
return self.deep_writers[name]
def save_image(self, title, image):
image_path = os.path.join(self.graph_path, 'images')
summary_op = tf.summary.image(title, image)
with tf.Session() as sess:
summary = sess.run(summary_op)
writer = tf.summary.FileWriter(image_path)
writer.add_summary(summary)
writer.close()
def save_value(self, graph_name, line_name, epoch, value):
summary = tf.Summary()
summary_value = summary.value.add()
summary_value.simple_value = value
summary_value.tag = graph_name
self.get_deep_writers(line_name).add_summary(summary, epoch)
def flush_line(self, line_name):
self.get_deep_writers(line_name).flush()
def close(self):
if self.writer is not None:
self.writer.close()
self.writer = None
for key in self.deep_writers:
self.deep_writers[key].close()
self.deep_writers = {} | 0.335024 | 0.117218 |
import sys
from core.utils import get_media_from_email, month_range
from django.conf import settings
from django.contrib.auth.decorators import login_required, user_passes_test
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect
from django.shortcuts import render
from django.utils import timezone
from forms import GizaEditForm
from models import Giza
reload(sys)
sys.setdefaultencoding('utf-8')
@login_required
def show_all_giza(request):
"""Function"""
db = Giza.objects.order_by('belongto', 'name').all()
template = "giza/showgiza.html"
return render(
request,
template,
{
'db': db,
'count': db.count(),
}
)
def show_giza(request):
"""Function"""
now = timezone.now()
startyear = settings.RANKING_START_YEAR
startmonth = settings.RANKING_START_MONTH
nowyear = now.year
nowmonth = now.month
month_list = []
for i in month_range(startmonth, startyear, nowmonth, nowyear):
month_list.append(i)
template = "giza/showgiza.html"
return render(
request,
template,
{
'count': 0,
'lists': reversed(month_list),
})
def search_giza(request, search_type, search_word):
"""Function"""
word = search_word.rstrip()
template = "giza/showgiza.html"
email = ''
if search_type == "name":
db = Giza.objects.filter(name__iexact=word).order_by('belongto', 'name')
elif search_type == "email":
db = Giza.objects.filter(email__icontains=word).order_by('belongto', 'name')
if not db.exists():
email = search_word
elif search_type == "belongto":
db = Giza.objects.filter(belongto__icontains=word).order_by('belongto', 'name')
elif search_type == "twitter":
db = Giza.objects.filter(twitter__icontains=word).order_by('belongto', 'name')
elif search_type == "facebook":
db = Giza.objects.filter(facebook__icontains=word).order_by('belongto', 'name')
else:
return render(
request,
template,
{
'count': 0,
}
)
return render(
request,
template,
{
'db': db,
'count': db.count(),
'email': email,
'search_type': search_type,
}
)
@login_required
def new_giza(request, email=''):
"""Function"""
if request.method == "POST":
editform = GizaEditForm(request.POST, request.FILES)
if editform.is_valid():
giza = editform.save(commit=False)
giza.user = request.user
giza_check = Giza.objects.filter(email__iexact=giza.email)
if (giza_check):
return HttpResponse(u"이미 존재합니다.<br><a href='javascript:history.back()''>돌아가기</a>")
giza.save()
print giza.get_serach_url(giza.email)
return redirect(giza.get_serach_url(giza.email))
elif request.method == "GET":
editform = GizaEditForm()
media = get_media_from_email(request, email)
return render(
request,
"giza/editgiza.html",
{
'form': editform,
'edituser': '',
'email': email,
'media': media
}
)
@login_required
def edit_giza(request, id):
"""Function"""
giza = get_object_or_404(Giza, pk=id)
referer = ''
if request.method == "POST":
editform = GizaEditForm(request.POST, request.FILES, instance=giza)
if editform.is_valid():
giza = editform.save(commit=False)
giza.user = request.user
giza.save()
nexturl = request.POST['next']
if nexturl and 'edit' not in nexturl:
return HttpResponseRedirect(nexturl)
return redirect(giza.get_absolute_url())
elif request.method == "GET":
editform = GizaEditForm(instance=giza)
referer = request.META.get('HTTP_REFERER')
return render(
request,
"giza/editgiza.html",
{
'form': editform,
'edituser': giza.user,
'id': id,
'next': referer,
}
)
@user_passes_test(lambda u: u.is_superuser)
def delete_giza(request, id):
"""Function"""
giza = get_object_or_404(Giza, pk=id)
giza.delete()
return redirect(giza.get_absolute_url()) | giza/views.py |
import sys
from core.utils import get_media_from_email, month_range
from django.conf import settings
from django.contrib.auth.decorators import login_required, user_passes_test
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect
from django.shortcuts import render
from django.utils import timezone
from forms import GizaEditForm
from models import Giza
reload(sys)
sys.setdefaultencoding('utf-8')
@login_required
def show_all_giza(request):
"""Function"""
db = Giza.objects.order_by('belongto', 'name').all()
template = "giza/showgiza.html"
return render(
request,
template,
{
'db': db,
'count': db.count(),
}
)
def show_giza(request):
"""Function"""
now = timezone.now()
startyear = settings.RANKING_START_YEAR
startmonth = settings.RANKING_START_MONTH
nowyear = now.year
nowmonth = now.month
month_list = []
for i in month_range(startmonth, startyear, nowmonth, nowyear):
month_list.append(i)
template = "giza/showgiza.html"
return render(
request,
template,
{
'count': 0,
'lists': reversed(month_list),
})
def search_giza(request, search_type, search_word):
"""Function"""
word = search_word.rstrip()
template = "giza/showgiza.html"
email = ''
if search_type == "name":
db = Giza.objects.filter(name__iexact=word).order_by('belongto', 'name')
elif search_type == "email":
db = Giza.objects.filter(email__icontains=word).order_by('belongto', 'name')
if not db.exists():
email = search_word
elif search_type == "belongto":
db = Giza.objects.filter(belongto__icontains=word).order_by('belongto', 'name')
elif search_type == "twitter":
db = Giza.objects.filter(twitter__icontains=word).order_by('belongto', 'name')
elif search_type == "facebook":
db = Giza.objects.filter(facebook__icontains=word).order_by('belongto', 'name')
else:
return render(
request,
template,
{
'count': 0,
}
)
return render(
request,
template,
{
'db': db,
'count': db.count(),
'email': email,
'search_type': search_type,
}
)
@login_required
def new_giza(request, email=''):
"""Function"""
if request.method == "POST":
editform = GizaEditForm(request.POST, request.FILES)
if editform.is_valid():
giza = editform.save(commit=False)
giza.user = request.user
giza_check = Giza.objects.filter(email__iexact=giza.email)
if (giza_check):
return HttpResponse(u"이미 존재합니다.<br><a href='javascript:history.back()''>돌아가기</a>")
giza.save()
print giza.get_serach_url(giza.email)
return redirect(giza.get_serach_url(giza.email))
elif request.method == "GET":
editform = GizaEditForm()
media = get_media_from_email(request, email)
return render(
request,
"giza/editgiza.html",
{
'form': editform,
'edituser': '',
'email': email,
'media': media
}
)
@login_required
def edit_giza(request, id):
"""Function"""
giza = get_object_or_404(Giza, pk=id)
referer = ''
if request.method == "POST":
editform = GizaEditForm(request.POST, request.FILES, instance=giza)
if editform.is_valid():
giza = editform.save(commit=False)
giza.user = request.user
giza.save()
nexturl = request.POST['next']
if nexturl and 'edit' not in nexturl:
return HttpResponseRedirect(nexturl)
return redirect(giza.get_absolute_url())
elif request.method == "GET":
editform = GizaEditForm(instance=giza)
referer = request.META.get('HTTP_REFERER')
return render(
request,
"giza/editgiza.html",
{
'form': editform,
'edituser': giza.user,
'id': id,
'next': referer,
}
)
@user_passes_test(lambda u: u.is_superuser)
def delete_giza(request, id):
"""Function"""
giza = get_object_or_404(Giza, pk=id)
giza.delete()
return redirect(giza.get_absolute_url()) | 0.351534 | 0.153232 |
import matplotlib.pyplot as plt
import cPickle
import matplotlib as mpl
from numpy import *
colorbar = ['blue', 'green', 'red', 'yellow']
def plot(data, datay):
for ele, y in zip(data, datay):
plt.text(ele[0], ele[1], str(y), color = colorbar[y])
plt.xlim([-2, 2]);plt.ylim([-2, 2])
def plot_all(self, bound = 2):
x, y = meshgrid(linspace(-bound, bound, 100),linspace(-bound, bound, 100))
data = concatenate([x.reshape(-1, 1), y.reshape(-1, 1)], 1)
pred = self.pred(data).reshape(x.shape)
cmap = mpl.colors.LinearSegmentedColormap.from_list('cmap', colorbar, 256)
plt.imshow(pred, interpolation = None, cmap = cmap)
if __name__ == '__main__':
plot_all(1)
size = 10000
data = random.uniform(-2, 2, size = (size, 2))
datay = []
rule = 'complex'
if rule == 'complex':
for (x, y) in data:
if y > -x+2 or y < -x-2:
plt.text(x, y, 'B', color = 'black')
datay.append(1)
elif y < -1 and x > 1:
plt.text(x, y, 'C', color = 'red')
datay.append(2)
elif x ** 2 + y ** 2 < 1:
plt.text(x, y, 'A', color = 'blue')
datay.append(0)
else:
plt.text(x, y, 'D', color = 'green')
datay.append(3)
else:
for (x, y) in data:
if y > 0 and x > 0:
plt.text(x, y, 'B', color = 'black')
datay.append(1)
elif y > 0 and x < 0:
plt.text(x, y, 'C', color = 'red')
datay.append(2)
elif y < 0 and x < 0:
plt.text(x, y, 'A', color = 'blue')
datay.append(0)
else:
plt.text(x, y, 'D', color = 'green')
datay.append(3)
plt.xlim([-2, 2])
plt.ylim([-2, 2])
plt.show()
for i in range(4):
print '%d: %d' % (i, datay.count(i))
cPickle.dump((array(data), array(datay)), open('data.dat', 'wb'), True) | ML/co-evaluate/createData.py | import matplotlib.pyplot as plt
import cPickle
import matplotlib as mpl
from numpy import *
colorbar = ['blue', 'green', 'red', 'yellow']
def plot(data, datay):
for ele, y in zip(data, datay):
plt.text(ele[0], ele[1], str(y), color = colorbar[y])
plt.xlim([-2, 2]);plt.ylim([-2, 2])
def plot_all(self, bound = 2):
x, y = meshgrid(linspace(-bound, bound, 100),linspace(-bound, bound, 100))
data = concatenate([x.reshape(-1, 1), y.reshape(-1, 1)], 1)
pred = self.pred(data).reshape(x.shape)
cmap = mpl.colors.LinearSegmentedColormap.from_list('cmap', colorbar, 256)
plt.imshow(pred, interpolation = None, cmap = cmap)
if __name__ == '__main__':
plot_all(1)
size = 10000
data = random.uniform(-2, 2, size = (size, 2))
datay = []
rule = 'complex'
if rule == 'complex':
for (x, y) in data:
if y > -x+2 or y < -x-2:
plt.text(x, y, 'B', color = 'black')
datay.append(1)
elif y < -1 and x > 1:
plt.text(x, y, 'C', color = 'red')
datay.append(2)
elif x ** 2 + y ** 2 < 1:
plt.text(x, y, 'A', color = 'blue')
datay.append(0)
else:
plt.text(x, y, 'D', color = 'green')
datay.append(3)
else:
for (x, y) in data:
if y > 0 and x > 0:
plt.text(x, y, 'B', color = 'black')
datay.append(1)
elif y > 0 and x < 0:
plt.text(x, y, 'C', color = 'red')
datay.append(2)
elif y < 0 and x < 0:
plt.text(x, y, 'A', color = 'blue')
datay.append(0)
else:
plt.text(x, y, 'D', color = 'green')
datay.append(3)
plt.xlim([-2, 2])
plt.ylim([-2, 2])
plt.show()
for i in range(4):
print '%d: %d' % (i, datay.count(i))
cPickle.dump((array(data), array(datay)), open('data.dat', 'wb'), True) | 0.198763 | 0.563198 |
import json
import logging
from pathlib import Path, WindowsPath
from typing import Optional, Union
from .globals import get_settings_dir, SETTINGS_FILE_NAME, OPEN_VR_DLL, get_data_dir, APPS_STORE_FILE_NAME, get_version, KNOWN_APPS
from .utils import JsonRepr
class AppSettings(JsonRepr):
skip_keys = ['open_vr_fsr_versions', 'open_vr_foveated_versions',
'current_fsr_version', 'current_foveated_version']
backup_created = False
needs_admin = False
previous_version = str()
user_apps = dict()
user_app_counter = len(user_apps.keys())
open_vr_fsr_versions = {
'v0.5': 'd74d3083e3506d83fac0d95520625eab',
'v0.6': '18c46267b042cac7c21a2059786e660c',
'v0.7': 'f3a0706ea3929234a73bdfde58493601',
'v0.8': '68fcb526c619103e4d9775e4fba2b747',
'v0.9': 'ddccc71f8239bf17ead5df1db43eeedb',
'v1.0': 'da03ca34b51587addebd78422f4d5c39',
'v1.1': '628a13f0faae439229237c3b44e5426c',
'v1.2': '2d551d67a642d3edba3e8467b00667cb',
'v1.3': 'ea417d2480b9a285ea9f6a3e9aa703b3',
'v2.0': 'b173ef3e95283c47f840152786d6ebf9',
'v2.1.1': '1f15031338f117ccc8d68a98f71d6b65',
}
open_vr_foveated_versions = {
'v0.1': 'f113aa2bbc9e13603fdc99c3944fcc48',
'v0.2': '51bec8ad9c6860615a71c2449feee780'
}
current_fsr_version = 'v2.1.1'
current_foveated_version = 'v0.2'
# Default plugin path
openvr_fsr_dir: Optional[str] = str(WindowsPath(get_data_dir() / 'openvr_fsr'))
openvr_foveated_dir: Optional[str] = str(WindowsPath(get_data_dir() / 'openvr_foveated'))
def __init__(self):
self.needs_admin = AppSettings.needs_admin
self.backup_created = AppSettings.backup_created
@staticmethod
def _get_settings_file() -> Path:
return get_settings_dir() / SETTINGS_FILE_NAME
@staticmethod
def _get_steam_apps_file() -> Path:
return get_settings_dir() / APPS_STORE_FILE_NAME
@classmethod
def save(cls):
file = cls._get_settings_file()
try:
with open(file.as_posix(), 'w') as f:
# noinspection PyTypeChecker
f.write(json.dumps(cls.to_js_object(cls)))
except Exception as e:
logging.error('Could not save application settings! %s', e)
return False
return True
@classmethod
def load(cls) -> bool:
file = cls._get_settings_file()
try:
if file.exists():
with open(file.as_posix(), 'r') as f:
# -- Load Settings
# noinspection PyTypeChecker
cls.from_js_dict(cls, json.loads(f.read()))
except Exception as e:
logging.error('Could not load application settings! %s', e)
return False
return True
@classmethod
def save_steam_apps(cls, steam_apps: dict):
file = cls._get_steam_apps_file()
try:
with open(file.as_posix(), 'w') as f:
# noinspection PyTypeChecker
f.write(json.dumps(steam_apps))
except Exception as e:
logging.error('Could not store steam apps to file! %s', e)
return False
return True
@classmethod
def load_steam_apps(cls) -> dict:
file = cls._get_steam_apps_file()
if not file.exists():
return dict()
try:
with open(file.as_posix(), 'r') as f:
# noinspection PyTypeChecker
steam_apps = json.load(f)
except Exception as e:
logging.error('Could not load steam apps from file! %s', e)
return dict()
# -- Add Known Apps data
for app_id, entry in steam_apps.items():
if app_id in KNOWN_APPS:
entry.update(KNOWN_APPS[app_id])
return steam_apps
@staticmethod
def update_fsr_dir(fsr_plugin_dir: Union[str, Path]) -> bool:
fsr_plugin_dir = Path(fsr_plugin_dir)
dir_str = str(WindowsPath(fsr_plugin_dir))
try:
if fsr_plugin_dir.exists():
verified = False
for _ in fsr_plugin_dir.glob(OPEN_VR_DLL):
verified = True
break
if not verified:
logging.error('Could not find OpenVR Api Dll in provided directory!')
return False
logging.info('Updating FSR PlugIn Dir: %s', dir_str)
AppSettings.openvr_fsr_dir = dir_str
AppSettings.save()
else:
logging.error('Selected Presets Directory does not exist: %s', fsr_plugin_dir.as_posix())
return False
except Exception as e:
logging.error('Error accessing path: %s', e)
return False
return True | app/app_settings.py | import json
import logging
from pathlib import Path, WindowsPath
from typing import Optional, Union
from .globals import get_settings_dir, SETTINGS_FILE_NAME, OPEN_VR_DLL, get_data_dir, APPS_STORE_FILE_NAME, get_version, KNOWN_APPS
from .utils import JsonRepr
class AppSettings(JsonRepr):
skip_keys = ['open_vr_fsr_versions', 'open_vr_foveated_versions',
'current_fsr_version', 'current_foveated_version']
backup_created = False
needs_admin = False
previous_version = str()
user_apps = dict()
user_app_counter = len(user_apps.keys())
open_vr_fsr_versions = {
'v0.5': 'd74d3083e3506d83fac0d95520625eab',
'v0.6': '18c46267b042cac7c21a2059786e660c',
'v0.7': 'f3a0706ea3929234a73bdfde58493601',
'v0.8': '68fcb526c619103e4d9775e4fba2b747',
'v0.9': 'ddccc71f8239bf17ead5df1db43eeedb',
'v1.0': 'da03ca34b51587addebd78422f4d5c39',
'v1.1': '628a13f0faae439229237c3b44e5426c',
'v1.2': '2d551d67a642d3edba3e8467b00667cb',
'v1.3': 'ea417d2480b9a285ea9f6a3e9aa703b3',
'v2.0': 'b173ef3e95283c47f840152786d6ebf9',
'v2.1.1': '1f15031338f117ccc8d68a98f71d6b65',
}
open_vr_foveated_versions = {
'v0.1': 'f113aa2bbc9e13603fdc99c3944fcc48',
'v0.2': '51bec8ad9c6860615a71c2449feee780'
}
current_fsr_version = 'v2.1.1'
current_foveated_version = 'v0.2'
# Default plugin path
openvr_fsr_dir: Optional[str] = str(WindowsPath(get_data_dir() / 'openvr_fsr'))
openvr_foveated_dir: Optional[str] = str(WindowsPath(get_data_dir() / 'openvr_foveated'))
def __init__(self):
self.needs_admin = AppSettings.needs_admin
self.backup_created = AppSettings.backup_created
@staticmethod
def _get_settings_file() -> Path:
return get_settings_dir() / SETTINGS_FILE_NAME
@staticmethod
def _get_steam_apps_file() -> Path:
return get_settings_dir() / APPS_STORE_FILE_NAME
@classmethod
def save(cls):
file = cls._get_settings_file()
try:
with open(file.as_posix(), 'w') as f:
# noinspection PyTypeChecker
f.write(json.dumps(cls.to_js_object(cls)))
except Exception as e:
logging.error('Could not save application settings! %s', e)
return False
return True
@classmethod
def load(cls) -> bool:
file = cls._get_settings_file()
try:
if file.exists():
with open(file.as_posix(), 'r') as f:
# -- Load Settings
# noinspection PyTypeChecker
cls.from_js_dict(cls, json.loads(f.read()))
except Exception as e:
logging.error('Could not load application settings! %s', e)
return False
return True
@classmethod
def save_steam_apps(cls, steam_apps: dict):
file = cls._get_steam_apps_file()
try:
with open(file.as_posix(), 'w') as f:
# noinspection PyTypeChecker
f.write(json.dumps(steam_apps))
except Exception as e:
logging.error('Could not store steam apps to file! %s', e)
return False
return True
@classmethod
def load_steam_apps(cls) -> dict:
file = cls._get_steam_apps_file()
if not file.exists():
return dict()
try:
with open(file.as_posix(), 'r') as f:
# noinspection PyTypeChecker
steam_apps = json.load(f)
except Exception as e:
logging.error('Could not load steam apps from file! %s', e)
return dict()
# -- Add Known Apps data
for app_id, entry in steam_apps.items():
if app_id in KNOWN_APPS:
entry.update(KNOWN_APPS[app_id])
return steam_apps
@staticmethod
def update_fsr_dir(fsr_plugin_dir: Union[str, Path]) -> bool:
fsr_plugin_dir = Path(fsr_plugin_dir)
dir_str = str(WindowsPath(fsr_plugin_dir))
try:
if fsr_plugin_dir.exists():
verified = False
for _ in fsr_plugin_dir.glob(OPEN_VR_DLL):
verified = True
break
if not verified:
logging.error('Could not find OpenVR Api Dll in provided directory!')
return False
logging.info('Updating FSR PlugIn Dir: %s', dir_str)
AppSettings.openvr_fsr_dir = dir_str
AppSettings.save()
else:
logging.error('Selected Presets Directory does not exist: %s', fsr_plugin_dir.as_posix())
return False
except Exception as e:
logging.error('Error accessing path: %s', e)
return False
return True | 0.617974 | 0.085366 |
from dataclasses import dataclass, field
from typing import Dict, Optional, Tuple, Union
from .chaum_pedersen import ChaumPedersenProof
from .election_object_base import ElectionObjectBase
from .elgamal import ElGamalCiphertext
from .group import ElementModP, ElementModQ
from .logs import log_warning
from .types import BALLOT_ID, CONTEST_ID, GUARDIAN_ID, SELECTION_ID
ELECTION_PUBLIC_KEY = ElementModP
@dataclass
class CiphertextCompensatedDecryptionSelection(ElectionObjectBase):
"""
A compensated fragment of a Guardian's Partial Decryption of a selection generated by an available guardian
"""
guardian_id: GUARDIAN_ID
"""
The Available Guardian that this share belongs to
"""
missing_guardian_id: GUARDIAN_ID
"""
The Missing Guardian for whom this share is calculated on behalf of
"""
description_hash: ElementModQ
"""
The SelectionDescription hash
"""
share: ElementModP
"""
The Share of the decryption of a selection. `M_{i,l} in the spec`
"""
recovery_key: ElementModP
"""
The Recovery Public Key for the missing_guardian that corresponds to the available guardian's share of the secret
"""
proof: ChaumPedersenProof
"""
The Proof that the share was decrypted correctly
"""
ProofOrRecovery = Union[
ChaumPedersenProof, Dict[GUARDIAN_ID, CiphertextCompensatedDecryptionSelection]
]
@dataclass
class CiphertextDecryptionSelection(ElectionObjectBase):
"""
A Guardian's Partial Decryption of a selection. A CiphertextDecryptionSelection
can be generated by a guardian directly, or it can be compensated for by a quoprum of guardians
When the guardian generates this share directly, the `proof` field is populated with
a `chaumPedersen` proof that the decryption share was generated correctly.
When the share is generated on behalf of this guardian by other guardians, the `recovered_parts`
collection is populated with the `CiphertextCompensatedDecryptionSelection` objects generated
by each available guardian.
"""
guardian_id: GUARDIAN_ID
"""
The Available Guardian that this share belongs to
"""
description_hash: ElementModQ
"""
The SelectionDescription hash
"""
share: ElementModP
"""
The Share of the decryption of a selection. `M_i` in the spec
"""
proof: Optional[ChaumPedersenProof] = field(init=True, default=None)
"""
The Proof that the share was decrypted correctly, if the guardian
was available for decryption
"""
recovered_parts: Optional[
Dict[GUARDIAN_ID, CiphertextCompensatedDecryptionSelection]
] = field(init=True, default=None)
"""
the recovered parts of the decryption provided by available guardians,
if the guardian was missing from decryption
"""
def is_valid(
self,
message: ElGamalCiphertext,
election_public_key: ELECTION_PUBLIC_KEY,
extended_base_hash: ElementModQ,
) -> bool:
"""
Verify that this CiphertextDecryptionSelection is valid for a
specific ElGamal key pair, public key, and election context.
:param message: the `ElGamalCiphertext` to compare
:param election_public_key: the `ElementModP Election Public Key for the Guardian
:param extended_base_hash: The `ElementModQ` election extended base hash.
"""
# verify we have a proof or recovered parts
if self.proof is None and self.recovered_parts is None:
log_warning(
f"CiphertextDecryptionSelection is_valid failed for guardian: {self.guardian_id} selection: {self.object_id} with missing data"
)
return False
if self.proof is not None and self.recovered_parts is not None:
log_warning(
f"CiphertextDecryptionSelection is_valid failed for guardian: {self.guardian_id} selection: {self.object_id} cannot have proof and recovery"
)
return False
if self.proof is not None and not self.proof.is_valid(
message,
election_public_key,
self.share,
extended_base_hash,
):
log_warning(
f"CiphertextDecryptionSelection is_valid failed for guardian: {self.guardian_id} selection: {self.object_id} with invalid proof"
)
return False
if self.recovered_parts is not None:
for (
compensating_guardian_id,
part,
) in self.recovered_parts.items():
if not part.proof.is_valid(
message,
part.recovery_key,
part.share,
extended_base_hash,
):
log_warning(
f"CiphertextDecryptionSelection is_valid failed for guardian: {self.guardian_id} selection: {self.object_id} with invalid partial proof"
)
return False
return True
def create_ciphertext_decryption_selection(
object_id: str,
guardian_id: GUARDIAN_ID,
description_hash: ElementModQ,
share: ElementModP,
proof_or_recovery: ProofOrRecovery,
) -> CiphertextDecryptionSelection:
"""
Create a ciphertext decryption selection
:param object_id: Object id
:param guardian_id: Guardian id
:param description_hash: Description hash
:param share: Share
:param proof_or_recovery: Proof or recovery
"""
if isinstance(proof_or_recovery, ChaumPedersenProof):
return CiphertextDecryptionSelection(
object_id, guardian_id, description_hash, share, proof=proof_or_recovery
)
elif isinstance(proof_or_recovery, Dict):
return CiphertextDecryptionSelection(
object_id,
guardian_id,
description_hash,
share,
recovered_parts=proof_or_recovery,
)
else:
log_warning(f"decryption share cannot assign {proof_or_recovery}")
return CiphertextDecryptionSelection(
object_id,
guardian_id,
description_hash,
share,
)
@dataclass
class CiphertextDecryptionContest(ElectionObjectBase):
"""
A Guardian's Partial Decryption of a contest
"""
guardian_id: GUARDIAN_ID
"""
The Available Guardian that this share belongs to
"""
description_hash: ElementModQ
"""
The ContestDescription Hash
"""
selections: Dict[SELECTION_ID, CiphertextDecryptionSelection]
"""
the collection of decryption shares for this contest's selections
"""
@dataclass
class CiphertextCompensatedDecryptionContest(ElectionObjectBase):
"""
A Guardian's Partial Decryption of a contest
"""
guardian_id: GUARDIAN_ID
"""
The Available Guardian that this share belongs to
"""
missing_guardian_id: GUARDIAN_ID
"""
The Missing Guardian for whom this share is calculated on behalf of
"""
description_hash: ElementModQ
"""
The ContestDescription Hash
"""
selections: Dict[SELECTION_ID, CiphertextCompensatedDecryptionSelection]
"""
the collection of decryption shares for this contest's selections
"""
@dataclass
class BallotDecryptionShare:
"""
A Guardian's Partial Decryption Share of a specific ballot (e.g. of a spoiled ballot)
"""
guardian_id: GUARDIAN_ID
"""
The Available Guardian that this share belongs to
"""
public_key: ElementModP
"""
The election public key for the guardian
"""
ballot_id: BALLOT_ID
"""
The Ballot Id that this Decryption Share belongs to
"""
contests: Dict[CONTEST_ID, CiphertextDecryptionContest]
"""
The collection of all contests in the ballot
"""
@dataclass
class CompensatedBallotDecryptionShare:
"""
A Compensated Partial Decryption Share generated by
an available guardian on behalf of a missing guardian
"""
guardian_id: GUARDIAN_ID
"""
The Available Guardian that this share belongs to
"""
missing_guardian_id: GUARDIAN_ID
"""
The Missing Guardian for whom this share is calculated on behalf of
"""
public_key: ElementModP
"""
The election public key for the guardian
"""
ballot_id: BALLOT_ID
"""
The Ballot Id that this Decryption Share belongs to
"""
contests: Dict[CONTEST_ID, CiphertextCompensatedDecryptionContest]
"""
The collection of all contests in the ballot
"""
@dataclass
class TallyDecryptionShare:
"""
A Guardian's Partial Decryption Share of an election tally
"""
guardian_id: GUARDIAN_ID
"""
The Available Guardian that this share belongs to
"""
public_key: ElementModP
"""
The election public key for the guardian
"""
contests: Dict[CONTEST_ID, CiphertextDecryptionContest]
"""
The collection of decryption shares for all contests in the election
"""
spoiled_ballots: Dict[BALLOT_ID, BallotDecryptionShare]
"""
The collection of decryption shares for all spoiled ballots in the election
"""
@dataclass
class CompensatedTallyDecryptionShare:
"""
A Compensated Partial Decryption Share generated by
an available guardian on behalf of a missing guardian
"""
guardian_id: GUARDIAN_ID
"""
The Available Guardian that this share belongs to
"""
missing_guardian_id: GUARDIAN_ID
"""
The Missing Guardian for whom this share is calculated on behalf of
"""
public_key: ElementModP
"""
The election public key for the guardian
"""
contests: Dict[CONTEST_ID, CiphertextCompensatedDecryptionContest]
"""
The collection of decryption shares for all contests in the election
"""
spoiled_ballots: Dict[BALLOT_ID, CompensatedBallotDecryptionShare]
"""
The collection of decryption shares for all spoiled ballots in the election
"""
def get_tally_shares_for_selection(
selection_id: str,
shares: Dict[GUARDIAN_ID, TallyDecryptionShare],
) -> Dict[GUARDIAN_ID, Tuple[ELECTION_PUBLIC_KEY, CiphertextDecryptionSelection]]:
"""
Get all of the cast shares for a specific selection
"""
cast_shares: Dict[
GUARDIAN_ID, Tuple[ELECTION_PUBLIC_KEY, CiphertextDecryptionSelection]
] = {}
for share in shares.values():
for contest in share.contests.values():
for selection in contest.selections.values():
if selection.object_id == selection_id:
cast_shares[share.guardian_id] = (share.public_key, selection)
return cast_shares
def get_spoiled_shares_for_selection(
ballot_id: str,
selection_id: str,
shares: Dict[GUARDIAN_ID, TallyDecryptionShare],
) -> Dict[GUARDIAN_ID, Tuple[ELECTION_PUBLIC_KEY, CiphertextDecryptionSelection]]:
"""
Get the spoiled shares for a given selection
"""
spoiled_shares: Dict[
GUARDIAN_ID, Tuple[ELECTION_PUBLIC_KEY, CiphertextDecryptionSelection]
] = {}
for share in shares.values():
for ballot in share.spoiled_ballots.values():
if ballot.ballot_id == ballot_id:
for contest in ballot.contests.values():
for selection in contest.selections.values():
if selection.object_id == selection_id:
spoiled_shares[share.guardian_id] = (
share.public_key,
selection,
)
return spoiled_shares
def get_ballot_shares_for_selection(
selection_id: str,
shares: Dict[GUARDIAN_ID, BallotDecryptionShare],
) -> Dict[GUARDIAN_ID, Tuple[ELECTION_PUBLIC_KEY, CiphertextDecryptionSelection]]:
"""
Get the ballot shares for a given selection, in the context of a specific ballot
"""
ballot_shares: Dict[
GUARDIAN_ID, Tuple[ELECTION_PUBLIC_KEY, CiphertextDecryptionSelection]
] = {}
for ballot_share in shares.values():
for contest_share in ballot_share.contests.values():
for selection_share in contest_share.selections.values():
if selection_share.object_id == selection_id:
ballot_shares[ballot_share.guardian_id] = (
ballot_share.public_key,
selection_share,
)
return ballot_shares | src/electionguard/decryption_share.py | from dataclasses import dataclass, field
from typing import Dict, Optional, Tuple, Union
from .chaum_pedersen import ChaumPedersenProof
from .election_object_base import ElectionObjectBase
from .elgamal import ElGamalCiphertext
from .group import ElementModP, ElementModQ
from .logs import log_warning
from .types import BALLOT_ID, CONTEST_ID, GUARDIAN_ID, SELECTION_ID
ELECTION_PUBLIC_KEY = ElementModP
@dataclass
class CiphertextCompensatedDecryptionSelection(ElectionObjectBase):
"""
A compensated fragment of a Guardian's Partial Decryption of a selection generated by an available guardian
"""
guardian_id: GUARDIAN_ID
"""
The Available Guardian that this share belongs to
"""
missing_guardian_id: GUARDIAN_ID
"""
The Missing Guardian for whom this share is calculated on behalf of
"""
description_hash: ElementModQ
"""
The SelectionDescription hash
"""
share: ElementModP
"""
The Share of the decryption of a selection. `M_{i,l} in the spec`
"""
recovery_key: ElementModP
"""
The Recovery Public Key for the missing_guardian that corresponds to the available guardian's share of the secret
"""
proof: ChaumPedersenProof
"""
The Proof that the share was decrypted correctly
"""
ProofOrRecovery = Union[
ChaumPedersenProof, Dict[GUARDIAN_ID, CiphertextCompensatedDecryptionSelection]
]
@dataclass
class CiphertextDecryptionSelection(ElectionObjectBase):
"""
A Guardian's Partial Decryption of a selection. A CiphertextDecryptionSelection
can be generated by a guardian directly, or it can be compensated for by a quoprum of guardians
When the guardian generates this share directly, the `proof` field is populated with
a `chaumPedersen` proof that the decryption share was generated correctly.
When the share is generated on behalf of this guardian by other guardians, the `recovered_parts`
collection is populated with the `CiphertextCompensatedDecryptionSelection` objects generated
by each available guardian.
"""
guardian_id: GUARDIAN_ID
"""
The Available Guardian that this share belongs to
"""
description_hash: ElementModQ
"""
The SelectionDescription hash
"""
share: ElementModP
"""
The Share of the decryption of a selection. `M_i` in the spec
"""
proof: Optional[ChaumPedersenProof] = field(init=True, default=None)
"""
The Proof that the share was decrypted correctly, if the guardian
was available for decryption
"""
recovered_parts: Optional[
Dict[GUARDIAN_ID, CiphertextCompensatedDecryptionSelection]
] = field(init=True, default=None)
"""
the recovered parts of the decryption provided by available guardians,
if the guardian was missing from decryption
"""
def is_valid(
self,
message: ElGamalCiphertext,
election_public_key: ELECTION_PUBLIC_KEY,
extended_base_hash: ElementModQ,
) -> bool:
"""
Verify that this CiphertextDecryptionSelection is valid for a
specific ElGamal key pair, public key, and election context.
:param message: the `ElGamalCiphertext` to compare
:param election_public_key: the `ElementModP Election Public Key for the Guardian
:param extended_base_hash: The `ElementModQ` election extended base hash.
"""
# verify we have a proof or recovered parts
if self.proof is None and self.recovered_parts is None:
log_warning(
f"CiphertextDecryptionSelection is_valid failed for guardian: {self.guardian_id} selection: {self.object_id} with missing data"
)
return False
if self.proof is not None and self.recovered_parts is not None:
log_warning(
f"CiphertextDecryptionSelection is_valid failed for guardian: {self.guardian_id} selection: {self.object_id} cannot have proof and recovery"
)
return False
if self.proof is not None and not self.proof.is_valid(
message,
election_public_key,
self.share,
extended_base_hash,
):
log_warning(
f"CiphertextDecryptionSelection is_valid failed for guardian: {self.guardian_id} selection: {self.object_id} with invalid proof"
)
return False
if self.recovered_parts is not None:
for (
compensating_guardian_id,
part,
) in self.recovered_parts.items():
if not part.proof.is_valid(
message,
part.recovery_key,
part.share,
extended_base_hash,
):
log_warning(
f"CiphertextDecryptionSelection is_valid failed for guardian: {self.guardian_id} selection: {self.object_id} with invalid partial proof"
)
return False
return True
def create_ciphertext_decryption_selection(
object_id: str,
guardian_id: GUARDIAN_ID,
description_hash: ElementModQ,
share: ElementModP,
proof_or_recovery: ProofOrRecovery,
) -> CiphertextDecryptionSelection:
"""
Create a ciphertext decryption selection
:param object_id: Object id
:param guardian_id: Guardian id
:param description_hash: Description hash
:param share: Share
:param proof_or_recovery: Proof or recovery
"""
if isinstance(proof_or_recovery, ChaumPedersenProof):
return CiphertextDecryptionSelection(
object_id, guardian_id, description_hash, share, proof=proof_or_recovery
)
elif isinstance(proof_or_recovery, Dict):
return CiphertextDecryptionSelection(
object_id,
guardian_id,
description_hash,
share,
recovered_parts=proof_or_recovery,
)
else:
log_warning(f"decryption share cannot assign {proof_or_recovery}")
return CiphertextDecryptionSelection(
object_id,
guardian_id,
description_hash,
share,
)
@dataclass
class CiphertextDecryptionContest(ElectionObjectBase):
"""
A Guardian's Partial Decryption of a contest
"""
guardian_id: GUARDIAN_ID
"""
The Available Guardian that this share belongs to
"""
description_hash: ElementModQ
"""
The ContestDescription Hash
"""
selections: Dict[SELECTION_ID, CiphertextDecryptionSelection]
"""
the collection of decryption shares for this contest's selections
"""
@dataclass
class CiphertextCompensatedDecryptionContest(ElectionObjectBase):
"""
A Guardian's Partial Decryption of a contest
"""
guardian_id: GUARDIAN_ID
"""
The Available Guardian that this share belongs to
"""
missing_guardian_id: GUARDIAN_ID
"""
The Missing Guardian for whom this share is calculated on behalf of
"""
description_hash: ElementModQ
"""
The ContestDescription Hash
"""
selections: Dict[SELECTION_ID, CiphertextCompensatedDecryptionSelection]
"""
the collection of decryption shares for this contest's selections
"""
@dataclass
class BallotDecryptionShare:
"""
A Guardian's Partial Decryption Share of a specific ballot (e.g. of a spoiled ballot)
"""
guardian_id: GUARDIAN_ID
"""
The Available Guardian that this share belongs to
"""
public_key: ElementModP
"""
The election public key for the guardian
"""
ballot_id: BALLOT_ID
"""
The Ballot Id that this Decryption Share belongs to
"""
contests: Dict[CONTEST_ID, CiphertextDecryptionContest]
"""
The collection of all contests in the ballot
"""
@dataclass
class CompensatedBallotDecryptionShare:
"""
A Compensated Partial Decryption Share generated by
an available guardian on behalf of a missing guardian
"""
guardian_id: GUARDIAN_ID
"""
The Available Guardian that this share belongs to
"""
missing_guardian_id: GUARDIAN_ID
"""
The Missing Guardian for whom this share is calculated on behalf of
"""
public_key: ElementModP
"""
The election public key for the guardian
"""
ballot_id: BALLOT_ID
"""
The Ballot Id that this Decryption Share belongs to
"""
contests: Dict[CONTEST_ID, CiphertextCompensatedDecryptionContest]
"""
The collection of all contests in the ballot
"""
@dataclass
class TallyDecryptionShare:
"""
A Guardian's Partial Decryption Share of an election tally
"""
guardian_id: GUARDIAN_ID
"""
The Available Guardian that this share belongs to
"""
public_key: ElementModP
"""
The election public key for the guardian
"""
contests: Dict[CONTEST_ID, CiphertextDecryptionContest]
"""
The collection of decryption shares for all contests in the election
"""
spoiled_ballots: Dict[BALLOT_ID, BallotDecryptionShare]
"""
The collection of decryption shares for all spoiled ballots in the election
"""
@dataclass
class CompensatedTallyDecryptionShare:
"""
A Compensated Partial Decryption Share generated by
an available guardian on behalf of a missing guardian
"""
guardian_id: GUARDIAN_ID
"""
The Available Guardian that this share belongs to
"""
missing_guardian_id: GUARDIAN_ID
"""
The Missing Guardian for whom this share is calculated on behalf of
"""
public_key: ElementModP
"""
The election public key for the guardian
"""
contests: Dict[CONTEST_ID, CiphertextCompensatedDecryptionContest]
"""
The collection of decryption shares for all contests in the election
"""
spoiled_ballots: Dict[BALLOT_ID, CompensatedBallotDecryptionShare]
"""
The collection of decryption shares for all spoiled ballots in the election
"""
def get_tally_shares_for_selection(
selection_id: str,
shares: Dict[GUARDIAN_ID, TallyDecryptionShare],
) -> Dict[GUARDIAN_ID, Tuple[ELECTION_PUBLIC_KEY, CiphertextDecryptionSelection]]:
"""
Get all of the cast shares for a specific selection
"""
cast_shares: Dict[
GUARDIAN_ID, Tuple[ELECTION_PUBLIC_KEY, CiphertextDecryptionSelection]
] = {}
for share in shares.values():
for contest in share.contests.values():
for selection in contest.selections.values():
if selection.object_id == selection_id:
cast_shares[share.guardian_id] = (share.public_key, selection)
return cast_shares
def get_spoiled_shares_for_selection(
ballot_id: str,
selection_id: str,
shares: Dict[GUARDIAN_ID, TallyDecryptionShare],
) -> Dict[GUARDIAN_ID, Tuple[ELECTION_PUBLIC_KEY, CiphertextDecryptionSelection]]:
"""
Get the spoiled shares for a given selection
"""
spoiled_shares: Dict[
GUARDIAN_ID, Tuple[ELECTION_PUBLIC_KEY, CiphertextDecryptionSelection]
] = {}
for share in shares.values():
for ballot in share.spoiled_ballots.values():
if ballot.ballot_id == ballot_id:
for contest in ballot.contests.values():
for selection in contest.selections.values():
if selection.object_id == selection_id:
spoiled_shares[share.guardian_id] = (
share.public_key,
selection,
)
return spoiled_shares
def get_ballot_shares_for_selection(
selection_id: str,
shares: Dict[GUARDIAN_ID, BallotDecryptionShare],
) -> Dict[GUARDIAN_ID, Tuple[ELECTION_PUBLIC_KEY, CiphertextDecryptionSelection]]:
"""
Get the ballot shares for a given selection, in the context of a specific ballot
"""
ballot_shares: Dict[
GUARDIAN_ID, Tuple[ELECTION_PUBLIC_KEY, CiphertextDecryptionSelection]
] = {}
for ballot_share in shares.values():
for contest_share in ballot_share.contests.values():
for selection_share in contest_share.selections.values():
if selection_share.object_id == selection_id:
ballot_shares[ballot_share.guardian_id] = (
ballot_share.public_key,
selection_share,
)
return ballot_shares | 0.877391 | 0.277051 |
import contextlib
import os
import numpy as np
import torch.distributed
import torch.utils.data
from pytools.pyutils.io.serialize import dumps_pickle, loads_pickle
from pytools.pyutils.misc.decorator import check_fn, check_failed_message
__all__ = [
"activate",
"register_extra_group",
"unregister_extra_group",
"is_distribute_activated",
"is_distribute_enabled",
"is_master",
"is_local_master",
"get_batch_size",
"get_rank",
"get_size",
'broadcast'
]
_REGISTERED_EXTRA_GROUPS = set()
_IS_CONTEXT_ACTIVATED = False
_IS_DISTRIBUTED_ENABLED = False
_LOCAL_RANK = None
_STAT_GROUP = None
@check_failed_message("Distributed environment is not activated")
def is_distribute_activated():
return _IS_CONTEXT_ACTIVATED
@check_failed_message("Distributed environment is not enabled")
def is_distribute_enabled():
return is_distribute_activated() and _IS_DISTRIBUTED_ENABLED
@check_fn(is_distribute_enabled)
def register_extra_group(*args, **kwargs):
global _REGISTERED_EXTRA_GROUPS
group = torch.distributed.new_group(*args, **kwargs)
_REGISTERED_EXTRA_GROUPS.add(group)
return group
@check_fn(is_distribute_enabled)
def unregister_extra_group(group=None):
global _REGISTERED_EXTRA_GROUPS
if group is None:
group = _REGISTERED_EXTRA_GROUPS.pop()
else:
_REGISTERED_EXTRA_GROUPS.remove(group)
torch.distributed.destroy_process_group(group)
@check_fn(is_distribute_enabled)
def get_rank():
return torch.distributed.get_rank()
@check_fn(is_distribute_enabled)
def get_size():
return torch.distributed.get_world_size()
@check_fn(is_distribute_enabled)
def get_local_rank():
return _LOCAL_RANK
def is_local_master():
return (not is_distribute_enabled()) or (get_local_rank() == 0)
def is_master():
return (not is_distribute_enabled()) or (get_rank() == 0)
def get_sampler(dataset, shuffle=True):
if is_distribute_enabled():
return torch.utils.data.distributed.DistributedSampler(dataset, get_size(), get_rank(), shuffle=shuffle)
else:
return None
def get_batch_size(batch_size):
if not is_distribute_enabled():
return batch_size
size = get_size()
return (batch_size // size) + int(get_rank() < batch_size % size)
@contextlib.contextmanager
def activate(is_distributed_enabled=False, local_rank=None, *args, **kwargs):
global _IS_CONTEXT_ACTIVATED
global _IS_DISTRIBUTED_ENABLED
global _LOCAL_RANK
global _STAT_GROUP
if _IS_CONTEXT_ACTIVATED:
raise RuntimeError("Distributed module is already activated")
try:
_IS_DISTRIBUTED_ENABLED = is_distributed_enabled
_IS_CONTEXT_ACTIVATED = True
if is_distributed_enabled:
group = torch.distributed.init_process_group(*args, **kwargs)
_LOCAL_RANK = int(local_rank) if local_rank else int(os.environ.get("LOCAL_RANK", get_rank()))
yield group
else:
yield
finally:
while _REGISTERED_EXTRA_GROUPS:
unregister_extra_group()
if is_distributed_enabled:
torch.distributed.destroy_process_group()
_LOCAL_RANK = None
_IS_DISTRIBUTED_ENABLED = False
_IS_CONTEXT_ACTIVATED = False
_STAT_GROUP = None
def broadcast(data, source=0, group=None):
if not is_distribute_enabled() or get_size() == 1:
if is_distribute_enabled() and (get_rank() != source or source != 0):
raise RuntimeError(f"Unknown source rank {source}")
return data
if not is_distribute_enabled():
raise RuntimeError(is_distribute_enabled.__failed_message__)
if group is None:
global _STAT_GROUP
group = _STAT_GROUP = _STAT_GROUP or register_extra_group(backend='gloo')
tensor = torch.ByteStorage.from_buffer(dumps_pickle(data))
tensor = torch.ByteTensor(tensor)
torch.distributed.broadcast(tensor, source, group=group)
return loads_pickle(tensor.numpy().tobytes())
def all_reduce(data, group=None, use_async_op=False):
if not is_distribute_enabled() or get_size() == 1:
return list() if use_async_op else data
if group is None:
global _STAT_GROUP
group = _STAT_GROUP = _STAT_GROUP or register_extra_group(backend='gloo')
if isinstance(data, (int, np.integer)):
data = torch.tensor(data, dtype=torch.int)
elif isinstance(data, (float, np.floating)):
data = torch.tensor(data, dtype=torch.float)
elif isinstance(data, np.ndarray):
data = torch.tensor(data)
elif not isinstance(data, torch.Tensor):
raise ValueError("Cannot convert data to torch Tensor")
task = torch.distributed.all_reduce(data, group=group, async_op=True)
if use_async_op:
return [task]
else:
task.wait()
return data
def barrier(group=None):
if not is_distribute_enabled() or get_size() == 1:
return
if group is None:
global _STAT_GROUP
group = _STAT_GROUP = _STAT_GROUP or register_extra_group(backend='gloo')
torch.distributed.barrier(group=group) | third_party/pytools/pytools/pytorch/distributed.py | import contextlib
import os
import numpy as np
import torch.distributed
import torch.utils.data
from pytools.pyutils.io.serialize import dumps_pickle, loads_pickle
from pytools.pyutils.misc.decorator import check_fn, check_failed_message
__all__ = [
"activate",
"register_extra_group",
"unregister_extra_group",
"is_distribute_activated",
"is_distribute_enabled",
"is_master",
"is_local_master",
"get_batch_size",
"get_rank",
"get_size",
'broadcast'
]
_REGISTERED_EXTRA_GROUPS = set()
_IS_CONTEXT_ACTIVATED = False
_IS_DISTRIBUTED_ENABLED = False
_LOCAL_RANK = None
_STAT_GROUP = None
@check_failed_message("Distributed environment is not activated")
def is_distribute_activated():
return _IS_CONTEXT_ACTIVATED
@check_failed_message("Distributed environment is not enabled")
def is_distribute_enabled():
return is_distribute_activated() and _IS_DISTRIBUTED_ENABLED
@check_fn(is_distribute_enabled)
def register_extra_group(*args, **kwargs):
global _REGISTERED_EXTRA_GROUPS
group = torch.distributed.new_group(*args, **kwargs)
_REGISTERED_EXTRA_GROUPS.add(group)
return group
@check_fn(is_distribute_enabled)
def unregister_extra_group(group=None):
global _REGISTERED_EXTRA_GROUPS
if group is None:
group = _REGISTERED_EXTRA_GROUPS.pop()
else:
_REGISTERED_EXTRA_GROUPS.remove(group)
torch.distributed.destroy_process_group(group)
@check_fn(is_distribute_enabled)
def get_rank():
return torch.distributed.get_rank()
@check_fn(is_distribute_enabled)
def get_size():
return torch.distributed.get_world_size()
@check_fn(is_distribute_enabled)
def get_local_rank():
return _LOCAL_RANK
def is_local_master():
return (not is_distribute_enabled()) or (get_local_rank() == 0)
def is_master():
return (not is_distribute_enabled()) or (get_rank() == 0)
def get_sampler(dataset, shuffle=True):
if is_distribute_enabled():
return torch.utils.data.distributed.DistributedSampler(dataset, get_size(), get_rank(), shuffle=shuffle)
else:
return None
def get_batch_size(batch_size):
if not is_distribute_enabled():
return batch_size
size = get_size()
return (batch_size // size) + int(get_rank() < batch_size % size)
@contextlib.contextmanager
def activate(is_distributed_enabled=False, local_rank=None, *args, **kwargs):
global _IS_CONTEXT_ACTIVATED
global _IS_DISTRIBUTED_ENABLED
global _LOCAL_RANK
global _STAT_GROUP
if _IS_CONTEXT_ACTIVATED:
raise RuntimeError("Distributed module is already activated")
try:
_IS_DISTRIBUTED_ENABLED = is_distributed_enabled
_IS_CONTEXT_ACTIVATED = True
if is_distributed_enabled:
group = torch.distributed.init_process_group(*args, **kwargs)
_LOCAL_RANK = int(local_rank) if local_rank else int(os.environ.get("LOCAL_RANK", get_rank()))
yield group
else:
yield
finally:
while _REGISTERED_EXTRA_GROUPS:
unregister_extra_group()
if is_distributed_enabled:
torch.distributed.destroy_process_group()
_LOCAL_RANK = None
_IS_DISTRIBUTED_ENABLED = False
_IS_CONTEXT_ACTIVATED = False
_STAT_GROUP = None
def broadcast(data, source=0, group=None):
if not is_distribute_enabled() or get_size() == 1:
if is_distribute_enabled() and (get_rank() != source or source != 0):
raise RuntimeError(f"Unknown source rank {source}")
return data
if not is_distribute_enabled():
raise RuntimeError(is_distribute_enabled.__failed_message__)
if group is None:
global _STAT_GROUP
group = _STAT_GROUP = _STAT_GROUP or register_extra_group(backend='gloo')
tensor = torch.ByteStorage.from_buffer(dumps_pickle(data))
tensor = torch.ByteTensor(tensor)
torch.distributed.broadcast(tensor, source, group=group)
return loads_pickle(tensor.numpy().tobytes())
def all_reduce(data, group=None, use_async_op=False):
if not is_distribute_enabled() or get_size() == 1:
return list() if use_async_op else data
if group is None:
global _STAT_GROUP
group = _STAT_GROUP = _STAT_GROUP or register_extra_group(backend='gloo')
if isinstance(data, (int, np.integer)):
data = torch.tensor(data, dtype=torch.int)
elif isinstance(data, (float, np.floating)):
data = torch.tensor(data, dtype=torch.float)
elif isinstance(data, np.ndarray):
data = torch.tensor(data)
elif not isinstance(data, torch.Tensor):
raise ValueError("Cannot convert data to torch Tensor")
task = torch.distributed.all_reduce(data, group=group, async_op=True)
if use_async_op:
return [task]
else:
task.wait()
return data
def barrier(group=None):
if not is_distribute_enabled() or get_size() == 1:
return
if group is None:
global _STAT_GROUP
group = _STAT_GROUP = _STAT_GROUP or register_extra_group(backend='gloo')
torch.distributed.barrier(group=group) | 0.625209 | 0.165425 |
from __future__ import generator_stop
import os
import shutil
import tempfile
from utils import check_on_input
from modernize.__main__ import main as modernize_main
SINGLE_PRINT_CONTENT = """
print 'world'
"""
TWO_PRINTS_CONTENT = """
print 'Hello'
print 'world'
"""
COMPLICATED_CONTENT = """
print 'Hello'
print u'world'
def sub(x):
print x, u"here"
"""
PROBLEMATIC_CONTENT = '''
"""
Hello
"""
from a.b.c import d
def test_existing():
print d
'''
def _check_for_multiple_futures(file_name, source_content):
"""
Checks for multiple identical futures in given file,
raises if found.
Returns dictionary of found futures (name => 1)
"""
counts = {}
result_content = ""
with open(file_name) as input:
for line in input:
if line.startswith("from __future__"):
counts[line] = 1 + counts.get(line, 0)
result_content += line
for future, how_many in counts.items():
if how_many > 1:
raise Exception(
f"The same future repeated more than once ({how_many} times):\n"
f"{future}\n\n* Input file:\n{source_content}\n\n"
f"* Output file:\n{result_content}\n"
)
return counts
def _check_on_input(file_content, extra_flags=[]):
try:
tmpdirname = tempfile.mkdtemp()
test_input_name = os.path.join(tmpdirname, "input.py")
with open(test_input_name, "wt") as input:
input.write(file_content)
modernize_main(extra_flags + ["-w", test_input_name])
_check_for_multiple_futures(test_input_name, file_content)
finally:
shutil.rmtree(tmpdirname)
def test_single_print():
_check_on_input(SINGLE_PRINT_CONTENT)
def test_two_prints():
_check_on_input(TWO_PRINTS_CONTENT)
def test_many_prints_and_unicode():
_check_on_input(COMPLICATED_CONTENT, ["--future-unicode"])
def test_two_files_on_single_run():
# Mostly to test whether second file gets its "from future ..."
try:
tmpdirname = tempfile.mkdtemp()
input_names = [
os.path.join(tmpdirname, f"input_{idx}.py") for idx in range(0, 3)
]
for input_name in input_names:
with open(input_name, "wt") as input:
input.write(TWO_PRINTS_CONTENT)
modernize_main(["-w"] + input_names)
for input_name in input_names:
futs = _check_for_multiple_futures(input_name, TWO_PRINTS_CONTENT)
if not futs:
raise Exception("File {0} got no from __future__ (but it should)")
finally:
shutil.rmtree(tmpdirname)
def test_problematic_file():
# ON this one I get crash
_check_on_input(PROBLEMATIC_CONTENT)
FUTURE_IMPORT_AS = (
"""\
from __future__ import print_function as pf
print("abc")
""",
"""\
from __future__ import print_function as pf
print("abc")
""",
)
FUTURE_IMPORT_AS_MULTIPLE = (
"""\
from __future__ import print_function as pf, division as dv
print("abc")
""",
"""\
from __future__ import print_function as pf, division as dv
print("abc")
""",
)
FUTURE_IMPORT_PAREN = (
"""\
from __future__ import (absolute_import, division, print_function)
unicode("abc")
""",
"""\
from __future__ import (absolute_import, division, print_function)
import six
six.text_type("abc")
""",
)
def test_future_import_as():
check_on_input(*FUTURE_IMPORT_AS)
def test_future_import_as_multiple():
check_on_input(*FUTURE_IMPORT_AS_MULTIPLE)
def test_future_import_paren():
check_on_input(*FUTURE_IMPORT_PAREN) | tests/test_future_behaviour.py |
from __future__ import generator_stop
import os
import shutil
import tempfile
from utils import check_on_input
from modernize.__main__ import main as modernize_main
SINGLE_PRINT_CONTENT = """
print 'world'
"""
TWO_PRINTS_CONTENT = """
print 'Hello'
print 'world'
"""
COMPLICATED_CONTENT = """
print 'Hello'
print u'world'
def sub(x):
print x, u"here"
"""
PROBLEMATIC_CONTENT = '''
"""
Hello
"""
from a.b.c import d
def test_existing():
print d
'''
def _check_for_multiple_futures(file_name, source_content):
"""
Checks for multiple identical futures in given file,
raises if found.
Returns dictionary of found futures (name => 1)
"""
counts = {}
result_content = ""
with open(file_name) as input:
for line in input:
if line.startswith("from __future__"):
counts[line] = 1 + counts.get(line, 0)
result_content += line
for future, how_many in counts.items():
if how_many > 1:
raise Exception(
f"The same future repeated more than once ({how_many} times):\n"
f"{future}\n\n* Input file:\n{source_content}\n\n"
f"* Output file:\n{result_content}\n"
)
return counts
def _check_on_input(file_content, extra_flags=[]):
try:
tmpdirname = tempfile.mkdtemp()
test_input_name = os.path.join(tmpdirname, "input.py")
with open(test_input_name, "wt") as input:
input.write(file_content)
modernize_main(extra_flags + ["-w", test_input_name])
_check_for_multiple_futures(test_input_name, file_content)
finally:
shutil.rmtree(tmpdirname)
def test_single_print():
_check_on_input(SINGLE_PRINT_CONTENT)
def test_two_prints():
_check_on_input(TWO_PRINTS_CONTENT)
def test_many_prints_and_unicode():
_check_on_input(COMPLICATED_CONTENT, ["--future-unicode"])
def test_two_files_on_single_run():
# Mostly to test whether second file gets its "from future ..."
try:
tmpdirname = tempfile.mkdtemp()
input_names = [
os.path.join(tmpdirname, f"input_{idx}.py") for idx in range(0, 3)
]
for input_name in input_names:
with open(input_name, "wt") as input:
input.write(TWO_PRINTS_CONTENT)
modernize_main(["-w"] + input_names)
for input_name in input_names:
futs = _check_for_multiple_futures(input_name, TWO_PRINTS_CONTENT)
if not futs:
raise Exception("File {0} got no from __future__ (but it should)")
finally:
shutil.rmtree(tmpdirname)
def test_problematic_file():
# ON this one I get crash
_check_on_input(PROBLEMATIC_CONTENT)
FUTURE_IMPORT_AS = (
"""\
from __future__ import print_function as pf
print("abc")
""",
"""\
from __future__ import print_function as pf
print("abc")
""",
)
FUTURE_IMPORT_AS_MULTIPLE = (
"""\
from __future__ import print_function as pf, division as dv
print("abc")
""",
"""\
from __future__ import print_function as pf, division as dv
print("abc")
""",
)
FUTURE_IMPORT_PAREN = (
"""\
from __future__ import (absolute_import, division, print_function)
unicode("abc")
""",
"""\
from __future__ import (absolute_import, division, print_function)
import six
six.text_type("abc")
""",
)
def test_future_import_as():
check_on_input(*FUTURE_IMPORT_AS)
def test_future_import_as_multiple():
check_on_input(*FUTURE_IMPORT_AS_MULTIPLE)
def test_future_import_paren():
check_on_input(*FUTURE_IMPORT_PAREN) | 0.437103 | 0.106784 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
from torch.autograd import Variable
class DilatedLSTMCell(nn.Module):
def __init__(self, input_size, hidden_size, clock=10, bias=True):
super(DilatedLSTMCell, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.bias = bias
self.weight_ih, self.weight_hh = {}, {}
if bias:
self.bias_ih, self.bias_hh = {}, {}
q, r = hidden_size // clock, hidden_size % clock
hidden_sizes = [q + (1 if j < r else 0) for j in range(clock)]
self.hidden_sizes = hidden_sizes
self.slice_idx = slice_idx = []
n = 0
for j, hidden_size_j in enumerate(hidden_sizes):
slice_idx.append((n, n + hidden_size_j))
n += hidden_size_j
input_size_j = input_size + hidden_size - hidden_size_j
w_ih_j = Parameter(torch.Tensor(4 * hidden_size_j, input_size_j))
w_hh_j = Parameter(torch.Tensor(4 * hidden_size_j, hidden_size_j))
setattr(self, 'weight_ih_{:d}'.format(j), w_ih_j)
setattr(self, 'weight_hh_{:d}'.format(j), w_hh_j)
self.weight_ih[j] = w_ih_j
self.weight_hh[j] = w_hh_j
if bias:
bias_ih_j = Parameter(torch.Tensor(4 * hidden_size_j))
bias_hh_j = Parameter(torch.Tensor(4 * hidden_size_j))
setattr(self, 'bias_ih_{:d}'.format(j), bias_ih_j)
setattr(self, 'bias_hh_{:d}'.format(j), bias_hh_j)
self.bias_ih[j] = bias_ih_j
self.bias_hh[j] = bias_hh_j
self.reset_parameters()
self.clock = clock
def reset_parameters(self):
import math
stdv = 1.0 / math.sqrt(self.hidden_sizes[0])
for weight in self.parameters():
weight.data.uniform_(-stdv, stdv)
def forward(self, x, hx, clock):
j = clock % self.clock
(start, end) = self.slice_idx[j]
hidden_size = self.hidden_size
(hx, cx) = hx
h_j = hx.narrow(1, start, end-start)
c_j = cx.narrow(1, start, end-start)
inputs = [x]
if start > 0:
inputs.append(hx.narrow(1, 0, start))
if end < hidden_size:
inputs.append(hx.narrow(1, end, hidden_size - end))
input_j = torch.cat(inputs, 1)
h_j, c_j = self._backend.LSTMCell(
input_j, (h_j, c_j),
self.weight_ih[j], self.weight_hh[j],
self.bias_ih[j], self.bias_hh[j],
)
hs, cs = [], []
if start > 0:
hs.append(hx.narrow(1, 0, start))
cs.append(cx.narrow(1, 0, start))
hs.append(h_j)
cs.append(c_j)
if end < hidden_size:
hs.append(hx.narrow(1, end, hidden_size - end))
cs.append(cx.narrow(1, end, hidden_size - end))
return torch.cat(hs, 1), torch.cat(cs, 1)
if __name__ == "__main__":
dlstm = DilatedLSTMCell(16, 32, 8)
h, c = Variable(torch.zeros(10, 32)), Variable(torch.zeros(10, 32))
for clock in range(100):
x = Variable(torch.randn(10, 16))
h, c = dlstm(x, (h, c), clock) | ai_challenge/models/dilated_rnn.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
from torch.autograd import Variable
class DilatedLSTMCell(nn.Module):
def __init__(self, input_size, hidden_size, clock=10, bias=True):
super(DilatedLSTMCell, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.bias = bias
self.weight_ih, self.weight_hh = {}, {}
if bias:
self.bias_ih, self.bias_hh = {}, {}
q, r = hidden_size // clock, hidden_size % clock
hidden_sizes = [q + (1 if j < r else 0) for j in range(clock)]
self.hidden_sizes = hidden_sizes
self.slice_idx = slice_idx = []
n = 0
for j, hidden_size_j in enumerate(hidden_sizes):
slice_idx.append((n, n + hidden_size_j))
n += hidden_size_j
input_size_j = input_size + hidden_size - hidden_size_j
w_ih_j = Parameter(torch.Tensor(4 * hidden_size_j, input_size_j))
w_hh_j = Parameter(torch.Tensor(4 * hidden_size_j, hidden_size_j))
setattr(self, 'weight_ih_{:d}'.format(j), w_ih_j)
setattr(self, 'weight_hh_{:d}'.format(j), w_hh_j)
self.weight_ih[j] = w_ih_j
self.weight_hh[j] = w_hh_j
if bias:
bias_ih_j = Parameter(torch.Tensor(4 * hidden_size_j))
bias_hh_j = Parameter(torch.Tensor(4 * hidden_size_j))
setattr(self, 'bias_ih_{:d}'.format(j), bias_ih_j)
setattr(self, 'bias_hh_{:d}'.format(j), bias_hh_j)
self.bias_ih[j] = bias_ih_j
self.bias_hh[j] = bias_hh_j
self.reset_parameters()
self.clock = clock
def reset_parameters(self):
import math
stdv = 1.0 / math.sqrt(self.hidden_sizes[0])
for weight in self.parameters():
weight.data.uniform_(-stdv, stdv)
def forward(self, x, hx, clock):
j = clock % self.clock
(start, end) = self.slice_idx[j]
hidden_size = self.hidden_size
(hx, cx) = hx
h_j = hx.narrow(1, start, end-start)
c_j = cx.narrow(1, start, end-start)
inputs = [x]
if start > 0:
inputs.append(hx.narrow(1, 0, start))
if end < hidden_size:
inputs.append(hx.narrow(1, end, hidden_size - end))
input_j = torch.cat(inputs, 1)
h_j, c_j = self._backend.LSTMCell(
input_j, (h_j, c_j),
self.weight_ih[j], self.weight_hh[j],
self.bias_ih[j], self.bias_hh[j],
)
hs, cs = [], []
if start > 0:
hs.append(hx.narrow(1, 0, start))
cs.append(cx.narrow(1, 0, start))
hs.append(h_j)
cs.append(c_j)
if end < hidden_size:
hs.append(hx.narrow(1, end, hidden_size - end))
cs.append(cx.narrow(1, end, hidden_size - end))
return torch.cat(hs, 1), torch.cat(cs, 1)
if __name__ == "__main__":
dlstm = DilatedLSTMCell(16, 32, 8)
h, c = Variable(torch.zeros(10, 32)), Variable(torch.zeros(10, 32))
for clock in range(100):
x = Variable(torch.randn(10, 16))
h, c = dlstm(x, (h, c), clock) | 0.87157 | 0.499634 |
from __future__ import absolute_import
from scrapy.http.request import Request as ScrapyRequest
from scrapy.http.response import Response as ScrapyResponse
from frontera.core.models import Request as FrontierRequest
from frontera.core.models import Response as FrontierResponse
from frontera.utils.converters import BaseRequestConverter, BaseResponseConverter
from w3lib.util import to_bytes, to_native_str
class RequestConverter(BaseRequestConverter):
"""Converts between frontera and Scrapy request objects"""
def __init__(self, spider):
self.spider = spider
def to_frontier(self, scrapy_request):
"""request: Scrapy > Frontier"""
if isinstance(scrapy_request.cookies, dict):
cookies = scrapy_request.cookies
else:
cookies = dict(sum([list(d.items()) for d in scrapy_request.cookies], []))
cb = scrapy_request.callback
if callable(cb):
cb = _find_method(self.spider, cb)
eb = scrapy_request.errback
if callable(eb):
eb = _find_method(self.spider, eb)
scrapy_meta = scrapy_request.meta
meta = {}
if b'frontier_request' in scrapy_meta:
request = scrapy_meta[b'frontier_request']
if isinstance(request, FrontierRequest):
meta = request.meta
del scrapy_meta[b'frontier_request']
meta.update({
b'scrapy_callback': cb,
b'scrapy_errback': eb,
b'scrapy_meta': scrapy_meta,
b'origin_is_frontier': True,
})
if 'redirect_urls' in scrapy_meta:
meta[b'redirect_urls'] = scrapy_meta['redirect_urls']
return FrontierRequest(url=scrapy_request.url,
method=scrapy_request.method,
headers=scrapy_request.headers,
cookies=cookies,
meta=meta,
body=scrapy_request.body)
def from_frontier(self, frontier_request):
"""request: Frontier > Scrapy"""
cb = frontier_request.meta.get(b'scrapy_callback', None)
if cb and self.spider:
cb = _get_method(self.spider, cb)
eb = frontier_request.meta.get(b'scrapy_errback', None)
if eb and self.spider:
eb = _get_method(self.spider, eb)
body = frontier_request.body
meta = frontier_request.meta.get(b'scrapy_meta', {})
meta[b'frontier_request'] = frontier_request
return ScrapyRequest(url=frontier_request.url,
callback=cb,
errback=eb,
body=body,
method=to_native_str(frontier_request.method),
headers=frontier_request.headers,
cookies=frontier_request.cookies,
meta=meta,
dont_filter=True)
class ResponseConverter(BaseResponseConverter):
"""Converts between frontera and Scrapy response objects"""
def __init__(self, spider, request_converter):
self.spider = spider
self._request_converter = request_converter
def to_frontier(self, scrapy_response):
"""response: Scrapy > Frontier"""
frontier_request = scrapy_response.meta[b'frontier_request']
frontier_request.meta[b'scrapy_meta'] = scrapy_response.meta
if 'redirect_urls' in scrapy_response.meta:
frontier_request.meta[b'redirect_urls'] = scrapy_response.meta['redirect_urls']
del scrapy_response.meta[b'frontier_request']
return FrontierResponse(url=scrapy_response.url,
status_code=scrapy_response.status,
headers=scrapy_response.headers,
body=scrapy_response.body,
request=frontier_request)
def from_frontier(self, response):
"""response: Frontier > Scrapy"""
return ScrapyResponse(url=response.url,
status=response.status_code,
headers=response.headers,
body=response.body,
request=self._request_converter.from_frontier(response.request))
def _find_method(obj, func):
if obj and hasattr(func, '__self__') and func.__self__ is obj:
return to_bytes(func.__func__.__name__)
else:
raise ValueError("Function %s is not a method of: %s" % (func, obj))
def _get_method(obj, name):
name = to_native_str(name)
try:
return getattr(obj, name)
except AttributeError:
raise ValueError("Method %r not found in: %s" % (name, obj)) | frontera/contrib/scrapy/converters.py | from __future__ import absolute_import
from scrapy.http.request import Request as ScrapyRequest
from scrapy.http.response import Response as ScrapyResponse
from frontera.core.models import Request as FrontierRequest
from frontera.core.models import Response as FrontierResponse
from frontera.utils.converters import BaseRequestConverter, BaseResponseConverter
from w3lib.util import to_bytes, to_native_str
class RequestConverter(BaseRequestConverter):
"""Converts between frontera and Scrapy request objects"""
def __init__(self, spider):
self.spider = spider
def to_frontier(self, scrapy_request):
"""request: Scrapy > Frontier"""
if isinstance(scrapy_request.cookies, dict):
cookies = scrapy_request.cookies
else:
cookies = dict(sum([list(d.items()) for d in scrapy_request.cookies], []))
cb = scrapy_request.callback
if callable(cb):
cb = _find_method(self.spider, cb)
eb = scrapy_request.errback
if callable(eb):
eb = _find_method(self.spider, eb)
scrapy_meta = scrapy_request.meta
meta = {}
if b'frontier_request' in scrapy_meta:
request = scrapy_meta[b'frontier_request']
if isinstance(request, FrontierRequest):
meta = request.meta
del scrapy_meta[b'frontier_request']
meta.update({
b'scrapy_callback': cb,
b'scrapy_errback': eb,
b'scrapy_meta': scrapy_meta,
b'origin_is_frontier': True,
})
if 'redirect_urls' in scrapy_meta:
meta[b'redirect_urls'] = scrapy_meta['redirect_urls']
return FrontierRequest(url=scrapy_request.url,
method=scrapy_request.method,
headers=scrapy_request.headers,
cookies=cookies,
meta=meta,
body=scrapy_request.body)
def from_frontier(self, frontier_request):
"""request: Frontier > Scrapy"""
cb = frontier_request.meta.get(b'scrapy_callback', None)
if cb and self.spider:
cb = _get_method(self.spider, cb)
eb = frontier_request.meta.get(b'scrapy_errback', None)
if eb and self.spider:
eb = _get_method(self.spider, eb)
body = frontier_request.body
meta = frontier_request.meta.get(b'scrapy_meta', {})
meta[b'frontier_request'] = frontier_request
return ScrapyRequest(url=frontier_request.url,
callback=cb,
errback=eb,
body=body,
method=to_native_str(frontier_request.method),
headers=frontier_request.headers,
cookies=frontier_request.cookies,
meta=meta,
dont_filter=True)
class ResponseConverter(BaseResponseConverter):
"""Converts between frontera and Scrapy response objects"""
def __init__(self, spider, request_converter):
self.spider = spider
self._request_converter = request_converter
def to_frontier(self, scrapy_response):
"""response: Scrapy > Frontier"""
frontier_request = scrapy_response.meta[b'frontier_request']
frontier_request.meta[b'scrapy_meta'] = scrapy_response.meta
if 'redirect_urls' in scrapy_response.meta:
frontier_request.meta[b'redirect_urls'] = scrapy_response.meta['redirect_urls']
del scrapy_response.meta[b'frontier_request']
return FrontierResponse(url=scrapy_response.url,
status_code=scrapy_response.status,
headers=scrapy_response.headers,
body=scrapy_response.body,
request=frontier_request)
def from_frontier(self, response):
"""response: Frontier > Scrapy"""
return ScrapyResponse(url=response.url,
status=response.status_code,
headers=response.headers,
body=response.body,
request=self._request_converter.from_frontier(response.request))
def _find_method(obj, func):
if obj and hasattr(func, '__self__') and func.__self__ is obj:
return to_bytes(func.__func__.__name__)
else:
raise ValueError("Function %s is not a method of: %s" % (func, obj))
def _get_method(obj, name):
name = to_native_str(name)
try:
return getattr(obj, name)
except AttributeError:
raise ValueError("Method %r not found in: %s" % (name, obj)) | 0.606032 | 0.057467 |
import requests
import os.path
import json
import pprint
import sys
import getopt
class FHIRSearchClient:
''' Class to call FHIR server directly as a GA4GHSearch-like client
This does not use the fhirpy library '''
def __init__(self, hostURL, cookies, debug=False ):
self.hostURL = hostURL
self.debug = debug
self.headers = {
'content-type': 'application/json'
}
self.cookies = cookies
def runQuery(self, query):
next_url = "{}/Patient?gender={}".format(self.hostURL, query)
pageCount = 0
#resultRows = []
print ("_Retrieving the query_")
if self.debug: print(self.cookies)
while next_url != None :
if self.debug:
print(next_url)
pageCount += 1
print ("____Page{}_______________".format(pageCount))
response = requests.request("GET", next_url, cookies=self.cookies)
if self.debug:
print(response.content)
result = (response.json())
if self.debug:
print(result)
if 'link' in result :
nxt = next((sub for sub in result['link'] if sub['relation'] == 'next'), None)
if nxt == None:
next_url = None
else:
next_url = nxt['url']
else:
next_url = None
for t in result['entry']:
print('patient id :',t['resource']['id'])
# if rowCount > 0:
# resultRows.append(result['data'])
# for r in result['data']:
# resultRows.append([*r.values()])
# return resultRows
def listResources(self):
next_url = self.hostURL + "/StructureDefinition"
pageCount = 0
resultRows = []
print ("_Retrieving the resource list_")
while next_url != None :
if self.debug:
pprint.pprint(next_url)
pageCount += 1
print ("____Page{}_______________".format(pageCount))
#response = requests.get(next_url, headers=self.headers)
response = requests.get(next_url, cookies=self.cookies)
if self.debug:
print(response.content)
result = (response.json())
if 'link' in result :
nxt = next((sub for sub in result['link'] if sub['relation'] == 'next'), None)
next_url = nxt['url']
else:
next_url = None
for t in result['entry']:
print(t['fullUrl'])
return
def usage():
print (sys.argv[0] +' -l listResources -r runQuery')
def main(argv):
endpoint = 'https://ncpi-api-fhir-service-dev.kidsfirstdrc.org'
full_cookie_path = os.path.expanduser('~/.keys/kf_cookies.json')
print(full_cookie_path)
with open(full_cookie_path) as f:
cookies = json.load(f)
searchClient = FHIRSearchClient(endpoint, cookies)
try:
opts, args = getopt.getopt(argv, "hlr:", ["help", "listResources", "runQuery"])
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-l", "--listTables"):
searchClient.listResources()
elif opt in ("-r", "--runQuery"):
searchClient.runQuery(arg)
if __name__ == "__main__":
main(sys.argv[1:]) | scripts/fhirpy/ncpi_fhir_requests_example.py | import requests
import os.path
import json
import pprint
import sys
import getopt
class FHIRSearchClient:
''' Class to call FHIR server directly as a GA4GHSearch-like client
This does not use the fhirpy library '''
def __init__(self, hostURL, cookies, debug=False ):
self.hostURL = hostURL
self.debug = debug
self.headers = {
'content-type': 'application/json'
}
self.cookies = cookies
def runQuery(self, query):
next_url = "{}/Patient?gender={}".format(self.hostURL, query)
pageCount = 0
#resultRows = []
print ("_Retrieving the query_")
if self.debug: print(self.cookies)
while next_url != None :
if self.debug:
print(next_url)
pageCount += 1
print ("____Page{}_______________".format(pageCount))
response = requests.request("GET", next_url, cookies=self.cookies)
if self.debug:
print(response.content)
result = (response.json())
if self.debug:
print(result)
if 'link' in result :
nxt = next((sub for sub in result['link'] if sub['relation'] == 'next'), None)
if nxt == None:
next_url = None
else:
next_url = nxt['url']
else:
next_url = None
for t in result['entry']:
print('patient id :',t['resource']['id'])
# if rowCount > 0:
# resultRows.append(result['data'])
# for r in result['data']:
# resultRows.append([*r.values()])
# return resultRows
def listResources(self):
next_url = self.hostURL + "/StructureDefinition"
pageCount = 0
resultRows = []
print ("_Retrieving the resource list_")
while next_url != None :
if self.debug:
pprint.pprint(next_url)
pageCount += 1
print ("____Page{}_______________".format(pageCount))
#response = requests.get(next_url, headers=self.headers)
response = requests.get(next_url, cookies=self.cookies)
if self.debug:
print(response.content)
result = (response.json())
if 'link' in result :
nxt = next((sub for sub in result['link'] if sub['relation'] == 'next'), None)
next_url = nxt['url']
else:
next_url = None
for t in result['entry']:
print(t['fullUrl'])
return
def usage():
print (sys.argv[0] +' -l listResources -r runQuery')
def main(argv):
endpoint = 'https://ncpi-api-fhir-service-dev.kidsfirstdrc.org'
full_cookie_path = os.path.expanduser('~/.keys/kf_cookies.json')
print(full_cookie_path)
with open(full_cookie_path) as f:
cookies = json.load(f)
searchClient = FHIRSearchClient(endpoint, cookies)
try:
opts, args = getopt.getopt(argv, "hlr:", ["help", "listResources", "runQuery"])
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-l", "--listTables"):
searchClient.listResources()
elif opt in ("-r", "--runQuery"):
searchClient.runQuery(arg)
if __name__ == "__main__":
main(sys.argv[1:]) | 0.047702 | 0.075278 |
import frappe
from datetime import date
import calendar
from frappe import _
from frappe.utils.data import flt
def execute(filters=None):
columns, data = [], []
columns = get_columns()
tdata = get_emp_list(filters)
row = []
for item in tdata:
item_break = item[5]
sub_item = item_break[1:-1]
split_sub_item = sub_item.split(', {')
for elem in split_sub_item:
if elem.count('{')==0:
sse = elem[:-1].split(',')
sc = sse[1].split(':')[1][1:-1]
if row.count(sc[:-1]) == 0:
row.append(sc[:-1])
else:
esse = elem[1:-1].split(',')
sc = esse[1].split(':')[1][1:-1]
if row.count(sc[:-1]) == 0:
row.append(sc[:-1])
row.sort()
for item in tdata:
item_break = item[5]
sub_item = item_break[1:-1]
split_sub_item = sub_item.split(', {')
col = []
for el in row:
col.append({'amount':0,'sc':el})
for elem in split_sub_item:
if elem.count('{')==0:
csse = elem[:-1].split(',')
amount = csse[0].split(':')[1]
sc = csse[1].split(':')[1][1:-1]
index = in_dictlist('sc',sc[:-1], col)
col[index].update({'amount':amount})
else:
esse = elem[1:-1].split(',')
amount = esse[0].split(':')[1]
sc = esse[1].split(':')[1][1:-1]
index = in_dictlist('sc',sc[:-1], col)
col[index].update({'amount':amount})
total = 0
for idx,value in enumerate(row):
item.append(flt(col[idx]['amount']))
total = total + flt(col[idx]['amount'])
item.append(total)
item.pop(5)
row.append("Total")
columns += row
data = tdata
return columns, data
def in_dictlist(key, value, my_dictlist):
for index,entry in enumerate(my_dictlist):
if entry[key] == value:
return index
return {}
def get_columns():
columns = ["Department Code",_("Employee")+":Link/Employee:140","Employee Name","Salary Structure","Date of Joining"]
return columns
@frappe.whitelist()
def get_joining_relieving_condition(start_date,end_date):
cond = """
and ifnull(t1.date_of_joining, '0000-00-00') <= '%(end_date)s'
and ifnull(t1.relieving_date, '2199-12-31') >= '%(start_date)s'
""" % {"start_date": start_date, "end_date": end_date}
return cond
@frappe.whitelist()
def get_emp_list(filters):
"""
Returns list of active employees based on selected criteria
and for which salary structure exists
"""
today = date.today()
f = calendar.monthrange(int(today.strftime("%Y")), int(today.strftime("%m")))
start_date = today.strftime("%Y-%m-")+ str(f[0])
end_date = today.strftime("%Y-%m-")+ str(f[1])
cond = get_joining_relieving_condition(start_date,end_date)
condition = ''
condition = """and payroll_frequency = '%(payroll_frequency)s'"""% {"payroll_frequency": "Monthly"}
sal_struct = frappe.db.sql_list("""
select
name from `tabSalary Structure`
where
docstatus = 1 and
is_active = 'Yes'
and company = %(company)s
and currency = %(currency)s and
ifnull(salary_slip_based_on_timesheet,0) = %(salary_slip_based_on_timesheet)s
{condition}""".format(condition=condition),
{"company": "Human Capital Group", "currency": "BDT", "salary_slip_based_on_timesheet":0})
if sal_struct:
cond += "and t2.salary_structure IN %(sal_struct)s "
cond += "and t2.payroll_payable_account = %(payroll_payable_account)s "
cond += "and %(from_date)s >= t2.from_date"
emp_list = frappe.db.sql("""
select
distinct t1.department_code, t1.name as employee, t1.employee_name, t2.salary_structure, sd.parent, sd.sales,
t1.date_of_joining, t1.status
from
`tabEmployee` t1, `tabSalary Structure Assignment` t2
LEFT JOIN
( SELECT parent, CONCAT(
'[',
GROUP_CONCAT( CONCAT( '{ "amount":', amount, ', "salary_component":"', salary_component, '" }' ) SEPARATOR ', '),
']' ) sales FROM `tabSalary Detail` GROUP BY parent ) sd ON sd.parent = t2.salary_structure
where
t1.name = t2.employee
and t2.docstatus = 1
and t1.status = "Active"
%s order by t1.department_code asc, t2.from_date desc
""" % cond, {"sal_struct": tuple(sal_struct), "from_date": filters.ending_date, "payroll_payable_account": "Payroll Payable - T"}, as_dict=True)
rdata = []
names = ""
for item in emp_list:
if item.employee not in names:
names += item.employee
rdata.append([item.department_code,item.employee,item.employee_name, item.salary_structure, item.date_of_joining, item.sales])
return rdata | tiger_app/tiger_app/report/salary_details_report/salary_details_report.py |
import frappe
from datetime import date
import calendar
from frappe import _
from frappe.utils.data import flt
def execute(filters=None):
columns, data = [], []
columns = get_columns()
tdata = get_emp_list(filters)
row = []
for item in tdata:
item_break = item[5]
sub_item = item_break[1:-1]
split_sub_item = sub_item.split(', {')
for elem in split_sub_item:
if elem.count('{')==0:
sse = elem[:-1].split(',')
sc = sse[1].split(':')[1][1:-1]
if row.count(sc[:-1]) == 0:
row.append(sc[:-1])
else:
esse = elem[1:-1].split(',')
sc = esse[1].split(':')[1][1:-1]
if row.count(sc[:-1]) == 0:
row.append(sc[:-1])
row.sort()
for item in tdata:
item_break = item[5]
sub_item = item_break[1:-1]
split_sub_item = sub_item.split(', {')
col = []
for el in row:
col.append({'amount':0,'sc':el})
for elem in split_sub_item:
if elem.count('{')==0:
csse = elem[:-1].split(',')
amount = csse[0].split(':')[1]
sc = csse[1].split(':')[1][1:-1]
index = in_dictlist('sc',sc[:-1], col)
col[index].update({'amount':amount})
else:
esse = elem[1:-1].split(',')
amount = esse[0].split(':')[1]
sc = esse[1].split(':')[1][1:-1]
index = in_dictlist('sc',sc[:-1], col)
col[index].update({'amount':amount})
total = 0
for idx,value in enumerate(row):
item.append(flt(col[idx]['amount']))
total = total + flt(col[idx]['amount'])
item.append(total)
item.pop(5)
row.append("Total")
columns += row
data = tdata
return columns, data
def in_dictlist(key, value, my_dictlist):
for index,entry in enumerate(my_dictlist):
if entry[key] == value:
return index
return {}
def get_columns():
columns = ["Department Code",_("Employee")+":Link/Employee:140","Employee Name","Salary Structure","Date of Joining"]
return columns
@frappe.whitelist()
def get_joining_relieving_condition(start_date,end_date):
cond = """
and ifnull(t1.date_of_joining, '0000-00-00') <= '%(end_date)s'
and ifnull(t1.relieving_date, '2199-12-31') >= '%(start_date)s'
""" % {"start_date": start_date, "end_date": end_date}
return cond
@frappe.whitelist()
def get_emp_list(filters):
"""
Returns list of active employees based on selected criteria
and for which salary structure exists
"""
today = date.today()
f = calendar.monthrange(int(today.strftime("%Y")), int(today.strftime("%m")))
start_date = today.strftime("%Y-%m-")+ str(f[0])
end_date = today.strftime("%Y-%m-")+ str(f[1])
cond = get_joining_relieving_condition(start_date,end_date)
condition = ''
condition = """and payroll_frequency = '%(payroll_frequency)s'"""% {"payroll_frequency": "Monthly"}
sal_struct = frappe.db.sql_list("""
select
name from `tabSalary Structure`
where
docstatus = 1 and
is_active = 'Yes'
and company = %(company)s
and currency = %(currency)s and
ifnull(salary_slip_based_on_timesheet,0) = %(salary_slip_based_on_timesheet)s
{condition}""".format(condition=condition),
{"company": "Human Capital Group", "currency": "BDT", "salary_slip_based_on_timesheet":0})
if sal_struct:
cond += "and t2.salary_structure IN %(sal_struct)s "
cond += "and t2.payroll_payable_account = %(payroll_payable_account)s "
cond += "and %(from_date)s >= t2.from_date"
emp_list = frappe.db.sql("""
select
distinct t1.department_code, t1.name as employee, t1.employee_name, t2.salary_structure, sd.parent, sd.sales,
t1.date_of_joining, t1.status
from
`tabEmployee` t1, `tabSalary Structure Assignment` t2
LEFT JOIN
( SELECT parent, CONCAT(
'[',
GROUP_CONCAT( CONCAT( '{ "amount":', amount, ', "salary_component":"', salary_component, '" }' ) SEPARATOR ', '),
']' ) sales FROM `tabSalary Detail` GROUP BY parent ) sd ON sd.parent = t2.salary_structure
where
t1.name = t2.employee
and t2.docstatus = 1
and t1.status = "Active"
%s order by t1.department_code asc, t2.from_date desc
""" % cond, {"sal_struct": tuple(sal_struct), "from_date": filters.ending_date, "payroll_payable_account": "Payroll Payable - T"}, as_dict=True)
rdata = []
names = ""
for item in emp_list:
if item.employee not in names:
names += item.employee
rdata.append([item.department_code,item.employee,item.employee_name, item.salary_structure, item.date_of_joining, item.sales])
return rdata | 0.157655 | 0.200108 |
from enum import Enum
import uuid
from typing import Any, Optional, List
from ._helpers import construct_iso8601, process_row
from ._generated.models import (
BatchQueryRequest as InternalLogQueryRequest,
BatchQueryResponse,
)
class LogsTable(object):
"""Contains the columns and rows for one table in a query response.
All required parameters must be populated in order to send to Azure.
:ivar name: Required. The name of the table.
:vartype name: str
:ivar columns: The labels of columns in this table.
:vartype columns: list[str]
:ivar column_types: The types of columns in this table.
:vartype column_types: list[object]
:ivar rows: Required. The resulting rows from this query.
:vartype rows: list[~azure.monitor.query.LogsTableRow]
"""
def __init__(self, **kwargs):
# type: (Any) -> None
self.name = kwargs.pop("name", None) # type: str
self.columns = kwargs.pop("columns", None) # type: Optional[str]
self.columns_types = kwargs.pop("column_types", None) # type: Optional[Any]
_rows = kwargs.pop("rows", None)
self.rows = [
LogsTableRow(
row=row,
row_index=ind,
col_types=self.columns_types,
columns=self.columns,
)
for ind, row in enumerate(_rows)
]
@classmethod
def _from_generated(cls, generated):
return cls(
name=generated.name,
columns=[col.name for col in generated.columns],
column_types=[col.type for col in generated.columns],
rows=generated.rows,
)
class LogsTableRow(object):
"""Represents a single row in logs table.
This type is gettable by both column name and column index.
:ivar int index: The index of the row in the table
"""
def __init__(self, **kwargs):
# type: (Any) -> None
_col_types = kwargs["col_types"]
row = kwargs["row"]
self._row = process_row(_col_types, row)
self.index = kwargs["row_index"]
_columns = kwargs["columns"]
self._row_dict = {_columns[i]: self._row[i] for i in range(len(self._row))}
def __iter__(self):
"""This will iterate over the row directly."""
return iter(self._row)
def __len__(self):
return len(self._row)
def __repr__(self):
return repr(self._row)
def __getitem__(self, column):
"""This type must be subscriptable directly to row.
Must be gettable by both column name and row index
:param column: The name of the column or the index of the element in a row.
:type column: str or int
"""
try:
return self._row_dict[column]
except KeyError:
return self._row[column]
class MetricsQueryResult(object):
"""The response to a metrics query.
:ivar cost: The integer value representing the cost of the query, for data case.
:vartype cost: int
:ivar timespan: Required. The timespan for which the data was retrieved. Its value consists of
two datetimes concatenated, separated by '/'. This may be adjusted in the future and returned
back from what was originally requested.
:vartype timespan: str
:ivar granularity: The granularity (window size) for which the metric data was returned in. This
may be adjusted in the future and returned back from what was originally requested. This is
not present if a metadata request was made.
:vartype granularity: ~datetime.timedelta
:ivar namespace: The namespace of the metrics that has been queried.
:vartype namespace: str
:ivar resource_region: The region of the resource that has been queried for metrics.
:vartype resource_region: str
:ivar metrics: Required. The value of the collection.
:vartype metrics: list[~azure.monitor.query.Metric]
"""
def __init__(self, **kwargs):
# type: (Any) -> None
self.cost = kwargs.get("cost", None)
self.timespan = kwargs["timespan"]
self.granularity = kwargs.get("granularity", None)
self.namespace = kwargs.get("namespace", None)
self.resource_region = kwargs.get("resource_region", None)
self.metrics = kwargs["metrics"]
@classmethod
def _from_generated(cls, generated):
if not generated:
return cls()
return cls(
cost=generated.cost,
timespan=generated.timespan,
granularity=generated.interval,
namespace=generated.namespace,
resource_region=generated.resourceregion,
metrics=MetricsList(metrics=[
Metric._from_generated(m) for m in generated.value # pylint: disable=protected-access
]),
)
class MetricsList(list):
"""Custom list for metrics
"""
def __init__(self, **kwargs): # pylint: disable=super-init-not-called
self._metrics = kwargs['metrics']
self._metric_names = {val.name: ind for ind, val in enumerate(self._metrics)}
def __iter__(self):
return iter(self._metrics)
def __len__(self):
return len(self._metrics)
def __repr__(self):
return repr(self._metrics)
def __getitem__(self, metric):
try:
return self._metrics[metric]
except TypeError: # TypeError: list indices must be integers or slices, not str
return self._metrics[self._metric_names[metric]]
class LogsBatchQuery(object):
"""A single request in a batch. The batch query API accepts a list of these objects.
:param workspace_id: Workspace Id to be included in the query.
:type workspace_id: str
:param query: The Analytics query. Learn more about the `Analytics query syntax
<https://azure.microsoft.com/documentation/articles/app-insights-analytics-reference/>`_.
:type query: str
:keyword timespan: Required. The timespan for which to query the data. This can be a timedelta,
a timedelta and a start datetime, or a start datetime/end datetime.
:paramtype timespan: ~datetime.timedelta or tuple[~datetime.datetime, ~datetime.timedelta]
or tuple[~datetime.datetime, ~datetime.datetime]
:keyword additional_workspaces: A list of workspaces that are included in the query.
These can be qualified workspace names, workspace Ids, or Azure resource Ids.
:paramtype additional_workspaces: list[str]
:keyword int server_timeout: the server timeout. The default timeout is 3 minutes,
and the maximum timeout is 10 minutes.
:keyword bool include_statistics: To get information about query statistics.
:keyword bool include_visualization: In the query language, it is possible to specify different
visualization options. By default, the API does not return information regarding the type of
visualization to show.
"""
def __init__(
self, workspace_id, query, **kwargs
): # pylint: disable=super-init-not-called
# type: (str, str, Any) -> None
if "timespan" not in kwargs:
raise TypeError(
"LogsBatchQuery() missing 1 required keyword-only argument: 'timespan'"
)
include_statistics = kwargs.pop("include_statistics", False)
include_visualization = kwargs.pop("include_visualization", False)
server_timeout = kwargs.pop("server_timeout", None)
prefer = ""
if server_timeout:
prefer += "wait=" + str(server_timeout)
if include_statistics:
if len(prefer) > 0:
prefer += ","
prefer += "include-statistics=true"
if include_visualization:
if len(prefer) > 0:
prefer += ","
prefer += "include-render=true"
headers = {"Prefer": prefer}
timespan = construct_iso8601(kwargs.pop("timespan"))
additional_workspaces = kwargs.pop("additional_workspaces", None)
self.id = str(uuid.uuid4())
self.body = {
"query": query,
"timespan": timespan,
"workspaces": additional_workspaces,
}
self.headers = headers
self.workspace = workspace_id
def _to_generated(self):
return InternalLogQueryRequest(
id=self.id, body=self.body, headers=self.headers, workspace=self.workspace
)
class LogsQueryResult(object):
"""The LogsQueryResult type is returned when the response of a query is a success.
:ivar tables: The list of tables, columns and rows.
:vartype tables: list[~azure.monitor.query.LogsTable]
:ivar statistics: This will include a statistics property in the response that describes various
performance statistics such as query execution time and resource usage.
:vartype statistics: Mapping
:ivar visualization: This will include a visualization property in the response that specifies the type of
visualization selected by the query and any properties for that visualization.
:vartype visualization: Mapping
:ivar status: The status of the result.
Always 'Success' for an instance of a LogsQueryResult.
:vartype status: ~azure.monitor.query.LogsQueryStatus
"""
def __init__(self, **kwargs):
self.tables = kwargs.get("tables", None)
self.statistics = kwargs.get("statistics", None)
self.visualization = kwargs.get("visualization", None)
self.status = LogsQueryStatus.SUCCESS
def __iter__(self):
return iter(self.tables)
@classmethod
def _from_generated(cls, generated):
if not generated:
return cls()
tables = None
if isinstance(generated, BatchQueryResponse):
generated = generated.body
if generated.tables is not None:
tables = [
LogsTable._from_generated(table) # pylint: disable=protected-access
for table in generated.tables
]
return cls(
tables=tables,
statistics=generated.statistics,
visualization=generated.render,
)
class MetricNamespaceClassification(str, Enum):
"""Kind of namespace"""
PLATFORM = "Platform"
CUSTOM = "Custom"
QOS = "Qos"
class MetricNamespace(object):
"""Metric namespace class specifies the metadata for a metric namespace.
:ivar id: The ID of the metricNamespace.
:vartype id: str
:ivar type: The type of the namespace.
:vartype type: str
:ivar name: The name of the namespace.
:vartype name: str
:ivar fully_qualified_namespace: The fully qualified namespace name.
:vartype fully_qualified_namespace: str
:ivar namespace_classification: Kind of namespace. Possible values include: "Platform", "Custom", "Qos".
:vartype namespace_classification: str or ~azure.monitor.query.MetricNamespaceClassification
"""
def __init__(self, **kwargs):
self.id = kwargs.get("id", None)
self.type = kwargs.get("type", None)
self.name = kwargs.get("name", None)
self.fully_qualified_namespace = kwargs.get("fully_qualified_namespace", None)
self.namespace_classification = kwargs.get("namespace_classification", None)
@classmethod
def _from_generated(cls, generated):
if not generated:
return cls()
fully_qualified_namespace = None
if generated.properties:
fully_qualified_namespace = generated.properties.metric_namespace_name
return cls(
id=generated.id,
type=generated.type,
name=generated.name,
fully_qualified_namespace=fully_qualified_namespace,
namespace_classification=generated.classification,
)
class MetricClass(str, Enum):
"""The class of the metric."""
AVAILABILITY = "Availability"
TRANSACTIONS = "Transactions"
ERRORS = "Errors"
LATENCY = "Latency"
SATURATION = "Saturation"
class MetricDefinition(object): # pylint: disable=too-many-instance-attributes
"""Metric definition class specifies the metadata for a metric.
:ivar dimension_required: Flag to indicate whether the dimension is required.
:vartype dimension_required: bool
:ivar resource_id: the resource identifier of the resource that emitted the metric.
:vartype resource_id: str
:ivar namespace: the namespace the metric belongs to.
:vartype namespace: str
:ivar name: the name and the display name of the metric, i.e. it is a localizable string.
:vartype name: str
:ivar unit: the unit of the metric. Possible values include: "Count", "Bytes", "Seconds",
"CountPerSecond", "BytesPerSecond", "Percent", "MilliSeconds", "ByteSeconds", "Unspecified",
"Cores", "MilliCores", "NanoCores", "BitsPerSecond".
:vartype unit: str or ~azure.monitor.query.MetricUnit
:ivar primary_aggregation_type: the primary aggregation type value defining how to use the
values for display. Possible values include: "None", "Average", "Count", "Minimum", "Maximum",
"Total".
:vartype primary_aggregation_type: str or ~azure.monitor.query.MetricAggregationType
:ivar metric_class: The class of the metric. Possible values include: "Availability",
"Transactions", "Errors", "Latency", "Saturation".
:vartype metric_class: str or ~azure.monitor.query.MetricClass
:ivar supported_aggregation_types: the collection of what aggregation types are supported.
:vartype supported_aggregation_types: list[str or ~azure.monitor.query.MetricAggregationType]
:ivar metric_availabilities: the collection of what aggregation intervals are available to be
queried.
:vartype metric_availabilities: list[~azure.monitor.query.MetricAvailability]
:ivar id: the resource identifier of the metric definition.
:vartype id: str
:ivar dimensions: the name and the display name of the dimension, i.e. it is a localizable
string.
:vartype dimensions: list[str]
"""
def __init__(self, **kwargs):
# type: (Any) -> None
self.dimension_required = kwargs.get(
"dimension_required", None
) # type: Optional[bool]
self.resource_id = kwargs.get("resource_id", None) # type: Optional[str]
self.namespace = kwargs.get("namespace", None) # type: Optional[str]
self.name = kwargs.get("name", None) # type: Optional[str]
self.unit = kwargs.get("unit", None) # type: Optional[str]
self.primary_aggregation_type = kwargs.get(
"primary_aggregation_type", None
) # type: Optional[str]
self.supported_aggregation_types = kwargs.get(
"supported_aggregation_types", None
) # type: Optional[str]
self.metric_availabilities = kwargs.get(
"metric_availabilities", None
) # type: List[MetricAvailability]
self.id = kwargs.get("id", None) # type: Optional[str]
self.dimensions = kwargs.get("dimensions", None) # type: Optional[List[str]]
self.metric_class = kwargs.get("metric_class", None) # type: Optional[str]
@classmethod
def _from_generated(cls, generated):
if not generated:
return cls()
dimensions = None
if generated.dimensions is not None:
dimensions = [d.value for d in generated.dimensions]
return cls(
dimension_required=generated.is_dimension_required,
resource_id=generated.resource_id,
namespace=generated.namespace,
name=generated.name.value,
unit=generated.unit,
primary_aggregation_type=generated.primary_aggregation_type,
supported_aggregation_types=generated.supported_aggregation_types,
metric_class=generated.metric_class,
metric_availabilities=[
MetricAvailability._from_generated( # pylint: disable=protected-access
val
)
for val in generated.metric_availabilities
],
id=generated.id,
dimensions=dimensions,
)
class MetricValue(object):
"""Represents a metric value.
:ivar timestamp: The timestamp for the metric value.
:vartype timestamp: ~datetime.datetime
:ivar average: The average value in the time range.
:vartype average: float
:ivar minimum: The least value in the time range.
:vartype minimum: float
:ivar maximum: The greatest value in the time range.
:vartype maximum: float
:ivar total: The sum of all of the values in the time range.
:vartype total: float
:ivar count: The number of samples in the time range. Can be used to determine the number of
values that contributed to the average value.
:vartype count: float
"""
def __init__(self, **kwargs):
# type: (Any) -> None
self.timestamp = kwargs["timestamp"]
self.average = kwargs.get("average", None)
self.minimum = kwargs.get("minimum", None)
self.maximum = kwargs.get("maximum", None)
self.total = kwargs.get("total", None)
self.count = kwargs.get("count", None)
@classmethod
def _from_generated(cls, generated):
if not generated:
return cls()
return cls(
timestamp=generated.time_stamp,
average=generated.average,
minimum=generated.minimum,
maximum=generated.maximum,
total=generated.total,
count=generated.count,
)
class Metric(object):
"""The result data of a single metric name.
:ivar id: The metric Id.
:vartype id: str
:ivar type: The resource type of the metric resource.
:vartype type: str
:ivar name: The name of the metric.
:vartype name: str
:ivar unit: The unit of the metric. To access these values, use the MetricUnit enum.
Possible values include: "Count", "Bytes",
"Seconds", "CountPerSecond", "BytesPerSecond", "Percent", "MilliSeconds", "ByteSeconds",
"Unspecified", "Cores", "MilliCores", "NanoCores", "BitsPerSecond".
:vartype unit: str
:ivar timeseries: The time series returned when a data query is performed.
:vartype timeseries: list[~azure.monitor.query.TimeSeriesElement]
:ivar display_description: Detailed description of this metric.
:vartype display_description: str
"""
def __init__(self, **kwargs):
# type: (Any) -> None
self.id = kwargs["id"]
self.type = kwargs["type"]
self.name = kwargs["name"]
self.unit = kwargs["unit"]
self.timeseries = kwargs["timeseries"]
self.display_description = kwargs["display_description"]
@classmethod
def _from_generated(cls, generated):
if not generated:
return cls()
return cls(
id=generated.id,
type=generated.type,
name=generated.name.value,
unit=generated.unit,
timeseries=[
TimeSeriesElement._from_generated(t) # pylint: disable=protected-access
for t in generated.timeseries
],
display_description=generated.display_description,
)
class TimeSeriesElement(object):
"""A time series result type. The discriminator value is always TimeSeries in this case.
:ivar metadata_values: The metadata values returned if $filter was specified in the call.
:vartype metadata_values: dict(str, str)
:ivar data: An array of data points representing the metric values. This is only returned if
a result type of data is specified.
:vartype data: list[~azure.monitor.query.MetricValue]
"""
def __init__(self, **kwargs):
# type: (Any) -> None
self.metadata_values = kwargs.get("metadata_values", None)
self.data = kwargs.get("data", None)
@classmethod
def _from_generated(cls, generated):
if not generated:
return cls()
return cls(
metadata_values={
obj.name.value: obj.value for obj in generated.metadatavalues
},
data=[
MetricValue._from_generated(val) for val in generated.data # pylint: disable=protected-access
],
)
class MetricAvailability(object):
"""Metric availability specifies the time grain (aggregation interval or frequency)
and the retention period for that time grain.
:ivar granularity: the time grain specifies the aggregation interval for the metric.
:vartype granularity: ~datetime.timedelta
:ivar retention: the retention period for the metric at the specified timegrain.
:vartype retention: ~datetime.timedelta
"""
def __init__(self, **kwargs):
# type: (Any) -> None
self.granularity = kwargs.get("granularity", None)
self.retention = kwargs.get("retention", None)
@classmethod
def _from_generated(cls, generated):
if not generated:
return cls()
return cls(granularity=generated.time_grain, retention=generated.retention)
class MetricAggregationType(str, Enum):
"""The aggregation type of the metric."""
NONE = "None"
AVERAGE = "Average"
COUNT = "Count"
MINIMUM = "Minimum"
MAXIMUM = "Maximum"
TOTAL = "Total"
class MetricUnit(str, Enum):
"""The unit of the metric."""
COUNT = "Count"
BYTES = "Bytes"
SECONDS = "Seconds"
COUNT_PER_SECOND = "CountPerSecond"
BYTES_PER_SECOND = "BytesPerSecond"
PERCENT = "Percent"
MILLI_SECONDS = "MilliSeconds"
BYTE_SECONDS = "ByteSeconds"
UNSPECIFIED = "Unspecified"
CORES = "Cores"
MILLI_CORES = "MilliCores"
NANO_CORES = "NanoCores"
BITS_PER_SECOND = "BitsPerSecond"
class LogsQueryPartialResult(object):
"""The LogsQueryPartialResult type is returned when the response of a query is a
partial success (or partial failure).
:ivar partial_data: The list of tables, columns and rows.
:vartype partial_data: list[~azure.monitor.query.LogsTable]
:ivar statistics: This will include a statistics property in the response that describes various
performance statistics such as query execution time and resource usage.
:vartype statistics: Mapping
:ivar visualization: This will include a visualization property in the response that specifies the type of
visualization selected by the query and any properties for that visualization.
:vartype visualization: Mapping
:ivar partial_error: The partial errror info
:vartype partial_error: ~azure.monitor.query.LogsQueryError
:ivar status: The status of the result. Always 'PartialError' for an instance of a LogsQueryPartialResult.
:vartype status: ~azure.monitor.query.LogsQueryStatus
"""
def __init__(self, **kwargs):
self.partial_data = kwargs.get("partial_data", None)
self.partial_error = kwargs.get("partial_error", None)
self.statistics = kwargs.get("statistics", None)
self.visualization = kwargs.get("visualization", None)
self.status = LogsQueryStatus.PARTIAL
def __iter__(self):
return iter(self.partial_data)
@classmethod
def _from_generated(cls, generated, error): # pylint: disable=arguments-differ
if not generated:
return cls()
partial_data = None
if isinstance(generated, BatchQueryResponse):
generated = generated.body
if generated.tables is not None:
partial_data = [
LogsTable._from_generated(table) # pylint: disable=protected-access
for table in generated.tables
]
return cls(
partial_data=partial_data,
partial_error=error._from_generated(generated.error), # pylint: disable=protected-access
statistics=generated.statistics,
visualization=generated.render,
)
class LogsQueryStatus(str, Enum):
"""The status of the result object."""
PARTIAL = "PartialError"
SUCCESS = "Success"
FAILURE = "Failure" | sdk/monitor/azure-monitor-query/azure/monitor/query/_models.py |
from enum import Enum
import uuid
from typing import Any, Optional, List
from ._helpers import construct_iso8601, process_row
from ._generated.models import (
BatchQueryRequest as InternalLogQueryRequest,
BatchQueryResponse,
)
class LogsTable(object):
"""Contains the columns and rows for one table in a query response.
All required parameters must be populated in order to send to Azure.
:ivar name: Required. The name of the table.
:vartype name: str
:ivar columns: The labels of columns in this table.
:vartype columns: list[str]
:ivar column_types: The types of columns in this table.
:vartype column_types: list[object]
:ivar rows: Required. The resulting rows from this query.
:vartype rows: list[~azure.monitor.query.LogsTableRow]
"""
def __init__(self, **kwargs):
# type: (Any) -> None
self.name = kwargs.pop("name", None) # type: str
self.columns = kwargs.pop("columns", None) # type: Optional[str]
self.columns_types = kwargs.pop("column_types", None) # type: Optional[Any]
_rows = kwargs.pop("rows", None)
self.rows = [
LogsTableRow(
row=row,
row_index=ind,
col_types=self.columns_types,
columns=self.columns,
)
for ind, row in enumerate(_rows)
]
@classmethod
def _from_generated(cls, generated):
return cls(
name=generated.name,
columns=[col.name for col in generated.columns],
column_types=[col.type for col in generated.columns],
rows=generated.rows,
)
class LogsTableRow(object):
"""Represents a single row in logs table.
This type is gettable by both column name and column index.
:ivar int index: The index of the row in the table
"""
def __init__(self, **kwargs):
# type: (Any) -> None
_col_types = kwargs["col_types"]
row = kwargs["row"]
self._row = process_row(_col_types, row)
self.index = kwargs["row_index"]
_columns = kwargs["columns"]
self._row_dict = {_columns[i]: self._row[i] for i in range(len(self._row))}
def __iter__(self):
"""This will iterate over the row directly."""
return iter(self._row)
def __len__(self):
return len(self._row)
def __repr__(self):
return repr(self._row)
def __getitem__(self, column):
"""This type must be subscriptable directly to row.
Must be gettable by both column name and row index
:param column: The name of the column or the index of the element in a row.
:type column: str or int
"""
try:
return self._row_dict[column]
except KeyError:
return self._row[column]
class MetricsQueryResult(object):
"""The response to a metrics query.
:ivar cost: The integer value representing the cost of the query, for data case.
:vartype cost: int
:ivar timespan: Required. The timespan for which the data was retrieved. Its value consists of
two datetimes concatenated, separated by '/'. This may be adjusted in the future and returned
back from what was originally requested.
:vartype timespan: str
:ivar granularity: The granularity (window size) for which the metric data was returned in. This
may be adjusted in the future and returned back from what was originally requested. This is
not present if a metadata request was made.
:vartype granularity: ~datetime.timedelta
:ivar namespace: The namespace of the metrics that has been queried.
:vartype namespace: str
:ivar resource_region: The region of the resource that has been queried for metrics.
:vartype resource_region: str
:ivar metrics: Required. The value of the collection.
:vartype metrics: list[~azure.monitor.query.Metric]
"""
def __init__(self, **kwargs):
# type: (Any) -> None
self.cost = kwargs.get("cost", None)
self.timespan = kwargs["timespan"]
self.granularity = kwargs.get("granularity", None)
self.namespace = kwargs.get("namespace", None)
self.resource_region = kwargs.get("resource_region", None)
self.metrics = kwargs["metrics"]
@classmethod
def _from_generated(cls, generated):
if not generated:
return cls()
return cls(
cost=generated.cost,
timespan=generated.timespan,
granularity=generated.interval,
namespace=generated.namespace,
resource_region=generated.resourceregion,
metrics=MetricsList(metrics=[
Metric._from_generated(m) for m in generated.value # pylint: disable=protected-access
]),
)
class MetricsList(list):
"""Custom list for metrics
"""
def __init__(self, **kwargs): # pylint: disable=super-init-not-called
self._metrics = kwargs['metrics']
self._metric_names = {val.name: ind for ind, val in enumerate(self._metrics)}
def __iter__(self):
return iter(self._metrics)
def __len__(self):
return len(self._metrics)
def __repr__(self):
return repr(self._metrics)
def __getitem__(self, metric):
try:
return self._metrics[metric]
except TypeError: # TypeError: list indices must be integers or slices, not str
return self._metrics[self._metric_names[metric]]
class LogsBatchQuery(object):
"""A single request in a batch. The batch query API accepts a list of these objects.
:param workspace_id: Workspace Id to be included in the query.
:type workspace_id: str
:param query: The Analytics query. Learn more about the `Analytics query syntax
<https://azure.microsoft.com/documentation/articles/app-insights-analytics-reference/>`_.
:type query: str
:keyword timespan: Required. The timespan for which to query the data. This can be a timedelta,
a timedelta and a start datetime, or a start datetime/end datetime.
:paramtype timespan: ~datetime.timedelta or tuple[~datetime.datetime, ~datetime.timedelta]
or tuple[~datetime.datetime, ~datetime.datetime]
:keyword additional_workspaces: A list of workspaces that are included in the query.
These can be qualified workspace names, workspace Ids, or Azure resource Ids.
:paramtype additional_workspaces: list[str]
:keyword int server_timeout: the server timeout. The default timeout is 3 minutes,
and the maximum timeout is 10 minutes.
:keyword bool include_statistics: To get information about query statistics.
:keyword bool include_visualization: In the query language, it is possible to specify different
visualization options. By default, the API does not return information regarding the type of
visualization to show.
"""
def __init__(
self, workspace_id, query, **kwargs
): # pylint: disable=super-init-not-called
# type: (str, str, Any) -> None
if "timespan" not in kwargs:
raise TypeError(
"LogsBatchQuery() missing 1 required keyword-only argument: 'timespan'"
)
include_statistics = kwargs.pop("include_statistics", False)
include_visualization = kwargs.pop("include_visualization", False)
server_timeout = kwargs.pop("server_timeout", None)
prefer = ""
if server_timeout:
prefer += "wait=" + str(server_timeout)
if include_statistics:
if len(prefer) > 0:
prefer += ","
prefer += "include-statistics=true"
if include_visualization:
if len(prefer) > 0:
prefer += ","
prefer += "include-render=true"
headers = {"Prefer": prefer}
timespan = construct_iso8601(kwargs.pop("timespan"))
additional_workspaces = kwargs.pop("additional_workspaces", None)
self.id = str(uuid.uuid4())
self.body = {
"query": query,
"timespan": timespan,
"workspaces": additional_workspaces,
}
self.headers = headers
self.workspace = workspace_id
def _to_generated(self):
return InternalLogQueryRequest(
id=self.id, body=self.body, headers=self.headers, workspace=self.workspace
)
class LogsQueryResult(object):
"""The LogsQueryResult type is returned when the response of a query is a success.
:ivar tables: The list of tables, columns and rows.
:vartype tables: list[~azure.monitor.query.LogsTable]
:ivar statistics: This will include a statistics property in the response that describes various
performance statistics such as query execution time and resource usage.
:vartype statistics: Mapping
:ivar visualization: This will include a visualization property in the response that specifies the type of
visualization selected by the query and any properties for that visualization.
:vartype visualization: Mapping
:ivar status: The status of the result.
Always 'Success' for an instance of a LogsQueryResult.
:vartype status: ~azure.monitor.query.LogsQueryStatus
"""
def __init__(self, **kwargs):
self.tables = kwargs.get("tables", None)
self.statistics = kwargs.get("statistics", None)
self.visualization = kwargs.get("visualization", None)
self.status = LogsQueryStatus.SUCCESS
def __iter__(self):
return iter(self.tables)
@classmethod
def _from_generated(cls, generated):
if not generated:
return cls()
tables = None
if isinstance(generated, BatchQueryResponse):
generated = generated.body
if generated.tables is not None:
tables = [
LogsTable._from_generated(table) # pylint: disable=protected-access
for table in generated.tables
]
return cls(
tables=tables,
statistics=generated.statistics,
visualization=generated.render,
)
class MetricNamespaceClassification(str, Enum):
"""Kind of namespace"""
PLATFORM = "Platform"
CUSTOM = "Custom"
QOS = "Qos"
class MetricNamespace(object):
"""Metric namespace class specifies the metadata for a metric namespace.
:ivar id: The ID of the metricNamespace.
:vartype id: str
:ivar type: The type of the namespace.
:vartype type: str
:ivar name: The name of the namespace.
:vartype name: str
:ivar fully_qualified_namespace: The fully qualified namespace name.
:vartype fully_qualified_namespace: str
:ivar namespace_classification: Kind of namespace. Possible values include: "Platform", "Custom", "Qos".
:vartype namespace_classification: str or ~azure.monitor.query.MetricNamespaceClassification
"""
def __init__(self, **kwargs):
self.id = kwargs.get("id", None)
self.type = kwargs.get("type", None)
self.name = kwargs.get("name", None)
self.fully_qualified_namespace = kwargs.get("fully_qualified_namespace", None)
self.namespace_classification = kwargs.get("namespace_classification", None)
@classmethod
def _from_generated(cls, generated):
if not generated:
return cls()
fully_qualified_namespace = None
if generated.properties:
fully_qualified_namespace = generated.properties.metric_namespace_name
return cls(
id=generated.id,
type=generated.type,
name=generated.name,
fully_qualified_namespace=fully_qualified_namespace,
namespace_classification=generated.classification,
)
class MetricClass(str, Enum):
"""The class of the metric."""
AVAILABILITY = "Availability"
TRANSACTIONS = "Transactions"
ERRORS = "Errors"
LATENCY = "Latency"
SATURATION = "Saturation"
class MetricDefinition(object): # pylint: disable=too-many-instance-attributes
"""Metric definition class specifies the metadata for a metric.
:ivar dimension_required: Flag to indicate whether the dimension is required.
:vartype dimension_required: bool
:ivar resource_id: the resource identifier of the resource that emitted the metric.
:vartype resource_id: str
:ivar namespace: the namespace the metric belongs to.
:vartype namespace: str
:ivar name: the name and the display name of the metric, i.e. it is a localizable string.
:vartype name: str
:ivar unit: the unit of the metric. Possible values include: "Count", "Bytes", "Seconds",
"CountPerSecond", "BytesPerSecond", "Percent", "MilliSeconds", "ByteSeconds", "Unspecified",
"Cores", "MilliCores", "NanoCores", "BitsPerSecond".
:vartype unit: str or ~azure.monitor.query.MetricUnit
:ivar primary_aggregation_type: the primary aggregation type value defining how to use the
values for display. Possible values include: "None", "Average", "Count", "Minimum", "Maximum",
"Total".
:vartype primary_aggregation_type: str or ~azure.monitor.query.MetricAggregationType
:ivar metric_class: The class of the metric. Possible values include: "Availability",
"Transactions", "Errors", "Latency", "Saturation".
:vartype metric_class: str or ~azure.monitor.query.MetricClass
:ivar supported_aggregation_types: the collection of what aggregation types are supported.
:vartype supported_aggregation_types: list[str or ~azure.monitor.query.MetricAggregationType]
:ivar metric_availabilities: the collection of what aggregation intervals are available to be
queried.
:vartype metric_availabilities: list[~azure.monitor.query.MetricAvailability]
:ivar id: the resource identifier of the metric definition.
:vartype id: str
:ivar dimensions: the name and the display name of the dimension, i.e. it is a localizable
string.
:vartype dimensions: list[str]
"""
def __init__(self, **kwargs):
# type: (Any) -> None
self.dimension_required = kwargs.get(
"dimension_required", None
) # type: Optional[bool]
self.resource_id = kwargs.get("resource_id", None) # type: Optional[str]
self.namespace = kwargs.get("namespace", None) # type: Optional[str]
self.name = kwargs.get("name", None) # type: Optional[str]
self.unit = kwargs.get("unit", None) # type: Optional[str]
self.primary_aggregation_type = kwargs.get(
"primary_aggregation_type", None
) # type: Optional[str]
self.supported_aggregation_types = kwargs.get(
"supported_aggregation_types", None
) # type: Optional[str]
self.metric_availabilities = kwargs.get(
"metric_availabilities", None
) # type: List[MetricAvailability]
self.id = kwargs.get("id", None) # type: Optional[str]
self.dimensions = kwargs.get("dimensions", None) # type: Optional[List[str]]
self.metric_class = kwargs.get("metric_class", None) # type: Optional[str]
@classmethod
def _from_generated(cls, generated):
if not generated:
return cls()
dimensions = None
if generated.dimensions is not None:
dimensions = [d.value for d in generated.dimensions]
return cls(
dimension_required=generated.is_dimension_required,
resource_id=generated.resource_id,
namespace=generated.namespace,
name=generated.name.value,
unit=generated.unit,
primary_aggregation_type=generated.primary_aggregation_type,
supported_aggregation_types=generated.supported_aggregation_types,
metric_class=generated.metric_class,
metric_availabilities=[
MetricAvailability._from_generated( # pylint: disable=protected-access
val
)
for val in generated.metric_availabilities
],
id=generated.id,
dimensions=dimensions,
)
class MetricValue(object):
"""Represents a metric value.
:ivar timestamp: The timestamp for the metric value.
:vartype timestamp: ~datetime.datetime
:ivar average: The average value in the time range.
:vartype average: float
:ivar minimum: The least value in the time range.
:vartype minimum: float
:ivar maximum: The greatest value in the time range.
:vartype maximum: float
:ivar total: The sum of all of the values in the time range.
:vartype total: float
:ivar count: The number of samples in the time range. Can be used to determine the number of
values that contributed to the average value.
:vartype count: float
"""
def __init__(self, **kwargs):
# type: (Any) -> None
self.timestamp = kwargs["timestamp"]
self.average = kwargs.get("average", None)
self.minimum = kwargs.get("minimum", None)
self.maximum = kwargs.get("maximum", None)
self.total = kwargs.get("total", None)
self.count = kwargs.get("count", None)
@classmethod
def _from_generated(cls, generated):
if not generated:
return cls()
return cls(
timestamp=generated.time_stamp,
average=generated.average,
minimum=generated.minimum,
maximum=generated.maximum,
total=generated.total,
count=generated.count,
)
class Metric(object):
"""The result data of a single metric name.
:ivar id: The metric Id.
:vartype id: str
:ivar type: The resource type of the metric resource.
:vartype type: str
:ivar name: The name of the metric.
:vartype name: str
:ivar unit: The unit of the metric. To access these values, use the MetricUnit enum.
Possible values include: "Count", "Bytes",
"Seconds", "CountPerSecond", "BytesPerSecond", "Percent", "MilliSeconds", "ByteSeconds",
"Unspecified", "Cores", "MilliCores", "NanoCores", "BitsPerSecond".
:vartype unit: str
:ivar timeseries: The time series returned when a data query is performed.
:vartype timeseries: list[~azure.monitor.query.TimeSeriesElement]
:ivar display_description: Detailed description of this metric.
:vartype display_description: str
"""
def __init__(self, **kwargs):
# type: (Any) -> None
self.id = kwargs["id"]
self.type = kwargs["type"]
self.name = kwargs["name"]
self.unit = kwargs["unit"]
self.timeseries = kwargs["timeseries"]
self.display_description = kwargs["display_description"]
@classmethod
def _from_generated(cls, generated):
if not generated:
return cls()
return cls(
id=generated.id,
type=generated.type,
name=generated.name.value,
unit=generated.unit,
timeseries=[
TimeSeriesElement._from_generated(t) # pylint: disable=protected-access
for t in generated.timeseries
],
display_description=generated.display_description,
)
class TimeSeriesElement(object):
"""A time series result type. The discriminator value is always TimeSeries in this case.
:ivar metadata_values: The metadata values returned if $filter was specified in the call.
:vartype metadata_values: dict(str, str)
:ivar data: An array of data points representing the metric values. This is only returned if
a result type of data is specified.
:vartype data: list[~azure.monitor.query.MetricValue]
"""
def __init__(self, **kwargs):
# type: (Any) -> None
self.metadata_values = kwargs.get("metadata_values", None)
self.data = kwargs.get("data", None)
@classmethod
def _from_generated(cls, generated):
if not generated:
return cls()
return cls(
metadata_values={
obj.name.value: obj.value for obj in generated.metadatavalues
},
data=[
MetricValue._from_generated(val) for val in generated.data # pylint: disable=protected-access
],
)
class MetricAvailability(object):
"""Metric availability specifies the time grain (aggregation interval or frequency)
and the retention period for that time grain.
:ivar granularity: the time grain specifies the aggregation interval for the metric.
:vartype granularity: ~datetime.timedelta
:ivar retention: the retention period for the metric at the specified timegrain.
:vartype retention: ~datetime.timedelta
"""
def __init__(self, **kwargs):
# type: (Any) -> None
self.granularity = kwargs.get("granularity", None)
self.retention = kwargs.get("retention", None)
@classmethod
def _from_generated(cls, generated):
if not generated:
return cls()
return cls(granularity=generated.time_grain, retention=generated.retention)
class MetricAggregationType(str, Enum):
"""The aggregation type of the metric."""
NONE = "None"
AVERAGE = "Average"
COUNT = "Count"
MINIMUM = "Minimum"
MAXIMUM = "Maximum"
TOTAL = "Total"
class MetricUnit(str, Enum):
"""The unit of the metric."""
COUNT = "Count"
BYTES = "Bytes"
SECONDS = "Seconds"
COUNT_PER_SECOND = "CountPerSecond"
BYTES_PER_SECOND = "BytesPerSecond"
PERCENT = "Percent"
MILLI_SECONDS = "MilliSeconds"
BYTE_SECONDS = "ByteSeconds"
UNSPECIFIED = "Unspecified"
CORES = "Cores"
MILLI_CORES = "MilliCores"
NANO_CORES = "NanoCores"
BITS_PER_SECOND = "BitsPerSecond"
class LogsQueryPartialResult(object):
"""The LogsQueryPartialResult type is returned when the response of a query is a
partial success (or partial failure).
:ivar partial_data: The list of tables, columns and rows.
:vartype partial_data: list[~azure.monitor.query.LogsTable]
:ivar statistics: This will include a statistics property in the response that describes various
performance statistics such as query execution time and resource usage.
:vartype statistics: Mapping
:ivar visualization: This will include a visualization property in the response that specifies the type of
visualization selected by the query and any properties for that visualization.
:vartype visualization: Mapping
:ivar partial_error: The partial errror info
:vartype partial_error: ~azure.monitor.query.LogsQueryError
:ivar status: The status of the result. Always 'PartialError' for an instance of a LogsQueryPartialResult.
:vartype status: ~azure.monitor.query.LogsQueryStatus
"""
def __init__(self, **kwargs):
self.partial_data = kwargs.get("partial_data", None)
self.partial_error = kwargs.get("partial_error", None)
self.statistics = kwargs.get("statistics", None)
self.visualization = kwargs.get("visualization", None)
self.status = LogsQueryStatus.PARTIAL
def __iter__(self):
return iter(self.partial_data)
@classmethod
def _from_generated(cls, generated, error): # pylint: disable=arguments-differ
if not generated:
return cls()
partial_data = None
if isinstance(generated, BatchQueryResponse):
generated = generated.body
if generated.tables is not None:
partial_data = [
LogsTable._from_generated(table) # pylint: disable=protected-access
for table in generated.tables
]
return cls(
partial_data=partial_data,
partial_error=error._from_generated(generated.error), # pylint: disable=protected-access
statistics=generated.statistics,
visualization=generated.render,
)
class LogsQueryStatus(str, Enum):
"""The status of the result object."""
PARTIAL = "PartialError"
SUCCESS = "Success"
FAILURE = "Failure" | 0.919579 | 0.302018 |
import sys, os, argparse, shutil, math, re
def run():
# argparse Stuff
parser = argparse.ArgumentParser(description='Given an input bed file, this program will output a number of bed files, each will have same number of total base pairs. This routine is used to parallelize SomaticSeq tasks. One limitation, however, is that some regions of the genome have much higher coverage than others. This is the reason some regions run much slower than others.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Variant Call Type, i.e., snp or indel
parser.add_argument('-infile', '--input-file', type=str, help='Input merged BED file', required=True, default=None)
parser.add_argument('-num', '--num-of-files', type=int, help='1', required=False, default=1)
parser.add_argument('-outfiles', '--output-files', type=str, help='Output BED file', required=False, default=sys.stdout)
# Parse the arguments:
args = parser.parse_args()
infile = args.input_file
outfiles = args.output_files
num = args.num_of_files
return infile, outfiles, num
def fai2bed(fai, bedout):
with open(fai) as fai, open(bedout, 'w') as bed:
fai_i = fai.readline().rstrip()
while fai_i:
fai_item = fai_i.split('\t')
bed.write( '{}\t{}\t{}\n'.format(fai_item[0], '0', fai_item[1] ) )
fai_i = fai.readline().rstrip()
return bedout
def split(infile, outfiles, num):
outfilesWritten = []
out_basename = os.path.basename(outfiles)
out_directory = os.path.dirname(outfiles)
if not out_directory:
out_directory = os.curdir
with open(infile) as bedin:
line_i = bedin.readline().rstrip()
while re.match(r'track|browser|#', line_i):
line_i = bedin.readline().rstrip()
total_region_size = 0
original_regions = []
while line_i:
items = line_i.split('\t')
chr_i = items[0]
start_i = int(items[1])
end_i = int(items[2])
total_region_size = total_region_size + ( end_i - start_i )
original_regions.append( (chr_i, start_i, end_i) )
line_i = bedin.readline().rstrip()
# For each bed file, this is the total base pairs in that file
size_per_file = math.ceil( total_region_size / num )
# Go through every original region and split
current_size = 0
current_region = []
ith_split = 1
for region_i in original_regions:
chr_i = region_i[0]
start_i = region_i[1]
end_i = region_i[2]
# If the "now size" is still less than size/file requirement
if current_size + (end_i - start_i) <= size_per_file:
# Need to collect more to fulfill the size/file requirement, so append to current_region list
current_region.append( '{}\t{}\t{}\n'.format(chr_i, start_i, end_i) )
current_size = current_size + (end_i - start_i)
# If the "now size" exceeds the size/file requirement, need to start splitting:
elif current_size + (end_i - start_i) > size_per_file:
# Split a big region into a smaller regino, such that the size of "current_region" is equal to the size/file requirement:
breakpoint_i = size_per_file + start_i - current_size
# Write these regions out, , reset "current_region," then add 1 to ith_split afterward to keep track:
outfilesWritten.append( '{}{}{}.{}'.format(out_directory, os.sep, ith_split, out_basename) )
with open( '{}{}{}.{}'.format(out_directory, os.sep, ith_split, out_basename), 'w' ) as ith_out:
for line_i in current_region:
ith_out.write( line_i )
# Make sure it doesn't write a 0-bp region:
if breakpoint_i > start_i:
ith_out.write( '{}\t{}\t{}\n'.format( chr_i, start_i, breakpoint_i ) )
ith_split += 1
current_region = []
# The remaining, is the end position of the original region and the previous breakpoint:
remaining_length = end_i - breakpoint_i
remaining_region = (chr_i, breakpoint_i, end_i)
# If the remnant of the previous region is less than the size/file requirement, simply make it "current_region" and then move on:
if remaining_length <= size_per_file:
current_region.append( '{}\t{}\t{}\n'.format(chr_i, breakpoint_i, end_i) )
current_size = remaining_length
# If the renmant of the previuos region exceed the size/file requirement, it needs to be properly split until it's small enough:
elif remaining_length > size_per_file:
# Each sub-region, if large enough, will have its own file output:
while (end_i - breakpoint_i) > size_per_file:
end_j = breakpoint_i + size_per_file
outfilesWritten.append( '{}{}{}.{}'.format(out_directory, os.sep, ith_split, out_basename) )
with open( '{}{}{}.{}'.format(out_directory, os.sep, ith_split, out_basename), 'w' ) as ith_out:
if end_j > breakpoint_i:
ith_out.write( '{}\t{}\t{}\n'.format( chr_i, breakpoint_i, end_j ) )
ith_split += 1
breakpoint_i = end_j
# After every sub-region has its own bed file, the remnant is added to "current_region" to deal with the next line of the "original_regions"
current_region.append( '{}\t{}\t{}\n'.format(chr_i, breakpoint_i, end_i) )
current_size = end_i - breakpoint_i
# The final region to write out:
ithOutName = '{}{}{}.{}'.format(out_directory, os.sep, ith_split, out_basename)
outfilesWritten.append( ithOutName )
with open( ithOutName, 'w' ) as ith_out:
for line_i in current_region:
ith_out.write( line_i )
return outfilesWritten
def split_vcf_file(vcf_file, work_dir=os.curdir, num=1):
num_lines = 0
with open_textfile(vcf_file) as vcf:
line_i = vcf.readline()
header = []
while line_i.startswith('#'):
header.append(line_i)
line_i = vcf.readline()
while line_i:
num_lines += 1
line_i = vcf.readline()
lines_per_file = math.ceil( float(num_lines)/num )
with open_textfile(vcf_file) as vcf:
outnames = [ os.curdir + os.sep + str(i) + '_' + re.sub(r'.vcf(.gz)?', '', os.path.basename(vcf_file)) + '.vcf' for i in range(num) ]
outhandles = [open(i, 'w') for i in outnames]
[write_header(header, i) for i in outhandles]
line_i = vcf.readline()
while line_i.startswith('#'):
line_i = vcf.readline()
while line_i:
i = 0
n = 0
while line_i:
outhandles[n].write( line_i )
i += 1
if i == lines_per_file:
i = 0
n += 1
line_i = vcf.readline()
[i.close() for i in outhandles]
return outnames
if __name__ == '__main__':
infile, outfiles, num = run()
split(infile, outfiles, num) | somaticseq/utilities/split_Bed_into_equal_regions.py |
import sys, os, argparse, shutil, math, re
def run():
# argparse Stuff
parser = argparse.ArgumentParser(description='Given an input bed file, this program will output a number of bed files, each will have same number of total base pairs. This routine is used to parallelize SomaticSeq tasks. One limitation, however, is that some regions of the genome have much higher coverage than others. This is the reason some regions run much slower than others.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Variant Call Type, i.e., snp or indel
parser.add_argument('-infile', '--input-file', type=str, help='Input merged BED file', required=True, default=None)
parser.add_argument('-num', '--num-of-files', type=int, help='1', required=False, default=1)
parser.add_argument('-outfiles', '--output-files', type=str, help='Output BED file', required=False, default=sys.stdout)
# Parse the arguments:
args = parser.parse_args()
infile = args.input_file
outfiles = args.output_files
num = args.num_of_files
return infile, outfiles, num
def fai2bed(fai, bedout):
with open(fai) as fai, open(bedout, 'w') as bed:
fai_i = fai.readline().rstrip()
while fai_i:
fai_item = fai_i.split('\t')
bed.write( '{}\t{}\t{}\n'.format(fai_item[0], '0', fai_item[1] ) )
fai_i = fai.readline().rstrip()
return bedout
def split(infile, outfiles, num):
outfilesWritten = []
out_basename = os.path.basename(outfiles)
out_directory = os.path.dirname(outfiles)
if not out_directory:
out_directory = os.curdir
with open(infile) as bedin:
line_i = bedin.readline().rstrip()
while re.match(r'track|browser|#', line_i):
line_i = bedin.readline().rstrip()
total_region_size = 0
original_regions = []
while line_i:
items = line_i.split('\t')
chr_i = items[0]
start_i = int(items[1])
end_i = int(items[2])
total_region_size = total_region_size + ( end_i - start_i )
original_regions.append( (chr_i, start_i, end_i) )
line_i = bedin.readline().rstrip()
# For each bed file, this is the total base pairs in that file
size_per_file = math.ceil( total_region_size / num )
# Go through every original region and split
current_size = 0
current_region = []
ith_split = 1
for region_i in original_regions:
chr_i = region_i[0]
start_i = region_i[1]
end_i = region_i[2]
# If the "now size" is still less than size/file requirement
if current_size + (end_i - start_i) <= size_per_file:
# Need to collect more to fulfill the size/file requirement, so append to current_region list
current_region.append( '{}\t{}\t{}\n'.format(chr_i, start_i, end_i) )
current_size = current_size + (end_i - start_i)
# If the "now size" exceeds the size/file requirement, need to start splitting:
elif current_size + (end_i - start_i) > size_per_file:
# Split a big region into a smaller regino, such that the size of "current_region" is equal to the size/file requirement:
breakpoint_i = size_per_file + start_i - current_size
# Write these regions out, , reset "current_region," then add 1 to ith_split afterward to keep track:
outfilesWritten.append( '{}{}{}.{}'.format(out_directory, os.sep, ith_split, out_basename) )
with open( '{}{}{}.{}'.format(out_directory, os.sep, ith_split, out_basename), 'w' ) as ith_out:
for line_i in current_region:
ith_out.write( line_i )
# Make sure it doesn't write a 0-bp region:
if breakpoint_i > start_i:
ith_out.write( '{}\t{}\t{}\n'.format( chr_i, start_i, breakpoint_i ) )
ith_split += 1
current_region = []
# The remaining, is the end position of the original region and the previous breakpoint:
remaining_length = end_i - breakpoint_i
remaining_region = (chr_i, breakpoint_i, end_i)
# If the remnant of the previous region is less than the size/file requirement, simply make it "current_region" and then move on:
if remaining_length <= size_per_file:
current_region.append( '{}\t{}\t{}\n'.format(chr_i, breakpoint_i, end_i) )
current_size = remaining_length
# If the renmant of the previuos region exceed the size/file requirement, it needs to be properly split until it's small enough:
elif remaining_length > size_per_file:
# Each sub-region, if large enough, will have its own file output:
while (end_i - breakpoint_i) > size_per_file:
end_j = breakpoint_i + size_per_file
outfilesWritten.append( '{}{}{}.{}'.format(out_directory, os.sep, ith_split, out_basename) )
with open( '{}{}{}.{}'.format(out_directory, os.sep, ith_split, out_basename), 'w' ) as ith_out:
if end_j > breakpoint_i:
ith_out.write( '{}\t{}\t{}\n'.format( chr_i, breakpoint_i, end_j ) )
ith_split += 1
breakpoint_i = end_j
# After every sub-region has its own bed file, the remnant is added to "current_region" to deal with the next line of the "original_regions"
current_region.append( '{}\t{}\t{}\n'.format(chr_i, breakpoint_i, end_i) )
current_size = end_i - breakpoint_i
# The final region to write out:
ithOutName = '{}{}{}.{}'.format(out_directory, os.sep, ith_split, out_basename)
outfilesWritten.append( ithOutName )
with open( ithOutName, 'w' ) as ith_out:
for line_i in current_region:
ith_out.write( line_i )
return outfilesWritten
def split_vcf_file(vcf_file, work_dir=os.curdir, num=1):
num_lines = 0
with open_textfile(vcf_file) as vcf:
line_i = vcf.readline()
header = []
while line_i.startswith('#'):
header.append(line_i)
line_i = vcf.readline()
while line_i:
num_lines += 1
line_i = vcf.readline()
lines_per_file = math.ceil( float(num_lines)/num )
with open_textfile(vcf_file) as vcf:
outnames = [ os.curdir + os.sep + str(i) + '_' + re.sub(r'.vcf(.gz)?', '', os.path.basename(vcf_file)) + '.vcf' for i in range(num) ]
outhandles = [open(i, 'w') for i in outnames]
[write_header(header, i) for i in outhandles]
line_i = vcf.readline()
while line_i.startswith('#'):
line_i = vcf.readline()
while line_i:
i = 0
n = 0
while line_i:
outhandles[n].write( line_i )
i += 1
if i == lines_per_file:
i = 0
n += 1
line_i = vcf.readline()
[i.close() for i in outhandles]
return outnames
if __name__ == '__main__':
infile, outfiles, num = run()
split(infile, outfiles, num) | 0.399577 | 0.218711 |
# ==============================================================================
# IMPORTS
# ==============================================================================
from setuptools import setup, find_packages
import codecs
import os
import re
# ==============================================================================
# GLOBALS
# ==============================================================================
HERE = os.path.abspath(os.path.dirname(__file__))
MAIN_FILE = os.path.join(HERE, 'viewerSync', '__init__.py')
# Get the long description from the relevant file
with codecs.open('README.rst', encoding='utf-8') as readme_file:
LONG_DESCRIPTION = readme_file.read()
# ==============================================================================
# PRIVATE FUNCTIONS
# ==============================================================================
def _find_metadata(filepath):
"""Reads all the metadata from a source file by opening manually.
Why open and read it and not import?
https://groups.google.com/d/topic/pypa-dev/0PkjVpcxTzQ/discussion
Args:
filepath : (str)
Filepath to the file containing the metadata.
Returns:
{str: str}
Dictionary with metadata keys and values.
Raises:
RuntimeError
Cannot proceed if version or module_name not found
"""
# Open in Latin-1 so that we avoid encoding errors.
# Use codecs.open for Python 2 compatibility
with codecs.open(filepath, 'r', 'latin1') as meta_file:
metadata_file = meta_file.read()
metadata = {}
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
author_match = re.search(r"^__author__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
author_email_match = re.search(r"^__author_email__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
copyright_match = re.search(r"^__copyright__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
credits_match = re.search(r"^__credits__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
license_match = re.search(r"^__license__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
maint_match = re.search(r"^__maintainer__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
maint_email_match = re.search(r"^__maintainer_email__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
module_name_match = re.search(r"^__module_name__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
short_desc_match = re.search(r"^__short_desc__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
status_match = re.search(r"^__status__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
url_match = re.search(r"^__url__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
if not version_match or not module_name_match:
raise RuntimeError("Unable to find version or module_name string.")
if author_match:
metadata['author'] = author_match.group(1)
if author_email_match:
metadata['author_email'] = author_email_match.group(1)
if copyright_match:
metadata['copyright'] = copyright_match.group(1)
if credits_match:
metadata['credits'] = credits_match.group(1)
if license_match:
metadata['license'] = license_match.group(1)
if maint_match:
metadata['maintainer'] = maint_match.group(1)
if maint_email_match:
metadata['maintainer_email'] = maint_email_match.group(1)
if module_name_match:
metadata['module_name'] = module_name_match.group(1)
if short_desc_match:
metadata['short_desc'] = short_desc_match.group(1)
if status_match:
metadata['status'] = status_match.group(1)
if version_match:
metadata['version'] = version_match.group(1)
if url_match:
metadata['url'] = url_match.group(1)
return metadata
# ==============================================================================
# MAIN
# ==============================================================================
metadata = _find_metadata(MAIN_FILE)
setup(
name=metadata['module_name'],
version=metadata['version'],
description=metadata.get('short_desc', ''),
long_description=LONG_DESCRIPTION,
# The project URL.
url=metadata.get('url', ''),
# Author & Maintainer details
author=metadata.get('author', ''),
author_email=metadata.get('author_email', ''),
maintainer=metadata.get('maintainer', ''),
maintainer_email=metadata.get('maintainer_email', ''),
# Choose your license
license=metadata.get('license', ''),
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 4 - Beta',
# Indicate who your project is intended for
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Developers',
'Topic :: Multimedia :: Graphics',
'Topic :: Multimedia :: Video',
'Topic :: Software Development :: Libraries :: Python Modules',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: Implementation :: CPython',
# OS
'Operating System :: OS Independent',
# Language
'Natural Language :: English',
],
# What does your project relate to?
keywords='film tv color vfx nuke',
# You can just specify the packages manually here if your project is
# simple. Or you can use find_packages.
packages=find_packages(exclude=['tests']),
# If there are data files included in your packages that need to be
# installed, specify them here. If using Python 2.6 or less, then these
# have to be included in MANIFEST.in as well.
package_data={},
include_package_data=True,
# Targeted OS
platforms='any',
) | setup.py | # ==============================================================================
# IMPORTS
# ==============================================================================
from setuptools import setup, find_packages
import codecs
import os
import re
# ==============================================================================
# GLOBALS
# ==============================================================================
HERE = os.path.abspath(os.path.dirname(__file__))
MAIN_FILE = os.path.join(HERE, 'viewerSync', '__init__.py')
# Get the long description from the relevant file
with codecs.open('README.rst', encoding='utf-8') as readme_file:
LONG_DESCRIPTION = readme_file.read()
# ==============================================================================
# PRIVATE FUNCTIONS
# ==============================================================================
def _find_metadata(filepath):
"""Reads all the metadata from a source file by opening manually.
Why open and read it and not import?
https://groups.google.com/d/topic/pypa-dev/0PkjVpcxTzQ/discussion
Args:
filepath : (str)
Filepath to the file containing the metadata.
Returns:
{str: str}
Dictionary with metadata keys and values.
Raises:
RuntimeError
Cannot proceed if version or module_name not found
"""
# Open in Latin-1 so that we avoid encoding errors.
# Use codecs.open for Python 2 compatibility
with codecs.open(filepath, 'r', 'latin1') as meta_file:
metadata_file = meta_file.read()
metadata = {}
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
author_match = re.search(r"^__author__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
author_email_match = re.search(r"^__author_email__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
copyright_match = re.search(r"^__copyright__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
credits_match = re.search(r"^__credits__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
license_match = re.search(r"^__license__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
maint_match = re.search(r"^__maintainer__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
maint_email_match = re.search(r"^__maintainer_email__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
module_name_match = re.search(r"^__module_name__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
short_desc_match = re.search(r"^__short_desc__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
status_match = re.search(r"^__status__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
url_match = re.search(r"^__url__ = ['\"]([^'\"]*)['\"]",
metadata_file, re.M)
if not version_match or not module_name_match:
raise RuntimeError("Unable to find version or module_name string.")
if author_match:
metadata['author'] = author_match.group(1)
if author_email_match:
metadata['author_email'] = author_email_match.group(1)
if copyright_match:
metadata['copyright'] = copyright_match.group(1)
if credits_match:
metadata['credits'] = credits_match.group(1)
if license_match:
metadata['license'] = license_match.group(1)
if maint_match:
metadata['maintainer'] = maint_match.group(1)
if maint_email_match:
metadata['maintainer_email'] = maint_email_match.group(1)
if module_name_match:
metadata['module_name'] = module_name_match.group(1)
if short_desc_match:
metadata['short_desc'] = short_desc_match.group(1)
if status_match:
metadata['status'] = status_match.group(1)
if version_match:
metadata['version'] = version_match.group(1)
if url_match:
metadata['url'] = url_match.group(1)
return metadata
# ==============================================================================
# MAIN
# ==============================================================================
metadata = _find_metadata(MAIN_FILE)
setup(
name=metadata['module_name'],
version=metadata['version'],
description=metadata.get('short_desc', ''),
long_description=LONG_DESCRIPTION,
# The project URL.
url=metadata.get('url', ''),
# Author & Maintainer details
author=metadata.get('author', ''),
author_email=metadata.get('author_email', ''),
maintainer=metadata.get('maintainer', ''),
maintainer_email=metadata.get('maintainer_email', ''),
# Choose your license
license=metadata.get('license', ''),
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 4 - Beta',
# Indicate who your project is intended for
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Developers',
'Topic :: Multimedia :: Graphics',
'Topic :: Multimedia :: Video',
'Topic :: Software Development :: Libraries :: Python Modules',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: Implementation :: CPython',
# OS
'Operating System :: OS Independent',
# Language
'Natural Language :: English',
],
# What does your project relate to?
keywords='film tv color vfx nuke',
# You can just specify the packages manually here if your project is
# simple. Or you can use find_packages.
packages=find_packages(exclude=['tests']),
# If there are data files included in your packages that need to be
# installed, specify them here. If using Python 2.6 or less, then these
# have to be included in MANIFEST.in as well.
package_data={},
include_package_data=True,
# Targeted OS
platforms='any',
) | 0.530966 | 0.224991 |
from django.urls import path, re_path
from django.views.generic import TemplateView
from django.views.decorators.cache import cache_page
from .views import *
# Seconds * Minutes
#cache_time = 60 * 2
cache_time = 0
slash = '/?'
rest_urls = {
'cohort': 'rest/cohort/',
'trait': 'rest/trait/',
'trait_category': 'rest/trait_category/',
'performance': 'rest/performance/',
'publication': 'rest/publication/',
'release': 'rest/release/',
'sample_set': 'rest/sample_set/',
'score': 'rest/score/',
'info': 'rest/info', # No slash (added later)
'api_versions': 'rest/api_versions', # No slash (added later)
'ancestry': 'rest/ancestry_categories', # No slash (added later)
'gwas': 'rest/gwas/get_score_ids/',
}
urlpatterns = [
# REST Documentation
path('rest/', TemplateView.as_view(template_name="rest_api/rest_doc.html")),
# Cohorts
re_path(r'^'+rest_urls['cohort']+'all'+slash, cache_page(cache_time)(RestListCohorts.as_view()), name="getAllCohorts"),
re_path(r'^'+rest_urls['cohort']+'(?P<cohort_symbol>[^/]+)'+slash, RestCohorts.as_view(), name="getCohorts"),
# EFO Traits
re_path(r'^'+rest_urls['trait']+'all'+slash, cache_page(cache_time)(RestListEFOTraits.as_view()), name="getAllTraits"),
re_path(r'^'+rest_urls['trait']+'search'+slash, RestEFOTraitSearch.as_view(), name="searchTraits"),
re_path(r'^'+rest_urls['trait']+'(?P<trait_id>[^/]+)'+slash, cache_page(cache_time)(RestEFOTrait.as_view()), name="getTrait"),
# Performance metrics
re_path(r'^'+rest_urls['performance']+'all'+slash, cache_page(cache_time)(RestListPerformances.as_view()), name="getAllPerformanceMetrics"),
re_path(r'^'+rest_urls['performance']+'search'+slash, RestPerformanceSearch.as_view(), name="searchPerformanceMetrics"),
re_path(r'^'+rest_urls['performance']+'(?P<ppm_id>[^/]+)'+slash, RestPerformance.as_view(), name="getPerformanceMetric"),
# Publications
re_path(r'^'+rest_urls['publication']+'all'+slash, cache_page(cache_time)(RestListPublications.as_view()), name="getAllPublications"),
re_path(r'^'+rest_urls['publication']+'search'+slash, cache_page(cache_time)(RestPublicationSearch.as_view()), name="searchPublications"),
re_path(r'^'+rest_urls['publication']+'(?P<pgp_id>[^/]+)'+slash, RestPublication.as_view(), name="getPublication"),
# Releases
re_path(r'^'+rest_urls['release']+'all'+slash, RestListReleases.as_view(), name="getAllReleases"),
re_path(r'^'+rest_urls['release']+'current'+slash, RestCurrentRelease.as_view(), name="getCurrentRelease"),
re_path(r'^'+rest_urls['release']+'(?P<release_date>[^/]+)'+slash, RestRelease.as_view(), name="getRelease"),
# Sample Set
re_path(r'^'+rest_urls['sample_set']+'all'+slash, cache_page(cache_time)(RestListSampleSets.as_view()), name="getAllSampleSets"),
re_path(r'^'+rest_urls['sample_set']+'search'+slash, RestSampleSetSearch.as_view(), name="searchSampleSet"),
re_path(r'^'+rest_urls['sample_set']+'(?P<pss_id>[^/]+)'+slash, RestSampleSet.as_view(), name="getSampleSet"),
# Scores
re_path(r'^'+rest_urls['score']+'all'+slash, cache_page(cache_time)(RestListScores.as_view()), name="getAllScores"),
re_path(r'^'+rest_urls['score']+'search'+slash, RestScoreSearch.as_view(), name="searchScores"),
re_path(r'^'+rest_urls['score']+'(?P<pgs_id>[^/]+)'+slash, RestScore.as_view(), name="getScore"),
# Extra endpoints
re_path(r'^'+rest_urls['gwas']+'(?P<gcst_id>[^/]+)'+slash, cache_page(cache_time)(RestGCST.as_view()), name="pgs_score_ids_from_gwas_gcst_id"),
re_path(r'^'+rest_urls['info']+slash, cache_page(cache_time)(RestInfo.as_view()), name="getInfo"),
re_path(r'^'+rest_urls['api_versions']+slash, cache_page(cache_time)(RestApiVersions.as_view()), name="getApiVersions"),
re_path(r'^'+rest_urls['ancestry']+slash, cache_page(cache_time)(RestAncestryCategories.as_view()), name="getAncestryCategories"),
# Trait Category
re_path(r'^'+rest_urls['trait_category']+'all'+slash, cache_page(cache_time)(RestListTraitCategories.as_view()), name="getAllTraitCategories")
] | rest_api/urls.py | from django.urls import path, re_path
from django.views.generic import TemplateView
from django.views.decorators.cache import cache_page
from .views import *
# Seconds * Minutes
#cache_time = 60 * 2
cache_time = 0
slash = '/?'
rest_urls = {
'cohort': 'rest/cohort/',
'trait': 'rest/trait/',
'trait_category': 'rest/trait_category/',
'performance': 'rest/performance/',
'publication': 'rest/publication/',
'release': 'rest/release/',
'sample_set': 'rest/sample_set/',
'score': 'rest/score/',
'info': 'rest/info', # No slash (added later)
'api_versions': 'rest/api_versions', # No slash (added later)
'ancestry': 'rest/ancestry_categories', # No slash (added later)
'gwas': 'rest/gwas/get_score_ids/',
}
urlpatterns = [
# REST Documentation
path('rest/', TemplateView.as_view(template_name="rest_api/rest_doc.html")),
# Cohorts
re_path(r'^'+rest_urls['cohort']+'all'+slash, cache_page(cache_time)(RestListCohorts.as_view()), name="getAllCohorts"),
re_path(r'^'+rest_urls['cohort']+'(?P<cohort_symbol>[^/]+)'+slash, RestCohorts.as_view(), name="getCohorts"),
# EFO Traits
re_path(r'^'+rest_urls['trait']+'all'+slash, cache_page(cache_time)(RestListEFOTraits.as_view()), name="getAllTraits"),
re_path(r'^'+rest_urls['trait']+'search'+slash, RestEFOTraitSearch.as_view(), name="searchTraits"),
re_path(r'^'+rest_urls['trait']+'(?P<trait_id>[^/]+)'+slash, cache_page(cache_time)(RestEFOTrait.as_view()), name="getTrait"),
# Performance metrics
re_path(r'^'+rest_urls['performance']+'all'+slash, cache_page(cache_time)(RestListPerformances.as_view()), name="getAllPerformanceMetrics"),
re_path(r'^'+rest_urls['performance']+'search'+slash, RestPerformanceSearch.as_view(), name="searchPerformanceMetrics"),
re_path(r'^'+rest_urls['performance']+'(?P<ppm_id>[^/]+)'+slash, RestPerformance.as_view(), name="getPerformanceMetric"),
# Publications
re_path(r'^'+rest_urls['publication']+'all'+slash, cache_page(cache_time)(RestListPublications.as_view()), name="getAllPublications"),
re_path(r'^'+rest_urls['publication']+'search'+slash, cache_page(cache_time)(RestPublicationSearch.as_view()), name="searchPublications"),
re_path(r'^'+rest_urls['publication']+'(?P<pgp_id>[^/]+)'+slash, RestPublication.as_view(), name="getPublication"),
# Releases
re_path(r'^'+rest_urls['release']+'all'+slash, RestListReleases.as_view(), name="getAllReleases"),
re_path(r'^'+rest_urls['release']+'current'+slash, RestCurrentRelease.as_view(), name="getCurrentRelease"),
re_path(r'^'+rest_urls['release']+'(?P<release_date>[^/]+)'+slash, RestRelease.as_view(), name="getRelease"),
# Sample Set
re_path(r'^'+rest_urls['sample_set']+'all'+slash, cache_page(cache_time)(RestListSampleSets.as_view()), name="getAllSampleSets"),
re_path(r'^'+rest_urls['sample_set']+'search'+slash, RestSampleSetSearch.as_view(), name="searchSampleSet"),
re_path(r'^'+rest_urls['sample_set']+'(?P<pss_id>[^/]+)'+slash, RestSampleSet.as_view(), name="getSampleSet"),
# Scores
re_path(r'^'+rest_urls['score']+'all'+slash, cache_page(cache_time)(RestListScores.as_view()), name="getAllScores"),
re_path(r'^'+rest_urls['score']+'search'+slash, RestScoreSearch.as_view(), name="searchScores"),
re_path(r'^'+rest_urls['score']+'(?P<pgs_id>[^/]+)'+slash, RestScore.as_view(), name="getScore"),
# Extra endpoints
re_path(r'^'+rest_urls['gwas']+'(?P<gcst_id>[^/]+)'+slash, cache_page(cache_time)(RestGCST.as_view()), name="pgs_score_ids_from_gwas_gcst_id"),
re_path(r'^'+rest_urls['info']+slash, cache_page(cache_time)(RestInfo.as_view()), name="getInfo"),
re_path(r'^'+rest_urls['api_versions']+slash, cache_page(cache_time)(RestApiVersions.as_view()), name="getApiVersions"),
re_path(r'^'+rest_urls['ancestry']+slash, cache_page(cache_time)(RestAncestryCategories.as_view()), name="getAncestryCategories"),
# Trait Category
re_path(r'^'+rest_urls['trait_category']+'all'+slash, cache_page(cache_time)(RestListTraitCategories.as_view()), name="getAllTraitCategories")
] | 0.380068 | 0.069038 |
__author__ = '<EMAIL> (<NAME>)'
import os
import re
import sets
import sys
# We assume that this file is in the scripts/ directory in the Google
# Mock root directory.
DEFAULT_GMOCK_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
# We need to call into gtest/scripts/fuse_gtest_files.py.
sys.path.append(os.path.join(DEFAULT_GMOCK_ROOT_DIR, 'gtest/scripts'))
import fuse_gtest_files
gtest = fuse_gtest_files
# Regex for matching '#include "gmock/..."'.
INCLUDE_GMOCK_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(gmock/.+)"')
# Where to find the source seed files.
GMOCK_H_SEED = 'include/gmock/gmock.h'
GMOCK_ALL_CC_SEED = 'src/gmock-all.cc'
# Where to put the generated files.
GTEST_H_OUTPUT = 'gtest/gtest.h'
GMOCK_H_OUTPUT = 'gmock/gmock.h'
GMOCK_GTEST_ALL_CC_OUTPUT = 'gmock-gtest-all.cc'
def GetGTestRootDir(gmock_root):
"""Returns the root directory of Google Test."""
return os.path.join(gmock_root, 'gtest')
def ValidateGMockRootDir(gmock_root):
"""Makes sure gmock_root points to a valid gmock root directory.
The function aborts the program on failure.
"""
gtest.ValidateGTestRootDir(GetGTestRootDir(gmock_root))
gtest.VerifyFileExists(gmock_root, GMOCK_H_SEED)
gtest.VerifyFileExists(gmock_root, GMOCK_ALL_CC_SEED)
def ValidateOutputDir(output_dir):
"""Makes sure output_dir points to a valid output directory.
The function aborts the program on failure.
"""
gtest.VerifyOutputFile(output_dir, gtest.GTEST_H_OUTPUT)
gtest.VerifyOutputFile(output_dir, GMOCK_H_OUTPUT)
gtest.VerifyOutputFile(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT)
def FuseGMockH(gmock_root, output_dir):
"""Scans folder gmock_root to generate gmock/gmock.h in output_dir."""
output_file = file(os.path.join(output_dir, GMOCK_H_OUTPUT), 'w')
processed_files = sets.Set() # Holds all gmock headers we've processed.
def ProcessFile(gmock_header_path):
"""Processes the given gmock header file."""
# We don't process the same header twice.
if gmock_header_path in processed_files:
return
processed_files.add(gmock_header_path)
# Reads each line in the given gmock header.
for line in file(os.path.join(gmock_root, gmock_header_path), 'r'):
m = INCLUDE_GMOCK_FILE_REGEX.match(line)
if m:
# It's '#include "gmock/..."' - let's process it recursively.
ProcessFile('include/' + m.group(1))
else:
m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
if m:
# It's '#include "gtest/foo.h"'. We translate it to
# "gtest/gtest.h", regardless of what foo is, since all
# gtest headers are fused into gtest/gtest.h.
# There is no need to #include gtest.h twice.
if not gtest.GTEST_H_SEED in processed_files:
processed_files.add(gtest.GTEST_H_SEED)
output_file.write('#include "%s"\n' % (gtest.GTEST_H_OUTPUT,))
else:
# Otherwise we copy the line unchanged to the output file.
output_file.write(line)
ProcessFile(GMOCK_H_SEED)
output_file.close()
def FuseGMockAllCcToFile(gmock_root, output_file):
"""Scans folder gmock_root to fuse gmock-all.cc into output_file."""
processed_files = sets.Set()
def ProcessFile(gmock_source_file):
"""Processes the given gmock source file."""
# We don't process the same #included file twice.
if gmock_source_file in processed_files:
return
processed_files.add(gmock_source_file)
# Reads each line in the given gmock source file.
for line in file(os.path.join(gmock_root, gmock_source_file), 'r'):
m = INCLUDE_GMOCK_FILE_REGEX.match(line)
if m:
# It's '#include "gmock/foo.h"'. We treat it as '#include
# "gmock/gmock.h"', as all other gmock headers are being fused
# into gmock.h and cannot be #included directly.
# There is no need to #include "gmock/gmock.h" more than once.
if not GMOCK_H_SEED in processed_files:
processed_files.add(GMOCK_H_SEED)
output_file.write('#include "%s"\n' % (GMOCK_H_OUTPUT,))
else:
m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
if m:
# It's '#include "gtest/..."'.
# There is no need to #include gtest.h as it has been
# #included by gtest-all.cc.
pass
else:
m = gtest.INCLUDE_SRC_FILE_REGEX.match(line)
if m:
# It's '#include "src/foo"' - let's process it recursively.
ProcessFile(m.group(1))
else:
# Otherwise we copy the line unchanged to the output file.
output_file.write(line)
ProcessFile(GMOCK_ALL_CC_SEED)
def FuseGMockGTestAllCc(gmock_root, output_dir):
"""Scans folder gmock_root to generate gmock-gtest-all.cc in output_dir."""
output_file = file(os.path.join(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT), 'w')
# First, fuse gtest-all.cc into gmock-gtest-all.cc.
gtest.FuseGTestAllCcToFile(GetGTestRootDir(gmock_root), output_file)
# Next, append fused gmock-all.cc to gmock-gtest-all.cc.
FuseGMockAllCcToFile(gmock_root, output_file)
output_file.close()
def FuseGMock(gmock_root, output_dir):
"""Fuses gtest.h, gmock.h, and gmock-gtest-all.h."""
ValidateGMockRootDir(gmock_root)
ValidateOutputDir(output_dir)
gtest.FuseGTestH(GetGTestRootDir(gmock_root), output_dir)
FuseGMockH(gmock_root, output_dir)
FuseGMockGTestAllCc(gmock_root, output_dir)
def main():
argc = len(sys.argv)
if argc == 2:
# fuse_gmock_files.py OUTPUT_DIR
FuseGMock(DEFAULT_GMOCK_ROOT_DIR, sys.argv[1])
elif argc == 3:
# fuse_gmock_files.py GMOCK_ROOT_DIR OUTPUT_DIR
FuseGMock(sys.argv[1], sys.argv[2])
else:
print __doc__
sys.exit(1)
if __name__ == '__main__':
main() | scripts/fuse_gmock_files.py | __author__ = '<EMAIL> (<NAME>)'
import os
import re
import sets
import sys
# We assume that this file is in the scripts/ directory in the Google
# Mock root directory.
DEFAULT_GMOCK_ROOT_DIR = os.path.join(os.path.dirname(__file__), '..')
# We need to call into gtest/scripts/fuse_gtest_files.py.
sys.path.append(os.path.join(DEFAULT_GMOCK_ROOT_DIR, 'gtest/scripts'))
import fuse_gtest_files
gtest = fuse_gtest_files
# Regex for matching '#include "gmock/..."'.
INCLUDE_GMOCK_FILE_REGEX = re.compile(r'^\s*#\s*include\s*"(gmock/.+)"')
# Where to find the source seed files.
GMOCK_H_SEED = 'include/gmock/gmock.h'
GMOCK_ALL_CC_SEED = 'src/gmock-all.cc'
# Where to put the generated files.
GTEST_H_OUTPUT = 'gtest/gtest.h'
GMOCK_H_OUTPUT = 'gmock/gmock.h'
GMOCK_GTEST_ALL_CC_OUTPUT = 'gmock-gtest-all.cc'
def GetGTestRootDir(gmock_root):
"""Returns the root directory of Google Test."""
return os.path.join(gmock_root, 'gtest')
def ValidateGMockRootDir(gmock_root):
"""Makes sure gmock_root points to a valid gmock root directory.
The function aborts the program on failure.
"""
gtest.ValidateGTestRootDir(GetGTestRootDir(gmock_root))
gtest.VerifyFileExists(gmock_root, GMOCK_H_SEED)
gtest.VerifyFileExists(gmock_root, GMOCK_ALL_CC_SEED)
def ValidateOutputDir(output_dir):
"""Makes sure output_dir points to a valid output directory.
The function aborts the program on failure.
"""
gtest.VerifyOutputFile(output_dir, gtest.GTEST_H_OUTPUT)
gtest.VerifyOutputFile(output_dir, GMOCK_H_OUTPUT)
gtest.VerifyOutputFile(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT)
def FuseGMockH(gmock_root, output_dir):
"""Scans folder gmock_root to generate gmock/gmock.h in output_dir."""
output_file = file(os.path.join(output_dir, GMOCK_H_OUTPUT), 'w')
processed_files = sets.Set() # Holds all gmock headers we've processed.
def ProcessFile(gmock_header_path):
"""Processes the given gmock header file."""
# We don't process the same header twice.
if gmock_header_path in processed_files:
return
processed_files.add(gmock_header_path)
# Reads each line in the given gmock header.
for line in file(os.path.join(gmock_root, gmock_header_path), 'r'):
m = INCLUDE_GMOCK_FILE_REGEX.match(line)
if m:
# It's '#include "gmock/..."' - let's process it recursively.
ProcessFile('include/' + m.group(1))
else:
m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
if m:
# It's '#include "gtest/foo.h"'. We translate it to
# "gtest/gtest.h", regardless of what foo is, since all
# gtest headers are fused into gtest/gtest.h.
# There is no need to #include gtest.h twice.
if not gtest.GTEST_H_SEED in processed_files:
processed_files.add(gtest.GTEST_H_SEED)
output_file.write('#include "%s"\n' % (gtest.GTEST_H_OUTPUT,))
else:
# Otherwise we copy the line unchanged to the output file.
output_file.write(line)
ProcessFile(GMOCK_H_SEED)
output_file.close()
def FuseGMockAllCcToFile(gmock_root, output_file):
"""Scans folder gmock_root to fuse gmock-all.cc into output_file."""
processed_files = sets.Set()
def ProcessFile(gmock_source_file):
"""Processes the given gmock source file."""
# We don't process the same #included file twice.
if gmock_source_file in processed_files:
return
processed_files.add(gmock_source_file)
# Reads each line in the given gmock source file.
for line in file(os.path.join(gmock_root, gmock_source_file), 'r'):
m = INCLUDE_GMOCK_FILE_REGEX.match(line)
if m:
# It's '#include "gmock/foo.h"'. We treat it as '#include
# "gmock/gmock.h"', as all other gmock headers are being fused
# into gmock.h and cannot be #included directly.
# There is no need to #include "gmock/gmock.h" more than once.
if not GMOCK_H_SEED in processed_files:
processed_files.add(GMOCK_H_SEED)
output_file.write('#include "%s"\n' % (GMOCK_H_OUTPUT,))
else:
m = gtest.INCLUDE_GTEST_FILE_REGEX.match(line)
if m:
# It's '#include "gtest/..."'.
# There is no need to #include gtest.h as it has been
# #included by gtest-all.cc.
pass
else:
m = gtest.INCLUDE_SRC_FILE_REGEX.match(line)
if m:
# It's '#include "src/foo"' - let's process it recursively.
ProcessFile(m.group(1))
else:
# Otherwise we copy the line unchanged to the output file.
output_file.write(line)
ProcessFile(GMOCK_ALL_CC_SEED)
def FuseGMockGTestAllCc(gmock_root, output_dir):
"""Scans folder gmock_root to generate gmock-gtest-all.cc in output_dir."""
output_file = file(os.path.join(output_dir, GMOCK_GTEST_ALL_CC_OUTPUT), 'w')
# First, fuse gtest-all.cc into gmock-gtest-all.cc.
gtest.FuseGTestAllCcToFile(GetGTestRootDir(gmock_root), output_file)
# Next, append fused gmock-all.cc to gmock-gtest-all.cc.
FuseGMockAllCcToFile(gmock_root, output_file)
output_file.close()
def FuseGMock(gmock_root, output_dir):
"""Fuses gtest.h, gmock.h, and gmock-gtest-all.h."""
ValidateGMockRootDir(gmock_root)
ValidateOutputDir(output_dir)
gtest.FuseGTestH(GetGTestRootDir(gmock_root), output_dir)
FuseGMockH(gmock_root, output_dir)
FuseGMockGTestAllCc(gmock_root, output_dir)
def main():
argc = len(sys.argv)
if argc == 2:
# fuse_gmock_files.py OUTPUT_DIR
FuseGMock(DEFAULT_GMOCK_ROOT_DIR, sys.argv[1])
elif argc == 3:
# fuse_gmock_files.py GMOCK_ROOT_DIR OUTPUT_DIR
FuseGMock(sys.argv[1], sys.argv[2])
else:
print __doc__
sys.exit(1)
if __name__ == '__main__':
main() | 0.45181 | 0.215743 |
import sys
import logging
import random
from pathlib import Path
import pandas as pd
from sklearn.model_selection import train_test_split
from tqdm import tqdm
def get_dataset(set_name, binary=False, **kwargs):
if set_name not in ['taxonomist', 'hpas', 'test', 'natops']:
raise ValueError("Wrong set_name")
if binary:
if set_name in ['taxonomist', 'test', 'natops']:
kwargs['make_binary'] = True
elif set_name == 'hpas':
kwargs['classes'] = ['none', 'dcopy']
rootdir = Path(kwargs.get('rootdir', './data'))
if set_name == 'taxonomist':
kwargs['window'] = 45
kwargs['skip'] = 45
if set_name == 'test':
set_name = 'taxonomist'
kwargs['window'] = 60
kwargs['skip'] = 60
kwargs['test'] = True
if set_name == 'natops':
kwargs['windowize'] = False
return load_hpc_data(rootdir / set_name, **kwargs)
def windowize(timeseries, labels, window=45, trim=60, skip=15, test=False):
result_labels = []
result_timeseries = []
node_ids = labels.index.get_level_values('node_id').unique()
if test:
node_ids = random.sample(list(node_ids), 100)
for node_id in tqdm(node_ids):
subset = timeseries.loc[[node_id], :, :].dropna()
temp = []
temp_labels = []
for i in range(len(subset.iloc[trim:-trim])):
if i < window:
continue
elif i % skip != 0:
continue
data = subset.iloc[i - window: i]
data.index = data.index.set_levels(
data.index.levels[0] + '_{}'.format(i), level=0)
temp.append(data)
label = labels.loc[[node_id], :, :]
label.index = label.index.set_levels(
label.index.levels[0] + '_{}'.format(i), level=0)
temp_labels.append(label)
result_timeseries.append(pd.concat(temp, axis=0))
result_labels.append(pd.concat(temp_labels, axis=0))
return (pd.concat(result_timeseries, axis=0),
pd.concat(result_labels, axis=0))
def drop_columns(timeseries):
return timeseries.drop(
[x for x in timeseries.columns
if x.endswith('HASW') or 'per_core' in x], axis=1)
def select_classes(timeseries, labels, classes):
if classes is None:
return timeseries, labels
labels = labels[labels['label'].isin(classes)]
timeseries = timeseries.loc[labels.index.get_level_values('node_id'), :, :]
return timeseries, labels
def process_data(timeseries, labels, classes=None, **kwargs):
timeseries = drop_columns(timeseries)
timeseries, labels = select_classes(timeseries, labels, classes=classes)
timeseries = timeseries.dropna(axis=0)
assert(not timeseries.isnull().any().any())
if kwargs.get('windowize', True):
return windowize(timeseries, labels, **kwargs)
return timeseries, labels
def load_hpc_data(data_folder, make_binary=False, for_autoencoder=False, **kwargs):
if for_autoencoder:
# Only get data from a single hardware node
if 'none' not in kwargs.get('classes'):
raise ValueError("Autoencoder has to train with healthy class")
nodeid_df = pd.read_csv(data_folder / 'nids.csv')
labels = pd.concat([pd.read_hdf(data_folder / 'train_labels.hdf'),
pd.read_hdf(data_folder / 'test_labels.hdf')])
labels = labels[labels['label'].isin(kwargs.get('classes'))]
best_nid = 0
best_count = 0
for nid in nodeid_df['nid'].unique():
node_ids = nodeid_df[nodeid_df['nid'] == nid]['node_id']
if len(labels.loc[node_ids, :, :]['label'].unique()) == 1:
continue
min_count = labels.loc[node_ids, :, :]['label'].value_counts().min()
if min_count > best_count:
best_nid = nid
best_count = min_count
node_ids = nodeid_df[nodeid_df['nid'] == best_nid]['node_id']
labels = labels.loc[node_ids, :, :]
logging.info("Returning runs from nid000%d, counts: %s",
best_nid, labels['label'].value_counts().to_dict())
timeseries = pd.concat([pd.read_hdf(data_folder / 'train.hdf'),
pd.read_hdf(data_folder / 'test.hdf')])
train_nodeids, test_nodeids = train_test_split(
labels.index.get_level_values('node_id').unique(), test_size=0.2, random_state=0)
test_timeseries = timeseries.loc[test_nodeids, :, :]
test_labels = labels.loc[test_nodeids, :, :]
timeseries = timeseries.loc[train_nodeids, :, :]
labels = labels.loc[train_nodeids, :, :]
else:
timeseries = pd.read_hdf(data_folder / 'train.hdf')
labels = pd.read_hdf(data_folder / 'train_labels.hdf')
labels['label'] = labels['label'].astype(str)
if make_binary:
label_to_keep = labels.mode()['label'][0]
labels[labels['label'] != label_to_keep] = 'other'
test_timeseries = pd.read_hdf(data_folder / 'test.hdf')
test_labels = pd.read_hdf(data_folder / 'test_labels.hdf')
test_labels['label'] = test_labels['label'].astype(str)
if make_binary:
test_labels[test_labels['label'] != label_to_keep] = 'other'
timeseries, labels = process_data(timeseries, labels, **kwargs)
assert(not timeseries.isnull().any().any())
test_timeseries, test_labels = process_data(
test_timeseries, test_labels, **kwargs)
assert(not test_timeseries.isnull().any().any())
# Divide test data
if kwargs.get('test', False):
test_node_ids = [
test_labels[test_labels['label'] == label].index.get_level_values('node_id')[0]
for label in test_labels['label'].unique()]
test_labels = test_labels.loc[test_node_ids, :]
test_timeseries = test_timeseries.loc[test_node_ids, :]
return timeseries, labels, test_timeseries, test_labels | data_loading.py | import sys
import logging
import random
from pathlib import Path
import pandas as pd
from sklearn.model_selection import train_test_split
from tqdm import tqdm
def get_dataset(set_name, binary=False, **kwargs):
if set_name not in ['taxonomist', 'hpas', 'test', 'natops']:
raise ValueError("Wrong set_name")
if binary:
if set_name in ['taxonomist', 'test', 'natops']:
kwargs['make_binary'] = True
elif set_name == 'hpas':
kwargs['classes'] = ['none', 'dcopy']
rootdir = Path(kwargs.get('rootdir', './data'))
if set_name == 'taxonomist':
kwargs['window'] = 45
kwargs['skip'] = 45
if set_name == 'test':
set_name = 'taxonomist'
kwargs['window'] = 60
kwargs['skip'] = 60
kwargs['test'] = True
if set_name == 'natops':
kwargs['windowize'] = False
return load_hpc_data(rootdir / set_name, **kwargs)
def windowize(timeseries, labels, window=45, trim=60, skip=15, test=False):
result_labels = []
result_timeseries = []
node_ids = labels.index.get_level_values('node_id').unique()
if test:
node_ids = random.sample(list(node_ids), 100)
for node_id in tqdm(node_ids):
subset = timeseries.loc[[node_id], :, :].dropna()
temp = []
temp_labels = []
for i in range(len(subset.iloc[trim:-trim])):
if i < window:
continue
elif i % skip != 0:
continue
data = subset.iloc[i - window: i]
data.index = data.index.set_levels(
data.index.levels[0] + '_{}'.format(i), level=0)
temp.append(data)
label = labels.loc[[node_id], :, :]
label.index = label.index.set_levels(
label.index.levels[0] + '_{}'.format(i), level=0)
temp_labels.append(label)
result_timeseries.append(pd.concat(temp, axis=0))
result_labels.append(pd.concat(temp_labels, axis=0))
return (pd.concat(result_timeseries, axis=0),
pd.concat(result_labels, axis=0))
def drop_columns(timeseries):
return timeseries.drop(
[x for x in timeseries.columns
if x.endswith('HASW') or 'per_core' in x], axis=1)
def select_classes(timeseries, labels, classes):
if classes is None:
return timeseries, labels
labels = labels[labels['label'].isin(classes)]
timeseries = timeseries.loc[labels.index.get_level_values('node_id'), :, :]
return timeseries, labels
def process_data(timeseries, labels, classes=None, **kwargs):
timeseries = drop_columns(timeseries)
timeseries, labels = select_classes(timeseries, labels, classes=classes)
timeseries = timeseries.dropna(axis=0)
assert(not timeseries.isnull().any().any())
if kwargs.get('windowize', True):
return windowize(timeseries, labels, **kwargs)
return timeseries, labels
def load_hpc_data(data_folder, make_binary=False, for_autoencoder=False, **kwargs):
if for_autoencoder:
# Only get data from a single hardware node
if 'none' not in kwargs.get('classes'):
raise ValueError("Autoencoder has to train with healthy class")
nodeid_df = pd.read_csv(data_folder / 'nids.csv')
labels = pd.concat([pd.read_hdf(data_folder / 'train_labels.hdf'),
pd.read_hdf(data_folder / 'test_labels.hdf')])
labels = labels[labels['label'].isin(kwargs.get('classes'))]
best_nid = 0
best_count = 0
for nid in nodeid_df['nid'].unique():
node_ids = nodeid_df[nodeid_df['nid'] == nid]['node_id']
if len(labels.loc[node_ids, :, :]['label'].unique()) == 1:
continue
min_count = labels.loc[node_ids, :, :]['label'].value_counts().min()
if min_count > best_count:
best_nid = nid
best_count = min_count
node_ids = nodeid_df[nodeid_df['nid'] == best_nid]['node_id']
labels = labels.loc[node_ids, :, :]
logging.info("Returning runs from nid000%d, counts: %s",
best_nid, labels['label'].value_counts().to_dict())
timeseries = pd.concat([pd.read_hdf(data_folder / 'train.hdf'),
pd.read_hdf(data_folder / 'test.hdf')])
train_nodeids, test_nodeids = train_test_split(
labels.index.get_level_values('node_id').unique(), test_size=0.2, random_state=0)
test_timeseries = timeseries.loc[test_nodeids, :, :]
test_labels = labels.loc[test_nodeids, :, :]
timeseries = timeseries.loc[train_nodeids, :, :]
labels = labels.loc[train_nodeids, :, :]
else:
timeseries = pd.read_hdf(data_folder / 'train.hdf')
labels = pd.read_hdf(data_folder / 'train_labels.hdf')
labels['label'] = labels['label'].astype(str)
if make_binary:
label_to_keep = labels.mode()['label'][0]
labels[labels['label'] != label_to_keep] = 'other'
test_timeseries = pd.read_hdf(data_folder / 'test.hdf')
test_labels = pd.read_hdf(data_folder / 'test_labels.hdf')
test_labels['label'] = test_labels['label'].astype(str)
if make_binary:
test_labels[test_labels['label'] != label_to_keep] = 'other'
timeseries, labels = process_data(timeseries, labels, **kwargs)
assert(not timeseries.isnull().any().any())
test_timeseries, test_labels = process_data(
test_timeseries, test_labels, **kwargs)
assert(not test_timeseries.isnull().any().any())
# Divide test data
if kwargs.get('test', False):
test_node_ids = [
test_labels[test_labels['label'] == label].index.get_level_values('node_id')[0]
for label in test_labels['label'].unique()]
test_labels = test_labels.loc[test_node_ids, :]
test_timeseries = test_timeseries.loc[test_node_ids, :]
return timeseries, labels, test_timeseries, test_labels | 0.33546 | 0.307631 |
import jwt
# The Users model
from models import User
# Importing the session
from db import session
# Datetime functionality
import datetime
# Reading the configuration file
import yaml
conf = yaml.safe_load(open("config.yml"))
# JWT constants
_SECRET = conf["jwt"]["secret"]
_ALGORITHM = conf["jwt"]["algorithm"]
_EXPIRATION_TIME = conf["jwt"]["expiration_time"] # Minutes until expiration
# Creating the JWT token
def create_token(user_id: int) -> str:
"""
Method to create a JWT token for a user using internal user_id
Parameters
----------
user_id (int): The user_id of the user to create the token for
Returns
-------
str: The JWT token
"""
# Creating the claims dictionary
claims = {
# Expiration date of the token
"exp": datetime.datetime.now() + datetime.timedelta(minutes=_EXPIRATION_TIME),
# Issue time of the token
"iat": datetime.datetime.now(),
# Subject of the token
"sub": user_id
}
# Creating the token
return jwt.encode(claims, _SECRET, algorithm=_ALGORITHM)
# Authenticating the JWT token
def authenticate_token(jwt_token: str) -> bool:
"""
Function that decodes the token and authenticates it.
Parameters
----------
jwt_token (str): The JWT token to authenticate
Returns
-------
bool: True if the token is valid, False otherwise
"""
try:
# Decoding the token
claims = jwt.decode(jwt_token, _SECRET, algorithms=[_ALGORITHM])
# Extracting the user_id from the token
user_id = claims["sub"]
# Extracting the expiration date from the token
expiration_date = claims["exp"]
# Checking if the token is expired
if datetime.datetime.fromtimestamp(expiration_date) < datetime.datetime.utcnow():
return False
# Checking if the user exists in the database
user = session.query(User).filter(User.id == user_id).first()
if user:
return True
else:
return False
except:
# If the token is invalid, return False
return False | api-book/chapter-6-production-tools/jwt_token_example/jwt_tokens.py | import jwt
# The Users model
from models import User
# Importing the session
from db import session
# Datetime functionality
import datetime
# Reading the configuration file
import yaml
conf = yaml.safe_load(open("config.yml"))
# JWT constants
_SECRET = conf["jwt"]["secret"]
_ALGORITHM = conf["jwt"]["algorithm"]
_EXPIRATION_TIME = conf["jwt"]["expiration_time"] # Minutes until expiration
# Creating the JWT token
def create_token(user_id: int) -> str:
"""
Method to create a JWT token for a user using internal user_id
Parameters
----------
user_id (int): The user_id of the user to create the token for
Returns
-------
str: The JWT token
"""
# Creating the claims dictionary
claims = {
# Expiration date of the token
"exp": datetime.datetime.now() + datetime.timedelta(minutes=_EXPIRATION_TIME),
# Issue time of the token
"iat": datetime.datetime.now(),
# Subject of the token
"sub": user_id
}
# Creating the token
return jwt.encode(claims, _SECRET, algorithm=_ALGORITHM)
# Authenticating the JWT token
def authenticate_token(jwt_token: str) -> bool:
"""
Function that decodes the token and authenticates it.
Parameters
----------
jwt_token (str): The JWT token to authenticate
Returns
-------
bool: True if the token is valid, False otherwise
"""
try:
# Decoding the token
claims = jwt.decode(jwt_token, _SECRET, algorithms=[_ALGORITHM])
# Extracting the user_id from the token
user_id = claims["sub"]
# Extracting the expiration date from the token
expiration_date = claims["exp"]
# Checking if the token is expired
if datetime.datetime.fromtimestamp(expiration_date) < datetime.datetime.utcnow():
return False
# Checking if the user exists in the database
user = session.query(User).filter(User.id == user_id).first()
if user:
return True
else:
return False
except:
# If the token is invalid, return False
return False | 0.722037 | 0.182153 |
import torch
import torch.nn as nn
from torch import sigmoid
from torch.nn.init import xavier_uniform_, zeros_, kaiming_uniform_
import torchvision as tv
def conv(in_planes, out_planes, kernel_size=3):
return nn.Sequential(
nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, padding=(kernel_size-1)//2, stride=2),
nn.ReLU(inplace=True)
)
def upconv(in_planes, out_planes):
return nn.Sequential(
nn.ConvTranspose2d(in_planes, out_planes, kernel_size=4, stride=2, padding=1),
nn.ReLU(inplace=True)
)
class PoseSep(nn.Module):
def __init__(self, nb_ref_imgs=2, output_exp=False, encoder='conv'):
super(PoseSep, self).__init__()
assert(output_exp == False)
self.nb_ref_imgs = nb_ref_imgs
self.output_exp = output_exp
conv_planes = [16, 32, 64, 128, 256, 256, 256]
if encoder == 'conv':
self.encoder = nn.Sequential(
conv(6, conv_planes[0], kernel_size=7),
conv(conv_planes[0], conv_planes[1], kernel_size=5),
conv(conv_planes[1], conv_planes[2]),
conv(conv_planes[2], conv_planes[3]),
conv(conv_planes[3], conv_planes[4]),
conv(conv_planes[4], conv_planes[5]),
conv(conv_planes[5], conv_planes[6])
)
self.pose_pred = nn.Conv2d(conv_planes[6], 6, kernel_size=1, padding=0)
elif encoder == 'resnet':
resnet = tv.models.resnet18(pretrained=False)
self.encoder = nn.Sequential(*(list(resnet.children())[:-2]))
self.encoder[0] = nn.Conv2d(6, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
self.pose_pred = nn.Conv2d(512, 6, kernel_size=1, padding=0)
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):
# xavier_uniform_(m.weight.data)
kaiming_uniform_(m.weight.data)
if m.bias is not None:
zeros_(m.bias)
def forward(self, target_image, ref_imgs):
assert(len(ref_imgs) == self.nb_ref_imgs)
poses = []
for i in range(self.nb_ref_imgs):
in_encoder = torch.cat([target_image, ref_imgs[i]], 1)
out_encoder = self.encoder(in_encoder)
out_pose = self.pose_pred(out_encoder)
out_pose = out_pose.mean(3).mean(2)
out_pose = 0.01 * out_pose.view(out_pose.size(0), 1, 6)
poses.append(out_pose)
pose = torch.cat(poses, 1)
exp_mask4 = None
exp_mask3 = None
exp_mask2 = None
exp_mask1 = None
if self.training:
return [exp_mask1, exp_mask2, exp_mask3, exp_mask4], pose
else:
return exp_mask1, pose | SfmLearner-Pytorch/models/PoseSep.py | import torch
import torch.nn as nn
from torch import sigmoid
from torch.nn.init import xavier_uniform_, zeros_, kaiming_uniform_
import torchvision as tv
def conv(in_planes, out_planes, kernel_size=3):
return nn.Sequential(
nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, padding=(kernel_size-1)//2, stride=2),
nn.ReLU(inplace=True)
)
def upconv(in_planes, out_planes):
return nn.Sequential(
nn.ConvTranspose2d(in_planes, out_planes, kernel_size=4, stride=2, padding=1),
nn.ReLU(inplace=True)
)
class PoseSep(nn.Module):
def __init__(self, nb_ref_imgs=2, output_exp=False, encoder='conv'):
super(PoseSep, self).__init__()
assert(output_exp == False)
self.nb_ref_imgs = nb_ref_imgs
self.output_exp = output_exp
conv_planes = [16, 32, 64, 128, 256, 256, 256]
if encoder == 'conv':
self.encoder = nn.Sequential(
conv(6, conv_planes[0], kernel_size=7),
conv(conv_planes[0], conv_planes[1], kernel_size=5),
conv(conv_planes[1], conv_planes[2]),
conv(conv_planes[2], conv_planes[3]),
conv(conv_planes[3], conv_planes[4]),
conv(conv_planes[4], conv_planes[5]),
conv(conv_planes[5], conv_planes[6])
)
self.pose_pred = nn.Conv2d(conv_planes[6], 6, kernel_size=1, padding=0)
elif encoder == 'resnet':
resnet = tv.models.resnet18(pretrained=False)
self.encoder = nn.Sequential(*(list(resnet.children())[:-2]))
self.encoder[0] = nn.Conv2d(6, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
self.pose_pred = nn.Conv2d(512, 6, kernel_size=1, padding=0)
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):
# xavier_uniform_(m.weight.data)
kaiming_uniform_(m.weight.data)
if m.bias is not None:
zeros_(m.bias)
def forward(self, target_image, ref_imgs):
assert(len(ref_imgs) == self.nb_ref_imgs)
poses = []
for i in range(self.nb_ref_imgs):
in_encoder = torch.cat([target_image, ref_imgs[i]], 1)
out_encoder = self.encoder(in_encoder)
out_pose = self.pose_pred(out_encoder)
out_pose = out_pose.mean(3).mean(2)
out_pose = 0.01 * out_pose.view(out_pose.size(0), 1, 6)
poses.append(out_pose)
pose = torch.cat(poses, 1)
exp_mask4 = None
exp_mask3 = None
exp_mask2 = None
exp_mask1 = None
if self.training:
return [exp_mask1, exp_mask2, exp_mask3, exp_mask4], pose
else:
return exp_mask1, pose | 0.932294 | 0.715325 |
import argparse
import subprocess as sp
import re
import os
import json
from parse_uniprot_entry_file import *
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--database_file', type=str, required=True, help="Path to the uniprot database file.")
parser.add_argument('-d', '--download', type=bool, required=False, default=False, help="Whether the file should be updated.")
parser.add_argument('-o', '--output_folder', type=str, required=True, help='Path to the directory where the files should be saved.')
return parser.parse_args()
def parse_entry(entry):
return { 'uniprot_id': get_uniprot_id(entry),
'sequence': get_protein_sequence(entry),
'length': get_protein_length(entry),
'known_ptms': get_ptms(entry),
'regions': get_regions(entry),
'function': get_function(entry) }
def main():
if args.download:
sp.run('wget -O {}.gz ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/complete/uniprot_sprot.dat.gz && gzip -d {}.gz'.format(args.database_file, args.database_file),
shell=True)
# Open the UniprotKB file
print('Opening the database file {}...'.format(args.database_file))
database_content = open(args.database_file).read()
entries = database_content.split('//\n')
# Only keep human entries
human_entries = list(filter(lambda entry_string: 'NCBI_TaxID=9606' in entry_string, entries))
# Create the files
print('Deleting old files.')
sp.run('rm {}/*'.format(args.output_folder), shell=True)
print('Creating separate files in {}...'.format(args.output_folder))
for entry in human_entries:
# Parse the entry
entry_dict = parse_entry(entry)
# Save as a json file
output_path = os.path.join(args.output_folder, '{}.json'.format(json_format['uniprot_id']))
open(output_path, 'w').write(json.dumps(entry_dict))
if __name__ == '__main__':
main() | database/scripts/download_uniprot_as_files.py | import argparse
import subprocess as sp
import re
import os
import json
from parse_uniprot_entry_file import *
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--database_file', type=str, required=True, help="Path to the uniprot database file.")
parser.add_argument('-d', '--download', type=bool, required=False, default=False, help="Whether the file should be updated.")
parser.add_argument('-o', '--output_folder', type=str, required=True, help='Path to the directory where the files should be saved.')
return parser.parse_args()
def parse_entry(entry):
return { 'uniprot_id': get_uniprot_id(entry),
'sequence': get_protein_sequence(entry),
'length': get_protein_length(entry),
'known_ptms': get_ptms(entry),
'regions': get_regions(entry),
'function': get_function(entry) }
def main():
if args.download:
sp.run('wget -O {}.gz ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/complete/uniprot_sprot.dat.gz && gzip -d {}.gz'.format(args.database_file, args.database_file),
shell=True)
# Open the UniprotKB file
print('Opening the database file {}...'.format(args.database_file))
database_content = open(args.database_file).read()
entries = database_content.split('//\n')
# Only keep human entries
human_entries = list(filter(lambda entry_string: 'NCBI_TaxID=9606' in entry_string, entries))
# Create the files
print('Deleting old files.')
sp.run('rm {}/*'.format(args.output_folder), shell=True)
print('Creating separate files in {}...'.format(args.output_folder))
for entry in human_entries:
# Parse the entry
entry_dict = parse_entry(entry)
# Save as a json file
output_path = os.path.join(args.output_folder, '{}.json'.format(json_format['uniprot_id']))
open(output_path, 'w').write(json.dumps(entry_dict))
if __name__ == '__main__':
main() | 0.371251 | 0.099865 |
import tensorflow as tf
from detext.layers.embedding_layer import create_embedding_layer
from detext.utils.layer_utils import get_sorted_dict
from detext.utils.parsing_utils import InputFtrType, InternalFtrType
class LstmLayer(tf.keras.layers.Layer):
def __init__(self, bidirectional, rnn_dropout, num_layers, forget_bias,
min_len, max_len, embedding_layer_param, embedding_hub_url,
**kwargs):
""" Initializes the model
For more details on parameters, check the argument parser in run_detext.py
"""
super(LstmLayer, self).__init__()
self.min_len = tf.constant(min_len, dtype=tf.dtypes.int32)
self.max_len = tf.constant(max_len, dtype=tf.dtypes.int32)
self.num_cls_sep = tf.constant(1, dtype=tf.dtypes.int32)
self._bidirectional = bidirectional
self._forget_bias = forget_bias
self._rnn_dropout = rnn_dropout
self.forward_only = not bidirectional
self.embedding = create_embedding_layer(embedding_layer_param, embedding_hub_url)
self._num_units = self.embedding.num_units().numpy()
self.text_ftr_size = self._num_units
self.text_encoders = []
for _ in range(num_layers):
if self.forward_only:
encoder = self.create_encoder(self._num_units)
else:
assert self._num_units % 2 == 0, "num_units must be a multiplier of 2 when bidirectional is True"
fw_encoder = self.create_encoder(self._num_units // 2)
bw_encoder = self.create_encoder(self._num_units // 2, go_backwards=True)
encoder = tf.keras.layers.Bidirectional(fw_encoder, backward_layer=bw_encoder)
self.text_encoders.append(encoder)
def create_encoder(self, num_units, **kwargs):
return tf.keras.layers.LSTM(num_units, bias_initializer=tf.keras.initializers.Constant(self._forget_bias), dropout=self._rnn_dropout,
return_sequences=True, return_state=True, **kwargs)
def call(self, inputs, training=None, **kwargs):
""" Apply LSTM on text fields
:param query: Tensor(dtype=string) Shape=[batch_size]
:param doc_fields: list(Tensor(dtype=string))/Tensor A list of document fields. Each has shape=
[batch_size, max_group_size]. For online scoring, these fields may be precomputed and
input as Tensor
:param user_fields: list(Tensor(dtype=string))/Tensor A list of user fields. Each has shape=
[batch_size]. For online scoring, these fields may be precomputed and input as Tensor
:param training: boolean Whether it's under training mode
:return: query, document and user features
"""
query = inputs.get(InputFtrType.QUERY_COLUMN_NAME, None)
doc_fields = inputs.get(InputFtrType.DOC_TEXT_COLUMN_NAMES, None)
user_fields = inputs.get(InputFtrType.USER_TEXT_COLUMN_NAMES, None)
query_ftrs = self.apply_lstm_on_query(query, training) if query is not None else None
user_ftrs = self.apply_lstm_on_user(user_fields, training) if user_fields is not None else None
doc_ftrs = self.apply_lstm_on_doc(doc_fields, training) if doc_fields is not None else None
return query_ftrs, doc_ftrs, user_ftrs
def apply_lstm_on_query(self, query, training):
"""
Applies LSTM on query
:return Tensor Query features. Shape=[batch_size, text_ftr_size]
"""
return self.apply_lstm_on_text(query, training)[InternalFtrType.LAST_MEMORY_STATE]
def apply_lstm_on_user(self, user_fields, training):
"""
Applies LSTM on user fields
:return Tensor User features. Shape=[batch_size, num_user_fields, text_ftr_size]
"""
if type(user_fields) is not list:
return user_fields
user_ftrs = []
for i, user_field in enumerate(user_fields):
user_field_ftrs = self.apply_lstm_on_text(user_field, training)[InternalFtrType.LAST_MEMORY_STATE]
user_ftrs.append(user_field_ftrs)
user_ftrs = tf.stack(user_ftrs, axis=1) # shape=[batch_size, num_user_fields, text_ftr_size]
return user_ftrs
def apply_lstm_on_text(self, text, training):
""" Applies LSTM on text with params partially filled with class members """
return apply_lstm_on_text(text, self.text_encoders, self.embedding, self._bidirectional, self.min_len, self.max_len, self.num_cls_sep, training)
def apply_lstm_on_doc(self, doc_fields, training):
""" Applies LSTM on documents
:return Tensor Document features. Shape=[batch_size, max_group_size, num_doc_fields, text_ftr_size]
"""
# doc_fields should be the doc embeddings
if type(doc_fields) is not list:
return doc_fields
doc_ftrs = []
for i, doc_field in enumerate(doc_fields):
doc_shape = tf.shape(input=doc_field) # Shape=[batch_size, group_size, sent_length]
doc_field = tf.reshape(doc_field, shape=[doc_shape[0] * doc_shape[1]])
doc_field_ftrs = self.apply_lstm_on_text(doc_field, training)[InternalFtrType.LAST_MEMORY_STATE]
# Restore batch_size and group_size
doc_field_ftrs = tf.reshape(doc_field_ftrs, shape=[doc_shape[0], doc_shape[1], self.text_ftr_size])
doc_ftrs.append(doc_field_ftrs)
doc_ftrs = tf.stack(doc_ftrs, axis=2) # Shape=[batch_size, max_group_size, num_doc_fields, text_ftr_size]
return doc_ftrs
def apply_lstm_on_embedding(input_emb, mask, lstm_encoders, forward_only, training):
"""Applies LSTM on given embeddings
:param input_emb Tensor(dtype=float) Shape=[batch_size, sentence_len, num_units]
:return A dictionary containing
seq_outputs: Tensor(dtype=float) Shape=[batch_size, sentence_len, num_units]
last_memory_state: Tensor(dtype=float) Shape=[batch_size, num_units]
last_carry_state: Tensor(dtype=float) Shape=[batch_size, num_units]
"""
first_encoder = lstm_encoders[0]
mask = tf.cast(mask, dtype=tf.dtypes.bool)
if forward_only:
# Shape(seq_outputs) = [batch_size, seq_len, num_units]
seq_outputs, last_memory_state, last_carry_state = first_encoder(input_emb, mask=mask, training=training)
for encoder in lstm_encoders[1:]: # Multi layer LSTM
seq_outputs, last_memory_state, last_carry_state = encoder(seq_outputs, mask=mask, training=training)
else:
# Shape(seq_outputs) = [batch_size, seq_len, num_units]
seq_outputs, last_fw_memory_state, last_fw_carry_state, last_bw_memory_state, last_bw_carry_state = first_encoder(input_emb, mask=mask,
training=training)
for encoder in lstm_encoders[1:]: # Multi layer LSTM
seq_outputs, last_fw_memory_state, last_fw_carry_state, last_bw_memory_state, last_bw_carry_state = encoder(seq_outputs, mask=mask,
training=training)
last_memory_state = tf.concat([last_fw_memory_state, last_bw_memory_state], axis=-1)
last_carry_state = tf.concat([last_fw_carry_state, last_bw_carry_state], axis=-1)
return {InternalFtrType.SEQ_OUTPUTS: seq_outputs,
InternalFtrType.LAST_MEMORY_STATE: last_memory_state,
InternalFtrType.LAST_CARRY_STATE: last_carry_state}
def apply_lstm_on_text(text, lstm_encoders, embedding_layer, bidirectional, min_len, max_len, num_cls_sep, training):
"""
Applies LSTM on text
:param text: Tensor Shape=[batch_size]
:param lstm_encoders: List(LSTM) List of LSTMs that stacks sequentially
:param embedding_layer Tensor Embedding matrix
:param bidirectional boolean Indicator of whether it's bidirectional encoder
:param training boolean Indicator of whether it's under training mode
:return A dictionary containing
seq_outputs: Tensor(dtype=float) Shape=[batch_size, sentence_len, num_units]
last_memory_state: Tensor(dtype=float) Shape=[batch_size, num_units]
last_carry_state: Tensor(dtype=float) Shape=[batch_size, num_units]
"""
forward_only = not bidirectional
input_seq = text
inputs = get_sorted_dict(
{InternalFtrType.SENTENCES: input_seq,
InternalFtrType.NUM_CLS: num_cls_sep,
InternalFtrType.NUM_SEP: num_cls_sep,
InternalFtrType.MIN_LEN: min_len,
InternalFtrType.MAX_LEN: max_len,
}
)
embedding_result = embedding_layer(inputs)
input_emb = embedding_result[InternalFtrType.EMBEDDED]
seq_len = embedding_result[InternalFtrType.LENGTH]
max_seq_len = tf.math.reduce_max(seq_len)
mask = tf.sequence_mask(seq_len, max_seq_len, dtype=tf.float32)
results = apply_lstm_on_embedding(input_emb, mask, lstm_encoders, forward_only, training)
return results | src/detext/layers/lstm_layer.py | import tensorflow as tf
from detext.layers.embedding_layer import create_embedding_layer
from detext.utils.layer_utils import get_sorted_dict
from detext.utils.parsing_utils import InputFtrType, InternalFtrType
class LstmLayer(tf.keras.layers.Layer):
def __init__(self, bidirectional, rnn_dropout, num_layers, forget_bias,
min_len, max_len, embedding_layer_param, embedding_hub_url,
**kwargs):
""" Initializes the model
For more details on parameters, check the argument parser in run_detext.py
"""
super(LstmLayer, self).__init__()
self.min_len = tf.constant(min_len, dtype=tf.dtypes.int32)
self.max_len = tf.constant(max_len, dtype=tf.dtypes.int32)
self.num_cls_sep = tf.constant(1, dtype=tf.dtypes.int32)
self._bidirectional = bidirectional
self._forget_bias = forget_bias
self._rnn_dropout = rnn_dropout
self.forward_only = not bidirectional
self.embedding = create_embedding_layer(embedding_layer_param, embedding_hub_url)
self._num_units = self.embedding.num_units().numpy()
self.text_ftr_size = self._num_units
self.text_encoders = []
for _ in range(num_layers):
if self.forward_only:
encoder = self.create_encoder(self._num_units)
else:
assert self._num_units % 2 == 0, "num_units must be a multiplier of 2 when bidirectional is True"
fw_encoder = self.create_encoder(self._num_units // 2)
bw_encoder = self.create_encoder(self._num_units // 2, go_backwards=True)
encoder = tf.keras.layers.Bidirectional(fw_encoder, backward_layer=bw_encoder)
self.text_encoders.append(encoder)
def create_encoder(self, num_units, **kwargs):
return tf.keras.layers.LSTM(num_units, bias_initializer=tf.keras.initializers.Constant(self._forget_bias), dropout=self._rnn_dropout,
return_sequences=True, return_state=True, **kwargs)
def call(self, inputs, training=None, **kwargs):
""" Apply LSTM on text fields
:param query: Tensor(dtype=string) Shape=[batch_size]
:param doc_fields: list(Tensor(dtype=string))/Tensor A list of document fields. Each has shape=
[batch_size, max_group_size]. For online scoring, these fields may be precomputed and
input as Tensor
:param user_fields: list(Tensor(dtype=string))/Tensor A list of user fields. Each has shape=
[batch_size]. For online scoring, these fields may be precomputed and input as Tensor
:param training: boolean Whether it's under training mode
:return: query, document and user features
"""
query = inputs.get(InputFtrType.QUERY_COLUMN_NAME, None)
doc_fields = inputs.get(InputFtrType.DOC_TEXT_COLUMN_NAMES, None)
user_fields = inputs.get(InputFtrType.USER_TEXT_COLUMN_NAMES, None)
query_ftrs = self.apply_lstm_on_query(query, training) if query is not None else None
user_ftrs = self.apply_lstm_on_user(user_fields, training) if user_fields is not None else None
doc_ftrs = self.apply_lstm_on_doc(doc_fields, training) if doc_fields is not None else None
return query_ftrs, doc_ftrs, user_ftrs
def apply_lstm_on_query(self, query, training):
"""
Applies LSTM on query
:return Tensor Query features. Shape=[batch_size, text_ftr_size]
"""
return self.apply_lstm_on_text(query, training)[InternalFtrType.LAST_MEMORY_STATE]
def apply_lstm_on_user(self, user_fields, training):
"""
Applies LSTM on user fields
:return Tensor User features. Shape=[batch_size, num_user_fields, text_ftr_size]
"""
if type(user_fields) is not list:
return user_fields
user_ftrs = []
for i, user_field in enumerate(user_fields):
user_field_ftrs = self.apply_lstm_on_text(user_field, training)[InternalFtrType.LAST_MEMORY_STATE]
user_ftrs.append(user_field_ftrs)
user_ftrs = tf.stack(user_ftrs, axis=1) # shape=[batch_size, num_user_fields, text_ftr_size]
return user_ftrs
def apply_lstm_on_text(self, text, training):
""" Applies LSTM on text with params partially filled with class members """
return apply_lstm_on_text(text, self.text_encoders, self.embedding, self._bidirectional, self.min_len, self.max_len, self.num_cls_sep, training)
def apply_lstm_on_doc(self, doc_fields, training):
""" Applies LSTM on documents
:return Tensor Document features. Shape=[batch_size, max_group_size, num_doc_fields, text_ftr_size]
"""
# doc_fields should be the doc embeddings
if type(doc_fields) is not list:
return doc_fields
doc_ftrs = []
for i, doc_field in enumerate(doc_fields):
doc_shape = tf.shape(input=doc_field) # Shape=[batch_size, group_size, sent_length]
doc_field = tf.reshape(doc_field, shape=[doc_shape[0] * doc_shape[1]])
doc_field_ftrs = self.apply_lstm_on_text(doc_field, training)[InternalFtrType.LAST_MEMORY_STATE]
# Restore batch_size and group_size
doc_field_ftrs = tf.reshape(doc_field_ftrs, shape=[doc_shape[0], doc_shape[1], self.text_ftr_size])
doc_ftrs.append(doc_field_ftrs)
doc_ftrs = tf.stack(doc_ftrs, axis=2) # Shape=[batch_size, max_group_size, num_doc_fields, text_ftr_size]
return doc_ftrs
def apply_lstm_on_embedding(input_emb, mask, lstm_encoders, forward_only, training):
"""Applies LSTM on given embeddings
:param input_emb Tensor(dtype=float) Shape=[batch_size, sentence_len, num_units]
:return A dictionary containing
seq_outputs: Tensor(dtype=float) Shape=[batch_size, sentence_len, num_units]
last_memory_state: Tensor(dtype=float) Shape=[batch_size, num_units]
last_carry_state: Tensor(dtype=float) Shape=[batch_size, num_units]
"""
first_encoder = lstm_encoders[0]
mask = tf.cast(mask, dtype=tf.dtypes.bool)
if forward_only:
# Shape(seq_outputs) = [batch_size, seq_len, num_units]
seq_outputs, last_memory_state, last_carry_state = first_encoder(input_emb, mask=mask, training=training)
for encoder in lstm_encoders[1:]: # Multi layer LSTM
seq_outputs, last_memory_state, last_carry_state = encoder(seq_outputs, mask=mask, training=training)
else:
# Shape(seq_outputs) = [batch_size, seq_len, num_units]
seq_outputs, last_fw_memory_state, last_fw_carry_state, last_bw_memory_state, last_bw_carry_state = first_encoder(input_emb, mask=mask,
training=training)
for encoder in lstm_encoders[1:]: # Multi layer LSTM
seq_outputs, last_fw_memory_state, last_fw_carry_state, last_bw_memory_state, last_bw_carry_state = encoder(seq_outputs, mask=mask,
training=training)
last_memory_state = tf.concat([last_fw_memory_state, last_bw_memory_state], axis=-1)
last_carry_state = tf.concat([last_fw_carry_state, last_bw_carry_state], axis=-1)
return {InternalFtrType.SEQ_OUTPUTS: seq_outputs,
InternalFtrType.LAST_MEMORY_STATE: last_memory_state,
InternalFtrType.LAST_CARRY_STATE: last_carry_state}
def apply_lstm_on_text(text, lstm_encoders, embedding_layer, bidirectional, min_len, max_len, num_cls_sep, training):
"""
Applies LSTM on text
:param text: Tensor Shape=[batch_size]
:param lstm_encoders: List(LSTM) List of LSTMs that stacks sequentially
:param embedding_layer Tensor Embedding matrix
:param bidirectional boolean Indicator of whether it's bidirectional encoder
:param training boolean Indicator of whether it's under training mode
:return A dictionary containing
seq_outputs: Tensor(dtype=float) Shape=[batch_size, sentence_len, num_units]
last_memory_state: Tensor(dtype=float) Shape=[batch_size, num_units]
last_carry_state: Tensor(dtype=float) Shape=[batch_size, num_units]
"""
forward_only = not bidirectional
input_seq = text
inputs = get_sorted_dict(
{InternalFtrType.SENTENCES: input_seq,
InternalFtrType.NUM_CLS: num_cls_sep,
InternalFtrType.NUM_SEP: num_cls_sep,
InternalFtrType.MIN_LEN: min_len,
InternalFtrType.MAX_LEN: max_len,
}
)
embedding_result = embedding_layer(inputs)
input_emb = embedding_result[InternalFtrType.EMBEDDED]
seq_len = embedding_result[InternalFtrType.LENGTH]
max_seq_len = tf.math.reduce_max(seq_len)
mask = tf.sequence_mask(seq_len, max_seq_len, dtype=tf.float32)
results = apply_lstm_on_embedding(input_emb, mask, lstm_encoders, forward_only, training)
return results | 0.872673 | 0.447279 |
import ctypes
import datetime
from time import sleep
import cv2
import numpy as np
import sounddevice as sd
from scipy.io import wavfile, loadmat
import csv
""" ~~~~~~~~~~~~~ TUNABLE PARAMETERS ~~~~~~~~~~~~~ """
# Name of the matlab file containing the test sequence
MAT_FILE_NAME = "NBACK_2_VersionA.mat"
# The N value in "N-Back" (usually 1 or 2)
N = 2
# Name of given trial
TRIAL_NAME = "nback_test"
# Colors dictionary that identifies the RGB values of the used colors
LETTERS = np.array(["A", "B", "C", "D", "E", "H", "I", "K", "L", "M", "O", "P", "R", "S", "T"], dtype=str)
# Frequency of matching n back letters is 1:FREQUENCY (FREQUENCY = 4 means 1 in 4 responses should be "Yes")
FREQUENCY = 4
# Name of the matlab file containing stimulus info (include filepath if necessary)
NUM_TESTS = 20
# The minimum period, in milliseconds, that could distinguish two different responses
STIMULUS_INTERVAL_S = 0.75
INTERIAL_INTERVAL_S = 2.00
"""~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
# Get screen dimensions
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
# Make sure cv2 images are displayed in full screen
window_name = 'projector'
cv2.namedWindow(window_name, cv2.WND_PROP_FULLSCREEN)
cv2.moveWindow(window_name, screensize[1] - 1, screensize[0] - 1)
cv2.setWindowProperty(window_name, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
# Create a blank white image as a template
img = np.full((screensize[1], screensize[0], 3), fill_value=255, dtype=np.uint8)
# Define text parameters for stimuli images
font = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 15.0
fontThickness = 40
countDownFontScale = 7.0
coutDownFontThickness = 28
if __name__ == "__main__":
# Get test sequence from mat file
mat = loadmat(MAT_FILE_NAME)
letter_sequence = mat["Sequence"]
answer_array = mat["Answers"]
# Creates an array that contains the global time for each time stamp
stimuli_time_stamps = np.empty(NUM_TESTS, dtype=datetime.datetime)
# Create an array of stimuli images
stimuli_images = []
for i in range(len(LETTERS)):
# Copy the template image
new_img = np.copy(img)
# Determine text size from given word
textsize = cv2.getTextSize(LETTERS[i], font, 1, 2)[0]
# Define parameters for positioning text on a given blank image
textX = int((img.shape[1] - textsize[0] * fontScale) / 2)
textY = int((img.shape[0] + textsize[1] * fontScale) / 2)
bottomLeftCornerOfText = (textX, textY)
# Position text on the screen
cv2.putText(new_img, LETTERS[i],
bottomLeftCornerOfText,
font,
fontScale,
color=(0, 0, 0),
thickness=fontThickness)
# Add the image to the array
stimuli_images.append(new_img)
# Give user a countdown
for word in ["Get Ready...", "3..", "2..", "1..", "GO!!!"]:
# Copy blank image from template
new_img = np.copy(img)
# Determine text size
textsize = cv2.getTextSize(word, font, 1, 2)[0]
# Define parameters for positioning text on template image
textX = int((img.shape[1] - textsize[0] * countDownFontScale) / 2)
textY = int((img.shape[0] + textsize[1] * countDownFontScale) / 2)
bottomLeftCornerOfText = (textX, textY)
# Position text on the screen
cv2.putText(new_img, word,
bottomLeftCornerOfText,
font,
countDownFontScale,
color=(0, 0, 0), # make the words black
thickness=coutDownFontThickness)
# Wait out a 1s delay, then destory the image
cv2.imshow(window_name, new_img)
cv2.waitKey(1)
sleep(1.0)
sleep(0.5)
# Define recording parameters and start recording
rec_seconds = int(NUM_TESTS) * (INTERIAL_INTERVAL_S + STIMULUS_INTERVAL_S) + 10
sample_rate = 44100
myrecording = sd.rec(int(rec_seconds * sample_rate), samplerate=sample_rate, channels=1)
recording_start_time = datetime.datetime.now()
sleep(1)
# Displays the text to the user for given number of iterations
for i in range(NUM_TESTS):
# Show image add the given array position to the user
cv2.imshow(window_name, stimuli_images[np.where(LETTERS == letter_sequence[i])[0][0]])
# Get global time of stimulus
stimuli_time_stamps[i] = datetime.datetime.now()
# Wait out the given delay, then destory the image
cv2.waitKey(1)
sleep(STIMULUS_INTERVAL_S)
# Show blank image in between stimuli
cv2.imshow(window_name, img)
# Wait out the given delay, then destory the image
cv2.waitKey(1)
sleep(INTERIAL_INTERVAL_S)
# Destroy last displayed image
cv2.destroyAllWindows()
# Stop the recording, save file as .wav
print("Waiting for recording to stop...")
sd.wait()
wavfile.write(TRIAL_NAME + '.wav', sample_rate, myrecording) # Save as WAV file
print("Done. Saving data...")
# Calculate the time at which each stimulus is displayed with respect to the start of the recording
stimuli_time_stamps = np.array(
[(stimuli_time_stamps[i] - recording_start_time).total_seconds() for i in range(NUM_TESTS)])
# Write results to file
with open(TRIAL_NAME + ".csv", 'w') as reac_file:
writer = csv.writer(reac_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['Letter', 'Correct answer', 'Stimuli time from start (s)'])
for i in range(NUM_TESTS):
writer.writerow([letter_sequence[i], answer_array[i], stimuli_time_stamps[i]])
print("Done.") | run_nback.py | import ctypes
import datetime
from time import sleep
import cv2
import numpy as np
import sounddevice as sd
from scipy.io import wavfile, loadmat
import csv
""" ~~~~~~~~~~~~~ TUNABLE PARAMETERS ~~~~~~~~~~~~~ """
# Name of the matlab file containing the test sequence
MAT_FILE_NAME = "NBACK_2_VersionA.mat"
# The N value in "N-Back" (usually 1 or 2)
N = 2
# Name of given trial
TRIAL_NAME = "nback_test"
# Colors dictionary that identifies the RGB values of the used colors
LETTERS = np.array(["A", "B", "C", "D", "E", "H", "I", "K", "L", "M", "O", "P", "R", "S", "T"], dtype=str)
# Frequency of matching n back letters is 1:FREQUENCY (FREQUENCY = 4 means 1 in 4 responses should be "Yes")
FREQUENCY = 4
# Name of the matlab file containing stimulus info (include filepath if necessary)
NUM_TESTS = 20
# The minimum period, in milliseconds, that could distinguish two different responses
STIMULUS_INTERVAL_S = 0.75
INTERIAL_INTERVAL_S = 2.00
"""~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"""
# Get screen dimensions
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
# Make sure cv2 images are displayed in full screen
window_name = 'projector'
cv2.namedWindow(window_name, cv2.WND_PROP_FULLSCREEN)
cv2.moveWindow(window_name, screensize[1] - 1, screensize[0] - 1)
cv2.setWindowProperty(window_name, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)
# Create a blank white image as a template
img = np.full((screensize[1], screensize[0], 3), fill_value=255, dtype=np.uint8)
# Define text parameters for stimuli images
font = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 15.0
fontThickness = 40
countDownFontScale = 7.0
coutDownFontThickness = 28
if __name__ == "__main__":
# Get test sequence from mat file
mat = loadmat(MAT_FILE_NAME)
letter_sequence = mat["Sequence"]
answer_array = mat["Answers"]
# Creates an array that contains the global time for each time stamp
stimuli_time_stamps = np.empty(NUM_TESTS, dtype=datetime.datetime)
# Create an array of stimuli images
stimuli_images = []
for i in range(len(LETTERS)):
# Copy the template image
new_img = np.copy(img)
# Determine text size from given word
textsize = cv2.getTextSize(LETTERS[i], font, 1, 2)[0]
# Define parameters for positioning text on a given blank image
textX = int((img.shape[1] - textsize[0] * fontScale) / 2)
textY = int((img.shape[0] + textsize[1] * fontScale) / 2)
bottomLeftCornerOfText = (textX, textY)
# Position text on the screen
cv2.putText(new_img, LETTERS[i],
bottomLeftCornerOfText,
font,
fontScale,
color=(0, 0, 0),
thickness=fontThickness)
# Add the image to the array
stimuli_images.append(new_img)
# Give user a countdown
for word in ["Get Ready...", "3..", "2..", "1..", "GO!!!"]:
# Copy blank image from template
new_img = np.copy(img)
# Determine text size
textsize = cv2.getTextSize(word, font, 1, 2)[0]
# Define parameters for positioning text on template image
textX = int((img.shape[1] - textsize[0] * countDownFontScale) / 2)
textY = int((img.shape[0] + textsize[1] * countDownFontScale) / 2)
bottomLeftCornerOfText = (textX, textY)
# Position text on the screen
cv2.putText(new_img, word,
bottomLeftCornerOfText,
font,
countDownFontScale,
color=(0, 0, 0), # make the words black
thickness=coutDownFontThickness)
# Wait out a 1s delay, then destory the image
cv2.imshow(window_name, new_img)
cv2.waitKey(1)
sleep(1.0)
sleep(0.5)
# Define recording parameters and start recording
rec_seconds = int(NUM_TESTS) * (INTERIAL_INTERVAL_S + STIMULUS_INTERVAL_S) + 10
sample_rate = 44100
myrecording = sd.rec(int(rec_seconds * sample_rate), samplerate=sample_rate, channels=1)
recording_start_time = datetime.datetime.now()
sleep(1)
# Displays the text to the user for given number of iterations
for i in range(NUM_TESTS):
# Show image add the given array position to the user
cv2.imshow(window_name, stimuli_images[np.where(LETTERS == letter_sequence[i])[0][0]])
# Get global time of stimulus
stimuli_time_stamps[i] = datetime.datetime.now()
# Wait out the given delay, then destory the image
cv2.waitKey(1)
sleep(STIMULUS_INTERVAL_S)
# Show blank image in between stimuli
cv2.imshow(window_name, img)
# Wait out the given delay, then destory the image
cv2.waitKey(1)
sleep(INTERIAL_INTERVAL_S)
# Destroy last displayed image
cv2.destroyAllWindows()
# Stop the recording, save file as .wav
print("Waiting for recording to stop...")
sd.wait()
wavfile.write(TRIAL_NAME + '.wav', sample_rate, myrecording) # Save as WAV file
print("Done. Saving data...")
# Calculate the time at which each stimulus is displayed with respect to the start of the recording
stimuli_time_stamps = np.array(
[(stimuli_time_stamps[i] - recording_start_time).total_seconds() for i in range(NUM_TESTS)])
# Write results to file
with open(TRIAL_NAME + ".csv", 'w') as reac_file:
writer = csv.writer(reac_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['Letter', 'Correct answer', 'Stimuli time from start (s)'])
for i in range(NUM_TESTS):
writer.writerow([letter_sequence[i], answer_array[i], stimuli_time_stamps[i]])
print("Done.") | 0.592667 | 0.316726 |
from datamart.metadata.metadata_base import MetadataBase
from datamart.metadata.variable_metadata import VariableMetadata
from datamart.utils import Utils
class GlobalMetadata(MetadataBase):
def __init__(self, description: dict, datamart_id: int):
"""Init method of GlobalMetadata.
Args:
description: description dict.
datamart_id: unique datamart_id.
Returns:
"""
super().__init__()
self._metadata["datamart_id"] = datamart_id
if "title" in description:
self._metadata["title"] = description["title"]
if "description" in description:
self._metadata["description"] = description["description"]
if "url" in description:
self._metadata["url"] = description["url"]
if "keywords" in description:
self._metadata["keywords"] = description["keywords"]
if "date_published" in description:
self._metadata["date_published"] = description["date_published"]
if self.date_published:
self.date_published = Utils.date_validate(self.date_published)
if "date_updated" in description:
self._metadata["date_updated"] = description["date_updated"]
if self.date_updated:
self.date_updated = Utils.date_validate(self.date_updated)
if "provenance" in description:
self._metadata["provenance"] = description["provenance"]
if "original_identifier" in description:
self._metadata["original_identifier"] = description["original_identifier"]
try:
self._metadata["materialization"] = description["materialization"]
except:
raise ValueError("No materialization found")
if "python_path" not in self.materialization:
raise ValueError("No python path found in materialization")
if "arguments" not in self.materialization:
self._metadata["materialization"]["arguments"] = None
self._metadata["variables"] = list()
self._variables = list()
if "license" in description:
self._metadata["license"] = description["license"]
@classmethod
def construct_global(cls, description, datamart_id):
return cls(description, datamart_id)
def add_variable_metadata(self, variable_metadata: VariableMetadata):
"""Add a variable_metadata to this golbal metadata instance.
Args:
variable_metadata: VariableMetadata instance need to be added.
Returns:
"""
self._variables.append(variable_metadata)
self._metadata["variables"].append(variable_metadata.value)
@property
def datamart_id(self):
return self._metadata["datamart_id"]
@property
def title(self):
return self._metadata.get("title", False)
@title.setter
def title(self, value):
self._metadata["title"] = value
@property
def description(self):
return self._metadata.get("description", False)
@description.setter
def description(self, value):
self._metadata["description"] = value
@property
def url(self):
return self._metadata.get("url", False)
@property
def keywords(self):
return self._metadata.get("keywords", False)
@keywords.setter
def keywords(self, value):
self._metadata["keywords"] = value
@property
def date_published(self):
return self._metadata.get("date_published", False)
@date_published.setter
def date_published(self, value):
self._metadata["date_published"] = value
@property
def date_updated(self):
return self._metadata.get("date_updated", False)
@date_updated.setter
def date_updated(self, value):
self._metadata["date_updated"] = value
@property
def provenance(self):
return self._metadata.get("provenance", False)
@property
def original_identifier(self):
return self._metadata.get("original_identifier", False)
@property
def materialization(self):
return self._metadata["materialization"]
@property
def variables(self):
return self._variables
@property
def variable_values(self):
return self._metadata["variables"]
@property
def license(self):
return self._metadata.get("license", False)
@license.setter
def license(self, value):
self._metadata["license"] = value | datamart/metadata/global_metadata.py | from datamart.metadata.metadata_base import MetadataBase
from datamart.metadata.variable_metadata import VariableMetadata
from datamart.utils import Utils
class GlobalMetadata(MetadataBase):
def __init__(self, description: dict, datamart_id: int):
"""Init method of GlobalMetadata.
Args:
description: description dict.
datamart_id: unique datamart_id.
Returns:
"""
super().__init__()
self._metadata["datamart_id"] = datamart_id
if "title" in description:
self._metadata["title"] = description["title"]
if "description" in description:
self._metadata["description"] = description["description"]
if "url" in description:
self._metadata["url"] = description["url"]
if "keywords" in description:
self._metadata["keywords"] = description["keywords"]
if "date_published" in description:
self._metadata["date_published"] = description["date_published"]
if self.date_published:
self.date_published = Utils.date_validate(self.date_published)
if "date_updated" in description:
self._metadata["date_updated"] = description["date_updated"]
if self.date_updated:
self.date_updated = Utils.date_validate(self.date_updated)
if "provenance" in description:
self._metadata["provenance"] = description["provenance"]
if "original_identifier" in description:
self._metadata["original_identifier"] = description["original_identifier"]
try:
self._metadata["materialization"] = description["materialization"]
except:
raise ValueError("No materialization found")
if "python_path" not in self.materialization:
raise ValueError("No python path found in materialization")
if "arguments" not in self.materialization:
self._metadata["materialization"]["arguments"] = None
self._metadata["variables"] = list()
self._variables = list()
if "license" in description:
self._metadata["license"] = description["license"]
@classmethod
def construct_global(cls, description, datamart_id):
return cls(description, datamart_id)
def add_variable_metadata(self, variable_metadata: VariableMetadata):
"""Add a variable_metadata to this golbal metadata instance.
Args:
variable_metadata: VariableMetadata instance need to be added.
Returns:
"""
self._variables.append(variable_metadata)
self._metadata["variables"].append(variable_metadata.value)
@property
def datamart_id(self):
return self._metadata["datamart_id"]
@property
def title(self):
return self._metadata.get("title", False)
@title.setter
def title(self, value):
self._metadata["title"] = value
@property
def description(self):
return self._metadata.get("description", False)
@description.setter
def description(self, value):
self._metadata["description"] = value
@property
def url(self):
return self._metadata.get("url", False)
@property
def keywords(self):
return self._metadata.get("keywords", False)
@keywords.setter
def keywords(self, value):
self._metadata["keywords"] = value
@property
def date_published(self):
return self._metadata.get("date_published", False)
@date_published.setter
def date_published(self, value):
self._metadata["date_published"] = value
@property
def date_updated(self):
return self._metadata.get("date_updated", False)
@date_updated.setter
def date_updated(self, value):
self._metadata["date_updated"] = value
@property
def provenance(self):
return self._metadata.get("provenance", False)
@property
def original_identifier(self):
return self._metadata.get("original_identifier", False)
@property
def materialization(self):
return self._metadata["materialization"]
@property
def variables(self):
return self._variables
@property
def variable_values(self):
return self._metadata["variables"]
@property
def license(self):
return self._metadata.get("license", False)
@license.setter
def license(self, value):
self._metadata["license"] = value | 0.781205 | 0.138841 |
import numpy as np
from camos.tasks.analysis import Analysis
from camos.utils.generategui import (
NumericInput,
DatasetList,
CustomComboInput,
ImageInput,
)
from camos.plotter.image import Image
class Correlation(Analysis):
analysis_name = "Cluster Data"
required = ["dataset"]
def __init__(self, *args, **kwargs):
super(Correlation, self).__init__(*args, **kwargs)
self.methods = {
"K-means": self.k_means,
"DBSCAN": self.dbscan,
"Agglomerative Clustering": self.agglomerative,
"Gaussian Mixture": self.gaussian_mixture,
}
self.method = None
self.colname = "Cluster"
self.plotter = Image
def _run(
self,
nclust: NumericInput("# of clusters", 5),
eps: NumericInput("eps (DBSCAN only)", 0.3),
min_samples: NumericInput("Min Samples (DBSCAN only)", 10),
_i_data: DatasetList("Input Datasets to Cluster", 0),
_i_mask: ImageInput("Mask", 0),
method: CustomComboInput(
["K-means", "DBSCAN", "Agglomerative Clustering", "Gaussian Mixture"],
"Clustering Method",
0,
),
):
data = []
for i in _i_data:
data.append(self.signal.data[i])
if len(data) < 1:
raise ValueError("Dataset is empty")
ROIs = np.unique(data[0][:]["CellID"])
# Define the output data
output_type = [("CellID", "int"), ("Cluster", "int")]
self.output = np.zeros(shape=(len(ROIs), 1), dtype=output_type)
X = np.zeros(len(ROIs))
# Merge all selected datasets
for d in data:
for n in d.dtype.names:
if n != "CellID":
# Merge new column
X = np.vstack((X, d[n][:, 0]))
method_fun = self.methods[list(self.methods.keys())[method]]
_labels = (
method_fun(X.T, n=int(nclust), eps=eps, min_samples=int(min_samples)) + 1
)
self.output[:]["CellID"] = ROIs.reshape(-1, 1)
self.output[:]["Cluster"] = _labels.reshape(-1, 1)
print(X.T)
print(_labels)
self.mask = self.model.images[_i_mask].image(0)
def k_means(self, X, n=15, **kwargs):
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=n, random_state=0).fit(X)
return kmeans.labels_
def dbscan(self, X, eps=0.3, min_samples=10, **kwargs):
from sklearn.cluster import DBSCAN
db = DBSCAN(eps=eps, min_samples=min_samples).fit(X)
return db.labels_
def agglomerative(self, X, **kwargs):
from sklearn.cluster import AgglomerativeClustering
clustering = AgglomerativeClustering().fit(X)
return clustering.labels_
def gaussian_mixture(self, X, n, **kwargs):
from sklearn.mixture import GaussianMixture
gm = GaussianMixture(n_components=2, random_state=0).fit_predict(X)
return gm.labels_ | camos/plugins/clustering/clustering.py | import numpy as np
from camos.tasks.analysis import Analysis
from camos.utils.generategui import (
NumericInput,
DatasetList,
CustomComboInput,
ImageInput,
)
from camos.plotter.image import Image
class Correlation(Analysis):
analysis_name = "Cluster Data"
required = ["dataset"]
def __init__(self, *args, **kwargs):
super(Correlation, self).__init__(*args, **kwargs)
self.methods = {
"K-means": self.k_means,
"DBSCAN": self.dbscan,
"Agglomerative Clustering": self.agglomerative,
"Gaussian Mixture": self.gaussian_mixture,
}
self.method = None
self.colname = "Cluster"
self.plotter = Image
def _run(
self,
nclust: NumericInput("# of clusters", 5),
eps: NumericInput("eps (DBSCAN only)", 0.3),
min_samples: NumericInput("Min Samples (DBSCAN only)", 10),
_i_data: DatasetList("Input Datasets to Cluster", 0),
_i_mask: ImageInput("Mask", 0),
method: CustomComboInput(
["K-means", "DBSCAN", "Agglomerative Clustering", "Gaussian Mixture"],
"Clustering Method",
0,
),
):
data = []
for i in _i_data:
data.append(self.signal.data[i])
if len(data) < 1:
raise ValueError("Dataset is empty")
ROIs = np.unique(data[0][:]["CellID"])
# Define the output data
output_type = [("CellID", "int"), ("Cluster", "int")]
self.output = np.zeros(shape=(len(ROIs), 1), dtype=output_type)
X = np.zeros(len(ROIs))
# Merge all selected datasets
for d in data:
for n in d.dtype.names:
if n != "CellID":
# Merge new column
X = np.vstack((X, d[n][:, 0]))
method_fun = self.methods[list(self.methods.keys())[method]]
_labels = (
method_fun(X.T, n=int(nclust), eps=eps, min_samples=int(min_samples)) + 1
)
self.output[:]["CellID"] = ROIs.reshape(-1, 1)
self.output[:]["Cluster"] = _labels.reshape(-1, 1)
print(X.T)
print(_labels)
self.mask = self.model.images[_i_mask].image(0)
def k_means(self, X, n=15, **kwargs):
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=n, random_state=0).fit(X)
return kmeans.labels_
def dbscan(self, X, eps=0.3, min_samples=10, **kwargs):
from sklearn.cluster import DBSCAN
db = DBSCAN(eps=eps, min_samples=min_samples).fit(X)
return db.labels_
def agglomerative(self, X, **kwargs):
from sklearn.cluster import AgglomerativeClustering
clustering = AgglomerativeClustering().fit(X)
return clustering.labels_
def gaussian_mixture(self, X, n, **kwargs):
from sklearn.mixture import GaussianMixture
gm = GaussianMixture(n_components=2, random_state=0).fit_predict(X)
return gm.labels_ | 0.753739 | 0.435902 |
import os
import sys
def convert(filename, stream=sys.stdout):
fontname = os.path.splitext(os.path.basename(filename))[0]
fontname = fontname.replace('-', '_')
glyphs = []
comments = []
h = 16
w = 8
with open(filename) as handle:
for line in handle:
line = line.rstrip()
if line.startswith('# Height:'):
h = int(line.split(': ')[1])
elif line.startswith('# Width:'):
w = int(line.split(': ')[1])
elif line.startswith('#'):
comments.append(line[1:].strip())
else:
glyphs.extend(line.split(':')[1].decode('hex'))
l = len(glyphs)
if comments:
for comment in comments:
stream.write('// {0}\n'.format(comment))
stream.write('\n')
stream.write('uint8_t piece_{0}_font_glyphs[{t}] = {{\n'.format(
fontname,
l=l,
h=h,
t=l * h,
))
as_hex = lambda c: '0x%02x' % (ord(c),)
last = (len(glyphs) // 12) * 12
for i in range(0, len(glyphs), 12):
stream.write(' {0}'.format(
', '.join(map(as_hex, glyphs[i:i + 12])),
))
if i != last:
stream.write(',')
stream.write('\n')
stream.write('};\n\n')
stream.write('static piece_font piece_{0}_font = {{\n'.format(fontname))
stream.write(' "{0}",\n'.format(fontname))
stream.write(' {w},\n {h},\n {l},\n'.format(w=w, h=h, l=l))
stream.write(' piece_{0}_font_glyphs,\n'.format(fontname))
stream.write(' 0,\n NULL\n')
stream.write('};\n\n')
return fontname
def convert_to(sources, target):
with open(target, 'w') as handle:
handle.write('/* This file is generated, do not modify */\n\n')
handle.write('/* Splint directives */\n/*@+charint@*/\n\n')
handle.write('#include <stdint.h>\n')
handle.write('#include <stdlib.h>\n\n')
handle.write('#include "piece/font.h"\n')
handle.write('#include "piece/util.h"\n\n')
fontnames = []
for source in sources:
fontnames.append(convert(str(source), handle))
fontnames.sort()
handle.write('void piece_font_init(void) {\n')
handle.write(' piece_fonts = piece_allocate(sizeof(piece_list));\n');
handle.write(' piece_list_new(piece_fonts, piece_font_free_item);\n')
for fontname in fontnames:
handle.write(' piece_list_append(piece_fonts, &piece_{0}_font);\n'
.format(fontname))
handle.write(' piece_font_init_alias();\n')
handle.write('}\n\n')
def run():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('font', nargs=1)
options = parser.parse_args()
convert(options.font[0])
if __name__ == '__main__':
sys.exit(run()) | site_scons/mkfont.py |
import os
import sys
def convert(filename, stream=sys.stdout):
fontname = os.path.splitext(os.path.basename(filename))[0]
fontname = fontname.replace('-', '_')
glyphs = []
comments = []
h = 16
w = 8
with open(filename) as handle:
for line in handle:
line = line.rstrip()
if line.startswith('# Height:'):
h = int(line.split(': ')[1])
elif line.startswith('# Width:'):
w = int(line.split(': ')[1])
elif line.startswith('#'):
comments.append(line[1:].strip())
else:
glyphs.extend(line.split(':')[1].decode('hex'))
l = len(glyphs)
if comments:
for comment in comments:
stream.write('// {0}\n'.format(comment))
stream.write('\n')
stream.write('uint8_t piece_{0}_font_glyphs[{t}] = {{\n'.format(
fontname,
l=l,
h=h,
t=l * h,
))
as_hex = lambda c: '0x%02x' % (ord(c),)
last = (len(glyphs) // 12) * 12
for i in range(0, len(glyphs), 12):
stream.write(' {0}'.format(
', '.join(map(as_hex, glyphs[i:i + 12])),
))
if i != last:
stream.write(',')
stream.write('\n')
stream.write('};\n\n')
stream.write('static piece_font piece_{0}_font = {{\n'.format(fontname))
stream.write(' "{0}",\n'.format(fontname))
stream.write(' {w},\n {h},\n {l},\n'.format(w=w, h=h, l=l))
stream.write(' piece_{0}_font_glyphs,\n'.format(fontname))
stream.write(' 0,\n NULL\n')
stream.write('};\n\n')
return fontname
def convert_to(sources, target):
with open(target, 'w') as handle:
handle.write('/* This file is generated, do not modify */\n\n')
handle.write('/* Splint directives */\n/*@+charint@*/\n\n')
handle.write('#include <stdint.h>\n')
handle.write('#include <stdlib.h>\n\n')
handle.write('#include "piece/font.h"\n')
handle.write('#include "piece/util.h"\n\n')
fontnames = []
for source in sources:
fontnames.append(convert(str(source), handle))
fontnames.sort()
handle.write('void piece_font_init(void) {\n')
handle.write(' piece_fonts = piece_allocate(sizeof(piece_list));\n');
handle.write(' piece_list_new(piece_fonts, piece_font_free_item);\n')
for fontname in fontnames:
handle.write(' piece_list_append(piece_fonts, &piece_{0}_font);\n'
.format(fontname))
handle.write(' piece_font_init_alias();\n')
handle.write('}\n\n')
def run():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('font', nargs=1)
options = parser.parse_args()
convert(options.font[0])
if __name__ == '__main__':
sys.exit(run()) | 0.255715 | 0.076064 |
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from forch.proto import devices_state_pb2 as forch_dot_proto_dot_devices__state__pb2
from forch.proto import shared_constants_pb2 as forch_dot_proto_dot_shared__constants__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='forch/proto/grpc/device_report.proto',
package='',
syntax='proto3',
serialized_options=None,
create_key=_descriptor._internal_create_key,
serialized_pb=b'\n$forch/proto/grpc/device_report.proto\x1a\x1f\x66orch/proto/devices_state.proto\x1a\"forch/proto/shared_constants.proto2l\n\x0c\x44\x65viceReport\x12-\n\x12ReportDevicesState\x12\r.DevicesState\x1a\x06.Empty\"\x00\x12-\n\x0cGetPortState\x12\x07.Device\x1a\x10.DevicePortEvent\"\x00\x30\x01\x62\x06proto3'
,
dependencies=[forch_dot_proto_dot_devices__state__pb2.DESCRIPTOR,forch_dot_proto_dot_shared__constants__pb2.DESCRIPTOR,])
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
_DEVICEREPORT = _descriptor.ServiceDescriptor(
name='DeviceReport',
full_name='DeviceReport',
file=DESCRIPTOR,
index=0,
serialized_options=None,
create_key=_descriptor._internal_create_key,
serialized_start=109,
serialized_end=217,
methods=[
_descriptor.MethodDescriptor(
name='ReportDevicesState',
full_name='DeviceReport.ReportDevicesState',
index=0,
containing_service=None,
input_type=forch_dot_proto_dot_devices__state__pb2._DEVICESSTATE,
output_type=forch_dot_proto_dot_shared__constants__pb2._EMPTY,
serialized_options=None,
create_key=_descriptor._internal_create_key,
),
_descriptor.MethodDescriptor(
name='GetPortState',
full_name='DeviceReport.GetPortState',
index=1,
containing_service=None,
input_type=forch_dot_proto_dot_devices__state__pb2._DEVICE,
output_type=forch_dot_proto_dot_devices__state__pb2._DEVICEPORTEVENT,
serialized_options=None,
create_key=_descriptor._internal_create_key,
),
])
_sym_db.RegisterServiceDescriptor(_DEVICEREPORT)
DESCRIPTOR.services_by_name['DeviceReport'] = _DEVICEREPORT
# @@protoc_insertion_point(module_scope) | forch/proto/grpc/device_report_pb2.py | """Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from forch.proto import devices_state_pb2 as forch_dot_proto_dot_devices__state__pb2
from forch.proto import shared_constants_pb2 as forch_dot_proto_dot_shared__constants__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='forch/proto/grpc/device_report.proto',
package='',
syntax='proto3',
serialized_options=None,
create_key=_descriptor._internal_create_key,
serialized_pb=b'\n$forch/proto/grpc/device_report.proto\x1a\x1f\x66orch/proto/devices_state.proto\x1a\"forch/proto/shared_constants.proto2l\n\x0c\x44\x65viceReport\x12-\n\x12ReportDevicesState\x12\r.DevicesState\x1a\x06.Empty\"\x00\x12-\n\x0cGetPortState\x12\x07.Device\x1a\x10.DevicePortEvent\"\x00\x30\x01\x62\x06proto3'
,
dependencies=[forch_dot_proto_dot_devices__state__pb2.DESCRIPTOR,forch_dot_proto_dot_shared__constants__pb2.DESCRIPTOR,])
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
_DEVICEREPORT = _descriptor.ServiceDescriptor(
name='DeviceReport',
full_name='DeviceReport',
file=DESCRIPTOR,
index=0,
serialized_options=None,
create_key=_descriptor._internal_create_key,
serialized_start=109,
serialized_end=217,
methods=[
_descriptor.MethodDescriptor(
name='ReportDevicesState',
full_name='DeviceReport.ReportDevicesState',
index=0,
containing_service=None,
input_type=forch_dot_proto_dot_devices__state__pb2._DEVICESSTATE,
output_type=forch_dot_proto_dot_shared__constants__pb2._EMPTY,
serialized_options=None,
create_key=_descriptor._internal_create_key,
),
_descriptor.MethodDescriptor(
name='GetPortState',
full_name='DeviceReport.GetPortState',
index=1,
containing_service=None,
input_type=forch_dot_proto_dot_devices__state__pb2._DEVICE,
output_type=forch_dot_proto_dot_devices__state__pb2._DEVICEPORTEVENT,
serialized_options=None,
create_key=_descriptor._internal_create_key,
),
])
_sym_db.RegisterServiceDescriptor(_DEVICEREPORT)
DESCRIPTOR.services_by_name['DeviceReport'] = _DEVICEREPORT
# @@protoc_insertion_point(module_scope) | 0.265404 | 0.089256 |
from django.utils import timezone
from pytz import UTC
from .availability_calendar_api import format_event_availability_calendar, activate_users_saved_timezone
from ..models import Event
from datetime import datetime, timedelta
def format_group_availability_calendar(event_id):
"""
Takes in event_id, accesses all user's event availability in database, converts to the viewing user's timezone,
and finally creates a table of the possible days and hours of the event with the each cell representing the number
of event members available at that given time.
:param event_id:
:return: a table of integers keyed on times
"13:00" [8, 10, 9, 10, ....]
"13:30" [9, 9, 8, ....]
"""
# First access and store all user_id
query = Event.objects.filter(event_id=event_id)
if query.count() == 0:
return None
else:
event = query[0]
user_schedules = []
for user in event.members.all():
user_schedules.append({user: format_event_availability_calendar(user, event_id)})
# Create appropriate table for group_availability
group_availability = {}
number_of_days = (event.potential_end_date - event.potential_start_date).days + 1
dt = datetime(year=1, month=1, day=1)
dt_end = datetime(year=1, month=1, day=2)
while dt < dt_end:
group_availability[dt.strftime("%I:%M %p")] = [[] for i in range(number_of_days)]
dt = dt + timedelta(minutes=30)
# Properly fill in dictionary with users available at each time
for schedule in user_schedules:
schedule_user = list(schedule.keys())[0]
availability = list(schedule.values())[0]
for half_hour_period in availability:
day_tracker = 0
for day in availability[half_hour_period]:
if day is False:
group_availability[half_hour_period][day_tracker].append(schedule_user)
day_tracker = day_tracker + 1
return group_availability
def add_member_ratios(event_id, group_availability):
"""
:param event_id: The id of the event
:param group_availability: The formatted group availability calendar
:return:
"""
# First access and store all user_id
query = Event.objects.filter(event_id=event_id)
if query.count() == 0:
return None
else:
event = query[0]
# Create appropriate table for group_availability
group_ratio = {}
number_of_days = (event.potential_end_date - event.potential_start_date).days + 1
dt = datetime(year=1, month=1, day=1)
dt_end = datetime(year=1, month=1, day=2)
while dt < dt_end:
group_ratio[dt.strftime("%I:%M %p")] = [0.0] * number_of_days
dt = dt + timedelta(minutes=30)
# Fill in each related cell with the appropriate ratio of people available
for half_hour_period in group_availability:
day_tracker = 0
for day in group_availability[half_hour_period]:
group_ratio[half_hour_period][day_tracker] = len(day) / event.members.count()
day_tracker = day_tracker + 1
return group_ratio
def apply_event_time_constraints(event, busy_times):
start_idx = event.no_earlier_than.hour * 2
end_idx = event.no_later_than.hour * 2
time_keys = list(busy_times.keys())
time_keys = time_keys[start_idx:end_idx]
busy_times_cut = dict.fromkeys(time_keys)
for k in time_keys:
busy_times_cut[k] = busy_times[k]
return busy_times_cut
def cut_user_availability_dates_to_match_event(user, event, busy_times):
activate_users_saved_timezone(user)
start_date = timezone.localtime(datetime.utcnow().replace(tzinfo=UTC)).replace(hour=0, minute=0, second=0,
microsecond=0).replace(tzinfo=UTC)
timezone.activate('UTC')
event_start_date = event.potential_start_date
time_keys = list(busy_times.keys())
while start_date > event_start_date:
event_start_date = event_start_date + timedelta(days=1)
for k in time_keys:
busy_times[k] = [False] + busy_times[k]
return busy_times | LinkUp/core/apis/event_calendar_api.py | from django.utils import timezone
from pytz import UTC
from .availability_calendar_api import format_event_availability_calendar, activate_users_saved_timezone
from ..models import Event
from datetime import datetime, timedelta
def format_group_availability_calendar(event_id):
"""
Takes in event_id, accesses all user's event availability in database, converts to the viewing user's timezone,
and finally creates a table of the possible days and hours of the event with the each cell representing the number
of event members available at that given time.
:param event_id:
:return: a table of integers keyed on times
"13:00" [8, 10, 9, 10, ....]
"13:30" [9, 9, 8, ....]
"""
# First access and store all user_id
query = Event.objects.filter(event_id=event_id)
if query.count() == 0:
return None
else:
event = query[0]
user_schedules = []
for user in event.members.all():
user_schedules.append({user: format_event_availability_calendar(user, event_id)})
# Create appropriate table for group_availability
group_availability = {}
number_of_days = (event.potential_end_date - event.potential_start_date).days + 1
dt = datetime(year=1, month=1, day=1)
dt_end = datetime(year=1, month=1, day=2)
while dt < dt_end:
group_availability[dt.strftime("%I:%M %p")] = [[] for i in range(number_of_days)]
dt = dt + timedelta(minutes=30)
# Properly fill in dictionary with users available at each time
for schedule in user_schedules:
schedule_user = list(schedule.keys())[0]
availability = list(schedule.values())[0]
for half_hour_period in availability:
day_tracker = 0
for day in availability[half_hour_period]:
if day is False:
group_availability[half_hour_period][day_tracker].append(schedule_user)
day_tracker = day_tracker + 1
return group_availability
def add_member_ratios(event_id, group_availability):
"""
:param event_id: The id of the event
:param group_availability: The formatted group availability calendar
:return:
"""
# First access and store all user_id
query = Event.objects.filter(event_id=event_id)
if query.count() == 0:
return None
else:
event = query[0]
# Create appropriate table for group_availability
group_ratio = {}
number_of_days = (event.potential_end_date - event.potential_start_date).days + 1
dt = datetime(year=1, month=1, day=1)
dt_end = datetime(year=1, month=1, day=2)
while dt < dt_end:
group_ratio[dt.strftime("%I:%M %p")] = [0.0] * number_of_days
dt = dt + timedelta(minutes=30)
# Fill in each related cell with the appropriate ratio of people available
for half_hour_period in group_availability:
day_tracker = 0
for day in group_availability[half_hour_period]:
group_ratio[half_hour_period][day_tracker] = len(day) / event.members.count()
day_tracker = day_tracker + 1
return group_ratio
def apply_event_time_constraints(event, busy_times):
start_idx = event.no_earlier_than.hour * 2
end_idx = event.no_later_than.hour * 2
time_keys = list(busy_times.keys())
time_keys = time_keys[start_idx:end_idx]
busy_times_cut = dict.fromkeys(time_keys)
for k in time_keys:
busy_times_cut[k] = busy_times[k]
return busy_times_cut
def cut_user_availability_dates_to_match_event(user, event, busy_times):
activate_users_saved_timezone(user)
start_date = timezone.localtime(datetime.utcnow().replace(tzinfo=UTC)).replace(hour=0, minute=0, second=0,
microsecond=0).replace(tzinfo=UTC)
timezone.activate('UTC')
event_start_date = event.potential_start_date
time_keys = list(busy_times.keys())
while start_date > event_start_date:
event_start_date = event_start_date + timedelta(days=1)
for k in time_keys:
busy_times[k] = [False] + busy_times[k]
return busy_times | 0.800731 | 0.368207 |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from mephisto.data_model.assignment import (
Assignment,
InitializationData,
AssignmentState,
)
from mephisto.data_model.unit import Unit
from typing import Dict, Optional, List, Any, TYPE_CHECKING, Iterator
from tqdm import tqdm # type: ignore
import os
import time
import enum
if TYPE_CHECKING:
from mephisto.data_model.task_run import TaskRun
from mephisto.abstractions.database import MephistoDB
import threading
from mephisto.operations.logger_core import get_logger
import types
logger = get_logger(name=__name__)
UNIT_GENERATOR_WAIT_SECONDS = 10
ASSIGNMENT_GENERATOR_WAIT_SECONDS = 0.5
SCREENING_UNIT_INDEX = -1
GOLD_UNIT_INDEX = -2
COMPENSATION_UNIT_INDEX = -3
class GeneratorType(enum.Enum):
NONE = 0
UNIT = 1
ASSIGNMENT = 2
class TaskLauncher:
"""
This class is responsible for managing the process of registering
and launching units, including the steps for pre-processing
data and storing them locally for assignments when appropriate.
"""
def __init__(
self,
db: "MephistoDB",
task_run: "TaskRun",
assignment_data_iterator: Iterator[InitializationData],
max_num_concurrent_units: int = 0,
):
"""Prepare the task launcher to get it ready to launch the assignments"""
self.db = db
self.task_run = task_run
self.assignment_data_iterable = assignment_data_iterator
self.assignments: List[Assignment] = []
self.units: List[Unit] = []
self.provider_type = task_run.get_provider().PROVIDER_TYPE
self.max_num_concurrent_units = max_num_concurrent_units
self.launched_units: Dict[str, Unit] = {}
self.unlaunched_units: Dict[str, Unit] = {}
self.keep_launching_units: bool = False
self.finished_generators: bool = False
self.assignment_thread_done: bool = True
self.launch_url: Optional[str] = None
self.unlaunched_units_access_condition = threading.Condition()
if isinstance(self.assignment_data_iterable, types.GeneratorType):
self.generator_type = GeneratorType.ASSIGNMENT
self.assignment_thread_done = False
elif max_num_concurrent_units != 0:
self.generator_type = GeneratorType.UNIT
else:
self.generator_type = GeneratorType.NONE
run_dir = task_run.get_run_dir()
os.makedirs(run_dir, exist_ok=True)
logger.debug(f"type of assignment data: {type(self.assignment_data_iterable)}")
self.units_thread: Optional[threading.Thread] = None
self.assignments_thread: Optional[threading.Thread] = None
def _create_single_assignment(self, assignment_data) -> None:
"""Create a single assignment in the database using its read assignment_data"""
task_run = self.task_run
task_config = task_run.get_task_config()
assignment_id = self.db.new_assignment(
task_run.task_id,
task_run.db_id,
task_run.requester_id,
task_run.task_type,
task_run.provider_type,
task_run.sandbox,
)
assignment = Assignment.get(self.db, assignment_id)
assignment.write_assignment_data(assignment_data)
self.assignments.append(assignment)
unit_count = len(assignment_data.unit_data)
for unit_idx in range(unit_count):
unit_id = self.db.new_unit(
task_run.task_id,
task_run.db_id,
task_run.requester_id,
assignment_id,
unit_idx,
task_config.task_reward,
task_run.provider_type,
task_run.task_type,
task_run.sandbox,
)
self.units.append(Unit.get(self.db, unit_id))
with self.unlaunched_units_access_condition:
self.unlaunched_units[unit_id] = Unit.get(self.db, unit_id)
def _try_generating_assignments(self) -> None:
"""Try to generate more assignments from the assignments_data_iterator"""
while not self.finished_generators:
try:
data = next(self.assignment_data_iterable)
self._create_single_assignment(data)
except StopIteration:
self.assignment_thread_done = True
time.sleep(ASSIGNMENT_GENERATOR_WAIT_SECONDS)
def create_assignments(self) -> None:
"""Create an assignment and associated units for the generated assignment data"""
self.keep_launching_units = True
if self.generator_type != GeneratorType.ASSIGNMENT:
for data in self.assignment_data_iterable:
self._create_single_assignment(data)
else:
self.assignments_thread = threading.Thread(
target=self._try_generating_assignments,
args=(),
name="assignment-generator",
)
self.assignments_thread.start()
def generate_units(self):
"""units generator which checks that only 'max_num_concurrent_units' running at the same time,
i.e. in the LAUNCHED or ASSIGNED states"""
while self.keep_launching_units:
units_id_to_remove = []
for db_id, unit in self.launched_units.items():
status = unit.get_status()
if (
status != AssignmentState.LAUNCHED
and status != AssignmentState.ASSIGNED
):
units_id_to_remove.append(db_id)
for db_id in units_id_to_remove:
self.launched_units.pop(db_id)
num_avail_units = self.max_num_concurrent_units - len(self.launched_units)
num_avail_units = (
len(self.unlaunched_units)
if self.max_num_concurrent_units == 0
else num_avail_units
)
units_id_to_remove = []
for i, item in enumerate(self.unlaunched_units.items()):
db_id, unit = item
if i < num_avail_units:
self.launched_units[unit.db_id] = unit
units_id_to_remove.append(db_id)
yield unit
else:
break
with self.unlaunched_units_access_condition:
for db_id in units_id_to_remove:
self.unlaunched_units.pop(db_id)
time.sleep(UNIT_GENERATOR_WAIT_SECONDS)
if not self.unlaunched_units:
break
def _launch_limited_units(self, url: str) -> None:
"""use units' generator to launch limited number of units according to (max_num_concurrent_units)"""
# Continue launching if we haven't pulled the plug, so long as there are currently
# units to launch, or more may come in the future.
while not self.finished_generators and (
len(self.unlaunched_units) > 0 or not self.assignment_thread_done
):
for unit in self.generate_units():
if unit is None:
break
unit.launch(url)
if self.generator_type == GeneratorType.NONE:
break
self.finished_generators = True
def launch_units(self, url: str) -> None:
"""launch any units registered by this TaskLauncher"""
self.launch_url = url
self.units_thread = threading.Thread(
target=self._launch_limited_units, args=(url,), name="unit-generator"
)
self.units_thread.start()
def launch_evaluation_unit(
self, unit_data: Dict[str, Any], unit_type_index: int
) -> "Unit":
"""Launch a specific evaluation unit, used for quality control"""
assert (
self.launch_url is not None
), "Cannot launch an evaluation unit before launching others"
task_run = self.task_run
task_config = task_run.get_task_config()
assignment_id = self.db.new_assignment(
task_run.task_id,
task_run.db_id,
task_run.requester_id,
task_run.task_type,
task_run.provider_type,
task_run.sandbox,
)
data = InitializationData(unit_data, [{}])
assignment = Assignment.get(self.db, assignment_id)
assignment.write_assignment_data(data)
self.assignments.append(assignment)
unit_id = self.db.new_unit(
task_run.task_id,
task_run.db_id,
task_run.requester_id,
assignment_id,
unit_type_index,
task_config.task_reward,
task_run.provider_type,
task_run.task_type,
task_run.sandbox,
)
evaluation_unit = Unit.get(self.db, unit_id)
evaluation_unit.launch(self.launch_url)
return evaluation_unit
def launch_screening_unit(self, unit_data: Dict[str, Any]) -> "Unit":
"""Launch a screening unit, which should never return to the pool"""
return self.launch_evaluation_unit(unit_data, SCREENING_UNIT_INDEX)
def launch_gold_unit(self, unit_data: Dict[str, Any]) -> "Unit":
"""Launch a screening unit, which should never return to the pool"""
return self.launch_evaluation_unit(unit_data, GOLD_UNIT_INDEX)
def get_assignments_are_all_created(self) -> bool:
return self.assignment_thread_done
def expire_units(self) -> None:
"""Clean up all units on this TaskLauncher"""
self.keep_launching_units = False
self.finished_generators = True
for unit in tqdm(self.units):
try:
unit.expire()
except Exception as e:
logger.exception(
f"Warning: failed to expire unit {unit.db_id}. Stated error: {e}",
exc_info=True,
)
def shutdown(self) -> None:
"""Clean up running threads for generating assignments and units"""
self.assignment_thread_done = True
self.keep_launching_units = False
self.finished_generators = True
if self.assignments_thread is not None:
self.assignments_thread.join()
if self.units_thread is not None:
self.units_thread.join() | mephisto/operations/task_launcher.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from mephisto.data_model.assignment import (
Assignment,
InitializationData,
AssignmentState,
)
from mephisto.data_model.unit import Unit
from typing import Dict, Optional, List, Any, TYPE_CHECKING, Iterator
from tqdm import tqdm # type: ignore
import os
import time
import enum
if TYPE_CHECKING:
from mephisto.data_model.task_run import TaskRun
from mephisto.abstractions.database import MephistoDB
import threading
from mephisto.operations.logger_core import get_logger
import types
logger = get_logger(name=__name__)
UNIT_GENERATOR_WAIT_SECONDS = 10
ASSIGNMENT_GENERATOR_WAIT_SECONDS = 0.5
SCREENING_UNIT_INDEX = -1
GOLD_UNIT_INDEX = -2
COMPENSATION_UNIT_INDEX = -3
class GeneratorType(enum.Enum):
NONE = 0
UNIT = 1
ASSIGNMENT = 2
class TaskLauncher:
"""
This class is responsible for managing the process of registering
and launching units, including the steps for pre-processing
data and storing them locally for assignments when appropriate.
"""
def __init__(
self,
db: "MephistoDB",
task_run: "TaskRun",
assignment_data_iterator: Iterator[InitializationData],
max_num_concurrent_units: int = 0,
):
"""Prepare the task launcher to get it ready to launch the assignments"""
self.db = db
self.task_run = task_run
self.assignment_data_iterable = assignment_data_iterator
self.assignments: List[Assignment] = []
self.units: List[Unit] = []
self.provider_type = task_run.get_provider().PROVIDER_TYPE
self.max_num_concurrent_units = max_num_concurrent_units
self.launched_units: Dict[str, Unit] = {}
self.unlaunched_units: Dict[str, Unit] = {}
self.keep_launching_units: bool = False
self.finished_generators: bool = False
self.assignment_thread_done: bool = True
self.launch_url: Optional[str] = None
self.unlaunched_units_access_condition = threading.Condition()
if isinstance(self.assignment_data_iterable, types.GeneratorType):
self.generator_type = GeneratorType.ASSIGNMENT
self.assignment_thread_done = False
elif max_num_concurrent_units != 0:
self.generator_type = GeneratorType.UNIT
else:
self.generator_type = GeneratorType.NONE
run_dir = task_run.get_run_dir()
os.makedirs(run_dir, exist_ok=True)
logger.debug(f"type of assignment data: {type(self.assignment_data_iterable)}")
self.units_thread: Optional[threading.Thread] = None
self.assignments_thread: Optional[threading.Thread] = None
def _create_single_assignment(self, assignment_data) -> None:
"""Create a single assignment in the database using its read assignment_data"""
task_run = self.task_run
task_config = task_run.get_task_config()
assignment_id = self.db.new_assignment(
task_run.task_id,
task_run.db_id,
task_run.requester_id,
task_run.task_type,
task_run.provider_type,
task_run.sandbox,
)
assignment = Assignment.get(self.db, assignment_id)
assignment.write_assignment_data(assignment_data)
self.assignments.append(assignment)
unit_count = len(assignment_data.unit_data)
for unit_idx in range(unit_count):
unit_id = self.db.new_unit(
task_run.task_id,
task_run.db_id,
task_run.requester_id,
assignment_id,
unit_idx,
task_config.task_reward,
task_run.provider_type,
task_run.task_type,
task_run.sandbox,
)
self.units.append(Unit.get(self.db, unit_id))
with self.unlaunched_units_access_condition:
self.unlaunched_units[unit_id] = Unit.get(self.db, unit_id)
def _try_generating_assignments(self) -> None:
"""Try to generate more assignments from the assignments_data_iterator"""
while not self.finished_generators:
try:
data = next(self.assignment_data_iterable)
self._create_single_assignment(data)
except StopIteration:
self.assignment_thread_done = True
time.sleep(ASSIGNMENT_GENERATOR_WAIT_SECONDS)
def create_assignments(self) -> None:
"""Create an assignment and associated units for the generated assignment data"""
self.keep_launching_units = True
if self.generator_type != GeneratorType.ASSIGNMENT:
for data in self.assignment_data_iterable:
self._create_single_assignment(data)
else:
self.assignments_thread = threading.Thread(
target=self._try_generating_assignments,
args=(),
name="assignment-generator",
)
self.assignments_thread.start()
def generate_units(self):
"""units generator which checks that only 'max_num_concurrent_units' running at the same time,
i.e. in the LAUNCHED or ASSIGNED states"""
while self.keep_launching_units:
units_id_to_remove = []
for db_id, unit in self.launched_units.items():
status = unit.get_status()
if (
status != AssignmentState.LAUNCHED
and status != AssignmentState.ASSIGNED
):
units_id_to_remove.append(db_id)
for db_id in units_id_to_remove:
self.launched_units.pop(db_id)
num_avail_units = self.max_num_concurrent_units - len(self.launched_units)
num_avail_units = (
len(self.unlaunched_units)
if self.max_num_concurrent_units == 0
else num_avail_units
)
units_id_to_remove = []
for i, item in enumerate(self.unlaunched_units.items()):
db_id, unit = item
if i < num_avail_units:
self.launched_units[unit.db_id] = unit
units_id_to_remove.append(db_id)
yield unit
else:
break
with self.unlaunched_units_access_condition:
for db_id in units_id_to_remove:
self.unlaunched_units.pop(db_id)
time.sleep(UNIT_GENERATOR_WAIT_SECONDS)
if not self.unlaunched_units:
break
def _launch_limited_units(self, url: str) -> None:
"""use units' generator to launch limited number of units according to (max_num_concurrent_units)"""
# Continue launching if we haven't pulled the plug, so long as there are currently
# units to launch, or more may come in the future.
while not self.finished_generators and (
len(self.unlaunched_units) > 0 or not self.assignment_thread_done
):
for unit in self.generate_units():
if unit is None:
break
unit.launch(url)
if self.generator_type == GeneratorType.NONE:
break
self.finished_generators = True
def launch_units(self, url: str) -> None:
"""launch any units registered by this TaskLauncher"""
self.launch_url = url
self.units_thread = threading.Thread(
target=self._launch_limited_units, args=(url,), name="unit-generator"
)
self.units_thread.start()
def launch_evaluation_unit(
self, unit_data: Dict[str, Any], unit_type_index: int
) -> "Unit":
"""Launch a specific evaluation unit, used for quality control"""
assert (
self.launch_url is not None
), "Cannot launch an evaluation unit before launching others"
task_run = self.task_run
task_config = task_run.get_task_config()
assignment_id = self.db.new_assignment(
task_run.task_id,
task_run.db_id,
task_run.requester_id,
task_run.task_type,
task_run.provider_type,
task_run.sandbox,
)
data = InitializationData(unit_data, [{}])
assignment = Assignment.get(self.db, assignment_id)
assignment.write_assignment_data(data)
self.assignments.append(assignment)
unit_id = self.db.new_unit(
task_run.task_id,
task_run.db_id,
task_run.requester_id,
assignment_id,
unit_type_index,
task_config.task_reward,
task_run.provider_type,
task_run.task_type,
task_run.sandbox,
)
evaluation_unit = Unit.get(self.db, unit_id)
evaluation_unit.launch(self.launch_url)
return evaluation_unit
def launch_screening_unit(self, unit_data: Dict[str, Any]) -> "Unit":
"""Launch a screening unit, which should never return to the pool"""
return self.launch_evaluation_unit(unit_data, SCREENING_UNIT_INDEX)
def launch_gold_unit(self, unit_data: Dict[str, Any]) -> "Unit":
"""Launch a screening unit, which should never return to the pool"""
return self.launch_evaluation_unit(unit_data, GOLD_UNIT_INDEX)
def get_assignments_are_all_created(self) -> bool:
return self.assignment_thread_done
def expire_units(self) -> None:
"""Clean up all units on this TaskLauncher"""
self.keep_launching_units = False
self.finished_generators = True
for unit in tqdm(self.units):
try:
unit.expire()
except Exception as e:
logger.exception(
f"Warning: failed to expire unit {unit.db_id}. Stated error: {e}",
exc_info=True,
)
def shutdown(self) -> None:
"""Clean up running threads for generating assignments and units"""
self.assignment_thread_done = True
self.keep_launching_units = False
self.finished_generators = True
if self.assignments_thread is not None:
self.assignments_thread.join()
if self.units_thread is not None:
self.units_thread.join() | 0.684686 | 0.205755 |
from __future__ import absolute_import, division, print_function
from cctbx import crystal
from cctbx import sgtbx
from cctbx import xray
from cctbx.array_family import flex
from cctbx import miller
from mmtbx import max_lik
from mmtbx.max_lik import maxlik
from libtbx.test_utils import approx_equal
from libtbx.utils import format_cpu_times
import time
from cctbx.development import random_structure
from cctbx.eltbx.xray_scattering import wk1995
import random
import math
from six.moves import range
if (1): # fixed random seed to avoid rare failures
random.seed(0)
flex.set_random_seed(0)
def test_1():
tstart = time.time()
fraction_missing = 0.1
d_min = 1.5
# create dummy model
symmetry = crystal.symmetry(unit_cell=(15.67, 25.37, 35.68, 90, 90, 90),
space_group_symbol="P 21 21 21")
structure = xray.structure(crystal_symmetry=symmetry)
for k in range(1000):
scatterer = xray.scatterer(
site = ((1.+k*abs(math.sin(k)))/1000.0,
(1.+k*abs(math.cos(k)))/1000.0,
(1.+ k)/1000.0),
u = abs(math.cos(k))*100./(8.*math.pi**2),
occupancy = 1.0,
scattering_type = "C")
structure.add_scatterer(scatterer)
# partial model
n_keep = int(round(structure.scatterers().size() * (1-fraction_missing)))
partial_structure = xray.structure(special_position_settings=structure)
partial_structure.add_scatterers(structure.scatterers()[:n_keep])
# fcalc (partial model), fobs (fcalc full model)
f_calc = structure.structure_factors(d_min=d_min,
anomalous_flag=False).f_calc()
f_calc_partial = partial_structure.structure_factors(d_min=d_min,
anomalous_flag=False).f_calc()
f_obs = abs(f_calc)
f_calc= abs(f_calc_partial)
d_star_sq = 1./flex.pow2(f_obs.d_spacings().data())
assert approx_equal(flex.max(f_calc.data()),6810.19834824)
assert approx_equal(flex.min(f_calc.data()),0.019589341727)
assert approx_equal(flex.mean(f_calc.data()),76.651506629)
assert approx_equal(flex.max(f_obs.data()),6962.58343229)
assert approx_equal(flex.min(f_obs.data()),0.00111552904935)
assert approx_equal(flex.mean(f_obs.data()),74.5148786464)
assert f_obs.size() == f_calc.size()
# define test set reflections
flags=flex.bool(f_calc_partial.indices().size(), False)
k=0
for i in range(f_calc_partial.indices().size()):
k=k+1
if (k !=10):
flags[i]=False
else:
k=0
flags[i]=True
assert flags.count(True) == 250
assert flags.count(False) == 2258
assert flags.size() == 2508
# *********************************************************TEST = 1
alpha, beta = maxlik.alpha_beta_est_manager(
f_obs = f_obs,
f_calc = f_calc,
free_reflections_per_bin = 1000,
flags = flags,
interpolation = False,
epsilons = f_obs.epsilons().data().as_double()).alpha_beta()
assert alpha.data().size() == beta.data().size()
assert alpha.data().size() == f_obs.size()
assert approx_equal(flex.min(alpha.data()),0.914152454693)
assert approx_equal(flex.max(alpha.data()),0.914152454693)
assert approx_equal(flex.min(beta.data()),818.503411782)
assert approx_equal(flex.max(beta.data()),818.503411782)
# *********************************************************TEST = 2
alpha, beta = maxlik.alpha_beta_est_manager(
f_obs = f_obs,
f_calc = f_calc,
free_reflections_per_bin = 50,
flags = flags,
interpolation = False,
epsilons = f_obs.epsilons().data().as_double()).alpha_beta()
assert alpha.data().size() == beta.data().size()
assert alpha.data().size() == f_obs.size()
assert approx_equal(flex.min(alpha.data()), 0.910350007113)
assert approx_equal(flex.max(alpha.data()), 1.07104387776)
assert approx_equal(flex.min(beta.data()), 21.7374310013)
assert approx_equal(flex.max(beta.data()), 4222.81104745)
# *********************************************************TEST = 3
alpha, beta = maxlik.alpha_beta_calc(
f = f_obs,
n_atoms_absent = 100,
n_atoms_included= 900,
bf_atoms_absent = 25.0,
final_error = 0.0,
absent_atom_type = "C").alpha_beta()
fom = max_lik.fom_and_phase_error(
f_obs = f_obs.data(),
f_model = flex.abs(f_calc.data()),
alpha = alpha.data(),
beta = beta.data(),
epsilons = f_obs.epsilons().data().as_double(),
centric_flags = f_obs.centric_flags().data()).fom()
assert flex.max(fom) <= 1.0
assert flex.min(fom) >= 0.0
assert flex.min(alpha.data()) == flex.max(alpha.data()) == 1.0
assert approx_equal(flex.min(beta.data()),7.964134920)
assert approx_equal(flex.max(beta.data()),13695.1589364)
# *********************************************************TEST = 4
xs = crystal.symmetry((3,4,5), "P 2 2 2")
mi = flex.miller_index(((1,-2,3), (0,0,-4)))
ms = miller.set(xs, mi)
fc = flex.double((1.,2.))
fo = flex.double((1.,2.))
mso = miller.set(xs, mi)
mac = miller.array(ms, fc)
mao = miller.array(ms, fo)
alp = flex.double(2,0.0)
bet = flex.double(2,1e+9)
fom = max_lik.fom_and_phase_error(
f_obs = mao.data(),
f_model = mac.data(),
alpha = alp,
beta = bet,
epsilons = mao.epsilons().data().as_double(),
centric_flags = mao.centric_flags().data()).fom()
assert approx_equal(fom,[0.0, 0.0])
alp = flex.double(2,1.0)
bet = flex.double(2,1e+9)
fom = max_lik.fom_and_phase_error(
f_obs = mao.data(),
f_model = mac.data(),
alpha = alp,
beta = bet,
epsilons = mao.epsilons().data().as_double(),
centric_flags = mao.centric_flags().data()).fom()
assert approx_equal(fom,[0.0, 0.0])
alp = flex.double(2,0.0)
bet = flex.double(2,1e-9)
fom = max_lik.fom_and_phase_error(
f_obs = mao.data(),
f_model = mac.data(),
alpha = alp,
beta = bet,
epsilons = mao.epsilons().data().as_double(),
centric_flags = mao.centric_flags().data()).fom()
assert approx_equal(fom,[0.0, 0.0])
alp = flex.double(2,1.0)
bet = flex.double(2,1e-9)
fom = max_lik.fom_and_phase_error(
f_obs = mao.data(),
f_model = mac.data(),
alpha = alp,
beta = bet,
epsilons = mao.epsilons().data().as_double(),
centric_flags = mao.centric_flags().data()).fom()
assert approx_equal(fom,[1.0, 1.0])
def test_2():
n_sites = 1000
d_min = 2.0
volume_per_atom = 50
fraction_missing = (0.0,)
scale = 5.0
# create dummy model
space_group_info = sgtbx.space_group_info("P212121")
structure = random_structure.xray_structure(
space_group_info = space_group_info,
elements = ["N"]*(n_sites),
volume_per_atom = volume_per_atom,
random_u_iso = False)
structure.scattering_type_registry(table="wk1995")
f_calc = structure.structure_factors(d_min = d_min,
anomalous_flag = False,
algorithm = "direct").f_calc()
f_obs = abs(f_calc)
for fm in fraction_missing:
# partial model
n_keep = int(round(structure.scatterers().size() * (1-fm)))
partial_structure = xray.structure(special_position_settings=structure)
partial_structure.add_scatterers(structure.scatterers()[:n_keep])
# fcalc (partial model), fobs (fcalc full model)
f_calc_partial = partial_structure.structure_factors(d_min=d_min,
anomalous_flag=False,
algorithm = "direct").f_calc()
f_calc= abs(f_calc_partial)
# define test set reflections
flags=flex.bool(f_calc_partial.indices().size(), False)
k=0
for i in range(f_calc_partial.indices().size()):
k=k+1
if (k !=10):
flags[i]=False
else:
k=0
flags[i]=True
# *********************************************************TEST = 1
alpha, beta = maxlik.alpha_beta_est_manager(
f_obs = f_obs,
f_calc = f_calc,
free_reflections_per_bin = f_obs.data().size(),
flags = flags,
interpolation = False,
epsilons = f_obs.epsilons().data().as_double()).alpha_beta()
assert alpha.size() == beta.size()
assert alpha.size() == f_obs.size()
assert approx_equal(flex.min(alpha.data()),1.0, 1.e-2)
assert approx_equal(flex.max(alpha.data()),1.0, 1.e-2)
assert approx_equal(flex.min(beta.data()) ,0.0, 1.e-2)
assert approx_equal(flex.max(beta.data()) ,0.0, 1.e-2)
alpha, beta = maxlik.alpha_beta_est_manager(
f_obs = f_obs,
f_calc = f_calc,
free_reflections_per_bin = f_obs.data().size(),
flags = flags,
interpolation = True,
epsilons = f_obs.epsilons().data().as_double()).alpha_beta()
assert alpha.size() == beta.size()
assert alpha.size() == f_obs.size()
assert approx_equal(flex.min(alpha.data()),1.0, 1.e-2)
assert approx_equal(flex.max(alpha.data()),1.0, 1.e-2)
assert approx_equal(flex.min(beta.data()) ,0.0, 1.e-2)
assert approx_equal(flex.max(beta.data()) ,0.0, 1.e-2)
# *********************************************************TEST = 2
alpha, beta = maxlik.alpha_beta_est_manager(
f_obs = miller.array(miller_set = f_obs,
data = f_obs.data() * scale),
f_calc = f_calc,
free_reflections_per_bin = 200,
flags = flags,
interpolation = False,
epsilons = f_obs.epsilons().data().as_double()).alpha_beta()
assert alpha.size() == beta.size()
assert alpha.size() == f_obs.size()
assert approx_equal(flex.min(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.max(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.min(beta.data()) ,0.0, 1.e-2)
assert approx_equal(flex.max(beta.data()) ,0.0, 1.e-2)
alpha, beta = maxlik.alpha_beta_est_manager(
f_obs = miller.array(miller_set = f_obs,
data = f_obs.data() * scale),
f_calc = f_calc,
free_reflections_per_bin = 200,
flags = flags,
interpolation = True,
epsilons = f_obs.epsilons().data().as_double()).alpha_beta()
assert alpha.size() == beta.size()
assert alpha.size() == f_obs.size()
assert approx_equal(flex.min(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.max(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.min(beta.data()) ,0.0, 1.e-2)
assert approx_equal(flex.max(beta.data()) ,0.0, 1.e-2)
# *********************************************************TEST = 3
alpha, beta = maxlik.alpha_beta_est_manager(
f_obs = miller.array(miller_set = f_obs,
data = f_obs.data() * scale),
f_calc = f_calc,
free_reflections_per_bin = 200,
flags = flex.bool(f_obs.data().size(), True),
interpolation = False,
epsilons = f_obs.epsilons().data().as_double()).alpha_beta()
assert alpha.size() == beta.size()
assert alpha.size() == f_obs.size()
assert approx_equal(flex.min(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.max(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.min(beta.data()) ,0.0, 1.e-2)
assert approx_equal(flex.max(beta.data()) ,0.0, 1.e-2)
alpha, beta = maxlik.alpha_beta_est_manager(
f_obs = miller.array(miller_set = f_obs,
data = f_obs.data() * scale),
f_calc = f_calc,
free_reflections_per_bin = 200,
flags = flex.bool(f_obs.data().size(), True),
interpolation = True,
epsilons = f_obs.epsilons().data().as_double()).alpha_beta()
assert alpha.size() == beta.size()
assert alpha.size() == f_obs.size()
assert approx_equal(flex.min(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.max(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.min(beta.data()) ,0.0, 1.e-2)
assert approx_equal(flex.max(beta.data()) ,0.0, 1.e-2)
# *********************************************************TEST = 4
alpha, beta = maxlik.alpha_beta_est_manager(
f_obs = miller.array(miller_set = f_obs,
data = f_obs.data() * scale),
f_calc = f_calc,
free_reflections_per_bin = 200,
flags = flex.bool(f_obs.data().size(), False),
interpolation = False,
epsilons = f_obs.epsilons().data().as_double()).alpha_beta()
assert alpha.size() == beta.size()
assert alpha.size() == f_obs.size()
assert approx_equal(flex.min(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.max(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.min(beta.data()) ,0.0, 1.e-2)
assert approx_equal(flex.max(beta.data()) ,0.0, 1.e-2)
alpha, beta = maxlik.alpha_beta_est_manager(
f_obs = miller.array(miller_set = f_obs,
data = f_obs.data() * scale),
f_calc = f_calc,
free_reflections_per_bin = 200,
flags = flex.bool(f_obs.data().size(), False),
interpolation = True,
epsilons = f_obs.epsilons().data().as_double()).alpha_beta()
assert alpha.size() == beta.size()
assert alpha.size() == f_obs.size()
assert approx_equal(flex.min(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.max(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.min(beta.data()) ,0.0, 1.e-2)
assert approx_equal(flex.max(beta.data()) ,0.0, 1.e-2)
# *********************************************************TEST = 5
def test_3():
symmetry = crystal.symmetry(unit_cell = (15.67, 25.37, 35.68, 90, 90, 90),
space_group_symbol = "P 21 21 21")
structure = xray.structure(crystal_symmetry = symmetry)
mi = structure.structure_factors(d_min = 1.5,
anomalous_flag = False).f_calc().indices()
# ================================================================= TEST-1
alpha = flex.double(mi.size())
beta = flex.double(mi.size())
d_obs = flex.double(mi.size())
d_calc = flex.double(mi.size())
for i in range(1,mi.size()+1):
d_obs [i-1] = i*1.0
d_calc[i-1] = i*1.0
beta [i-1] = i*500.0
alpha [i-1] = float(i) / float(i + 1)
obj = max_lik.f_star_w_star_mu_nu(f_obs = d_obs,
f_model = d_calc,
alpha = alpha,
beta = beta,
space_group = symmetry.space_group(),
miller_indices = mi)
f_star = obj.f_star()
w_star = obj.w_star()
mu = obj.mu()
nu = obj.nu()
nzero = obj.number_of_f_star_zero()
assert approx_equal(flex.max(f_star) , 2505.77677201 , 1.e-4)
assert approx_equal(flex.min(f_star) , 0.0 , 1.e-4)
assert approx_equal(flex.mean(f_star), 1085.99060715 , 1.e-4)
assert approx_equal(flex.max(w_star) , 1.0 , 1.e-4)
assert approx_equal(flex.min(w_star) , 0.0 , 1.e-4)
assert approx_equal(flex.mean(w_star), 0.01782658613 , 1.e-4)
assert approx_equal(flex.max(mu) , 2.23810354633 , 1.e-4)
assert approx_equal(flex.min(mu) , 0.0 , 1.e-4)
assert approx_equal(flex.mean(mu) , 1.20159615933 , 1.e-4)
assert approx_equal(flex.max(nu) , 0.999107484116, 1.e-4)
assert approx_equal(flex.min(nu) , 0.0 , 1.e-4)
assert approx_equal(flex.mean(nu) , 0.745699513719, 1.e-4)
assert approx_equal(nzero , 501 )
def test_4():
symmetry = crystal.symmetry(unit_cell = (15.67, 25.37, 35.68, 90, 90, 90),
space_group_symbol = "P 21 21 21")
structure = xray.structure(crystal_symmetry = symmetry)
ma = structure.structure_factors(d_min = 1.5,
anomalous_flag = False).f_calc()
mi = ma.indices()
# ================================================================= TEST-1
alpha = flex.double(mi.size())
beta = flex.double(mi.size())
d_obs = flex.double(mi.size())
d_calc = flex.double(mi.size())
# define test set reflections
flags=flex.int(beta.size(), 0)
k=0
for i in range(flags.size()):
k=k+1
if (k !=10):
flags[i]=0
else:
k=0
flags[i]=1
for i in range(1,mi.size()+1):
d_obs [i-1] = i*1.5
d_calc[i-1] = i*1.0
beta [i-1] = i*500.0
alpha [i-1] = float(i) / float(i + 1)
obj = max_lik.fom_and_phase_error(
f_obs = d_obs,
f_model = d_calc,
alpha = alpha,
beta = beta,
epsilons = ma.epsilons().data().as_double(),
centric_flags = ma.centric_flags().data())
per = obj.phase_error()
fom = obj.fom()
assert approx_equal(flex.max(per) , 89.9325000127 , 1.e-4)
assert approx_equal(flex.min(per) , 5.37565067746e-05 , 1.e-4)
assert approx_equal(flex.mean(per), 20.7942460698 , 1.e-4)
assert approx_equal(flex.max(fom) , 0.999999402705 , 1.e-4)
assert approx_equal(flex.min(fom) , 0.000749999859375 , 1.e-4)
assert approx_equal(flex.mean(fom), 0.858269037582 , 1.e-4)
def run():
test_1()
test_2()
test_3()
test_4()
print(format_cpu_times())
if (__name__ == "__main__"):
run() | mmtbx/max_lik/tst_maxlik.py | from __future__ import absolute_import, division, print_function
from cctbx import crystal
from cctbx import sgtbx
from cctbx import xray
from cctbx.array_family import flex
from cctbx import miller
from mmtbx import max_lik
from mmtbx.max_lik import maxlik
from libtbx.test_utils import approx_equal
from libtbx.utils import format_cpu_times
import time
from cctbx.development import random_structure
from cctbx.eltbx.xray_scattering import wk1995
import random
import math
from six.moves import range
if (1): # fixed random seed to avoid rare failures
random.seed(0)
flex.set_random_seed(0)
def test_1():
tstart = time.time()
fraction_missing = 0.1
d_min = 1.5
# create dummy model
symmetry = crystal.symmetry(unit_cell=(15.67, 25.37, 35.68, 90, 90, 90),
space_group_symbol="P 21 21 21")
structure = xray.structure(crystal_symmetry=symmetry)
for k in range(1000):
scatterer = xray.scatterer(
site = ((1.+k*abs(math.sin(k)))/1000.0,
(1.+k*abs(math.cos(k)))/1000.0,
(1.+ k)/1000.0),
u = abs(math.cos(k))*100./(8.*math.pi**2),
occupancy = 1.0,
scattering_type = "C")
structure.add_scatterer(scatterer)
# partial model
n_keep = int(round(structure.scatterers().size() * (1-fraction_missing)))
partial_structure = xray.structure(special_position_settings=structure)
partial_structure.add_scatterers(structure.scatterers()[:n_keep])
# fcalc (partial model), fobs (fcalc full model)
f_calc = structure.structure_factors(d_min=d_min,
anomalous_flag=False).f_calc()
f_calc_partial = partial_structure.structure_factors(d_min=d_min,
anomalous_flag=False).f_calc()
f_obs = abs(f_calc)
f_calc= abs(f_calc_partial)
d_star_sq = 1./flex.pow2(f_obs.d_spacings().data())
assert approx_equal(flex.max(f_calc.data()),6810.19834824)
assert approx_equal(flex.min(f_calc.data()),0.019589341727)
assert approx_equal(flex.mean(f_calc.data()),76.651506629)
assert approx_equal(flex.max(f_obs.data()),6962.58343229)
assert approx_equal(flex.min(f_obs.data()),0.00111552904935)
assert approx_equal(flex.mean(f_obs.data()),74.5148786464)
assert f_obs.size() == f_calc.size()
# define test set reflections
flags=flex.bool(f_calc_partial.indices().size(), False)
k=0
for i in range(f_calc_partial.indices().size()):
k=k+1
if (k !=10):
flags[i]=False
else:
k=0
flags[i]=True
assert flags.count(True) == 250
assert flags.count(False) == 2258
assert flags.size() == 2508
# *********************************************************TEST = 1
alpha, beta = maxlik.alpha_beta_est_manager(
f_obs = f_obs,
f_calc = f_calc,
free_reflections_per_bin = 1000,
flags = flags,
interpolation = False,
epsilons = f_obs.epsilons().data().as_double()).alpha_beta()
assert alpha.data().size() == beta.data().size()
assert alpha.data().size() == f_obs.size()
assert approx_equal(flex.min(alpha.data()),0.914152454693)
assert approx_equal(flex.max(alpha.data()),0.914152454693)
assert approx_equal(flex.min(beta.data()),818.503411782)
assert approx_equal(flex.max(beta.data()),818.503411782)
# *********************************************************TEST = 2
alpha, beta = maxlik.alpha_beta_est_manager(
f_obs = f_obs,
f_calc = f_calc,
free_reflections_per_bin = 50,
flags = flags,
interpolation = False,
epsilons = f_obs.epsilons().data().as_double()).alpha_beta()
assert alpha.data().size() == beta.data().size()
assert alpha.data().size() == f_obs.size()
assert approx_equal(flex.min(alpha.data()), 0.910350007113)
assert approx_equal(flex.max(alpha.data()), 1.07104387776)
assert approx_equal(flex.min(beta.data()), 21.7374310013)
assert approx_equal(flex.max(beta.data()), 4222.81104745)
# *********************************************************TEST = 3
alpha, beta = maxlik.alpha_beta_calc(
f = f_obs,
n_atoms_absent = 100,
n_atoms_included= 900,
bf_atoms_absent = 25.0,
final_error = 0.0,
absent_atom_type = "C").alpha_beta()
fom = max_lik.fom_and_phase_error(
f_obs = f_obs.data(),
f_model = flex.abs(f_calc.data()),
alpha = alpha.data(),
beta = beta.data(),
epsilons = f_obs.epsilons().data().as_double(),
centric_flags = f_obs.centric_flags().data()).fom()
assert flex.max(fom) <= 1.0
assert flex.min(fom) >= 0.0
assert flex.min(alpha.data()) == flex.max(alpha.data()) == 1.0
assert approx_equal(flex.min(beta.data()),7.964134920)
assert approx_equal(flex.max(beta.data()),13695.1589364)
# *********************************************************TEST = 4
xs = crystal.symmetry((3,4,5), "P 2 2 2")
mi = flex.miller_index(((1,-2,3), (0,0,-4)))
ms = miller.set(xs, mi)
fc = flex.double((1.,2.))
fo = flex.double((1.,2.))
mso = miller.set(xs, mi)
mac = miller.array(ms, fc)
mao = miller.array(ms, fo)
alp = flex.double(2,0.0)
bet = flex.double(2,1e+9)
fom = max_lik.fom_and_phase_error(
f_obs = mao.data(),
f_model = mac.data(),
alpha = alp,
beta = bet,
epsilons = mao.epsilons().data().as_double(),
centric_flags = mao.centric_flags().data()).fom()
assert approx_equal(fom,[0.0, 0.0])
alp = flex.double(2,1.0)
bet = flex.double(2,1e+9)
fom = max_lik.fom_and_phase_error(
f_obs = mao.data(),
f_model = mac.data(),
alpha = alp,
beta = bet,
epsilons = mao.epsilons().data().as_double(),
centric_flags = mao.centric_flags().data()).fom()
assert approx_equal(fom,[0.0, 0.0])
alp = flex.double(2,0.0)
bet = flex.double(2,1e-9)
fom = max_lik.fom_and_phase_error(
f_obs = mao.data(),
f_model = mac.data(),
alpha = alp,
beta = bet,
epsilons = mao.epsilons().data().as_double(),
centric_flags = mao.centric_flags().data()).fom()
assert approx_equal(fom,[0.0, 0.0])
alp = flex.double(2,1.0)
bet = flex.double(2,1e-9)
fom = max_lik.fom_and_phase_error(
f_obs = mao.data(),
f_model = mac.data(),
alpha = alp,
beta = bet,
epsilons = mao.epsilons().data().as_double(),
centric_flags = mao.centric_flags().data()).fom()
assert approx_equal(fom,[1.0, 1.0])
def test_2():
n_sites = 1000
d_min = 2.0
volume_per_atom = 50
fraction_missing = (0.0,)
scale = 5.0
# create dummy model
space_group_info = sgtbx.space_group_info("P212121")
structure = random_structure.xray_structure(
space_group_info = space_group_info,
elements = ["N"]*(n_sites),
volume_per_atom = volume_per_atom,
random_u_iso = False)
structure.scattering_type_registry(table="wk1995")
f_calc = structure.structure_factors(d_min = d_min,
anomalous_flag = False,
algorithm = "direct").f_calc()
f_obs = abs(f_calc)
for fm in fraction_missing:
# partial model
n_keep = int(round(structure.scatterers().size() * (1-fm)))
partial_structure = xray.structure(special_position_settings=structure)
partial_structure.add_scatterers(structure.scatterers()[:n_keep])
# fcalc (partial model), fobs (fcalc full model)
f_calc_partial = partial_structure.structure_factors(d_min=d_min,
anomalous_flag=False,
algorithm = "direct").f_calc()
f_calc= abs(f_calc_partial)
# define test set reflections
flags=flex.bool(f_calc_partial.indices().size(), False)
k=0
for i in range(f_calc_partial.indices().size()):
k=k+1
if (k !=10):
flags[i]=False
else:
k=0
flags[i]=True
# *********************************************************TEST = 1
alpha, beta = maxlik.alpha_beta_est_manager(
f_obs = f_obs,
f_calc = f_calc,
free_reflections_per_bin = f_obs.data().size(),
flags = flags,
interpolation = False,
epsilons = f_obs.epsilons().data().as_double()).alpha_beta()
assert alpha.size() == beta.size()
assert alpha.size() == f_obs.size()
assert approx_equal(flex.min(alpha.data()),1.0, 1.e-2)
assert approx_equal(flex.max(alpha.data()),1.0, 1.e-2)
assert approx_equal(flex.min(beta.data()) ,0.0, 1.e-2)
assert approx_equal(flex.max(beta.data()) ,0.0, 1.e-2)
alpha, beta = maxlik.alpha_beta_est_manager(
f_obs = f_obs,
f_calc = f_calc,
free_reflections_per_bin = f_obs.data().size(),
flags = flags,
interpolation = True,
epsilons = f_obs.epsilons().data().as_double()).alpha_beta()
assert alpha.size() == beta.size()
assert alpha.size() == f_obs.size()
assert approx_equal(flex.min(alpha.data()),1.0, 1.e-2)
assert approx_equal(flex.max(alpha.data()),1.0, 1.e-2)
assert approx_equal(flex.min(beta.data()) ,0.0, 1.e-2)
assert approx_equal(flex.max(beta.data()) ,0.0, 1.e-2)
# *********************************************************TEST = 2
alpha, beta = maxlik.alpha_beta_est_manager(
f_obs = miller.array(miller_set = f_obs,
data = f_obs.data() * scale),
f_calc = f_calc,
free_reflections_per_bin = 200,
flags = flags,
interpolation = False,
epsilons = f_obs.epsilons().data().as_double()).alpha_beta()
assert alpha.size() == beta.size()
assert alpha.size() == f_obs.size()
assert approx_equal(flex.min(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.max(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.min(beta.data()) ,0.0, 1.e-2)
assert approx_equal(flex.max(beta.data()) ,0.0, 1.e-2)
alpha, beta = maxlik.alpha_beta_est_manager(
f_obs = miller.array(miller_set = f_obs,
data = f_obs.data() * scale),
f_calc = f_calc,
free_reflections_per_bin = 200,
flags = flags,
interpolation = True,
epsilons = f_obs.epsilons().data().as_double()).alpha_beta()
assert alpha.size() == beta.size()
assert alpha.size() == f_obs.size()
assert approx_equal(flex.min(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.max(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.min(beta.data()) ,0.0, 1.e-2)
assert approx_equal(flex.max(beta.data()) ,0.0, 1.e-2)
# *********************************************************TEST = 3
alpha, beta = maxlik.alpha_beta_est_manager(
f_obs = miller.array(miller_set = f_obs,
data = f_obs.data() * scale),
f_calc = f_calc,
free_reflections_per_bin = 200,
flags = flex.bool(f_obs.data().size(), True),
interpolation = False,
epsilons = f_obs.epsilons().data().as_double()).alpha_beta()
assert alpha.size() == beta.size()
assert alpha.size() == f_obs.size()
assert approx_equal(flex.min(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.max(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.min(beta.data()) ,0.0, 1.e-2)
assert approx_equal(flex.max(beta.data()) ,0.0, 1.e-2)
alpha, beta = maxlik.alpha_beta_est_manager(
f_obs = miller.array(miller_set = f_obs,
data = f_obs.data() * scale),
f_calc = f_calc,
free_reflections_per_bin = 200,
flags = flex.bool(f_obs.data().size(), True),
interpolation = True,
epsilons = f_obs.epsilons().data().as_double()).alpha_beta()
assert alpha.size() == beta.size()
assert alpha.size() == f_obs.size()
assert approx_equal(flex.min(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.max(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.min(beta.data()) ,0.0, 1.e-2)
assert approx_equal(flex.max(beta.data()) ,0.0, 1.e-2)
# *********************************************************TEST = 4
alpha, beta = maxlik.alpha_beta_est_manager(
f_obs = miller.array(miller_set = f_obs,
data = f_obs.data() * scale),
f_calc = f_calc,
free_reflections_per_bin = 200,
flags = flex.bool(f_obs.data().size(), False),
interpolation = False,
epsilons = f_obs.epsilons().data().as_double()).alpha_beta()
assert alpha.size() == beta.size()
assert alpha.size() == f_obs.size()
assert approx_equal(flex.min(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.max(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.min(beta.data()) ,0.0, 1.e-2)
assert approx_equal(flex.max(beta.data()) ,0.0, 1.e-2)
alpha, beta = maxlik.alpha_beta_est_manager(
f_obs = miller.array(miller_set = f_obs,
data = f_obs.data() * scale),
f_calc = f_calc,
free_reflections_per_bin = 200,
flags = flex.bool(f_obs.data().size(), False),
interpolation = True,
epsilons = f_obs.epsilons().data().as_double()).alpha_beta()
assert alpha.size() == beta.size()
assert alpha.size() == f_obs.size()
assert approx_equal(flex.min(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.max(alpha.data()),1.0/scale, 1.e-2)
assert approx_equal(flex.min(beta.data()) ,0.0, 1.e-2)
assert approx_equal(flex.max(beta.data()) ,0.0, 1.e-2)
# *********************************************************TEST = 5
def test_3():
symmetry = crystal.symmetry(unit_cell = (15.67, 25.37, 35.68, 90, 90, 90),
space_group_symbol = "P 21 21 21")
structure = xray.structure(crystal_symmetry = symmetry)
mi = structure.structure_factors(d_min = 1.5,
anomalous_flag = False).f_calc().indices()
# ================================================================= TEST-1
alpha = flex.double(mi.size())
beta = flex.double(mi.size())
d_obs = flex.double(mi.size())
d_calc = flex.double(mi.size())
for i in range(1,mi.size()+1):
d_obs [i-1] = i*1.0
d_calc[i-1] = i*1.0
beta [i-1] = i*500.0
alpha [i-1] = float(i) / float(i + 1)
obj = max_lik.f_star_w_star_mu_nu(f_obs = d_obs,
f_model = d_calc,
alpha = alpha,
beta = beta,
space_group = symmetry.space_group(),
miller_indices = mi)
f_star = obj.f_star()
w_star = obj.w_star()
mu = obj.mu()
nu = obj.nu()
nzero = obj.number_of_f_star_zero()
assert approx_equal(flex.max(f_star) , 2505.77677201 , 1.e-4)
assert approx_equal(flex.min(f_star) , 0.0 , 1.e-4)
assert approx_equal(flex.mean(f_star), 1085.99060715 , 1.e-4)
assert approx_equal(flex.max(w_star) , 1.0 , 1.e-4)
assert approx_equal(flex.min(w_star) , 0.0 , 1.e-4)
assert approx_equal(flex.mean(w_star), 0.01782658613 , 1.e-4)
assert approx_equal(flex.max(mu) , 2.23810354633 , 1.e-4)
assert approx_equal(flex.min(mu) , 0.0 , 1.e-4)
assert approx_equal(flex.mean(mu) , 1.20159615933 , 1.e-4)
assert approx_equal(flex.max(nu) , 0.999107484116, 1.e-4)
assert approx_equal(flex.min(nu) , 0.0 , 1.e-4)
assert approx_equal(flex.mean(nu) , 0.745699513719, 1.e-4)
assert approx_equal(nzero , 501 )
def test_4():
symmetry = crystal.symmetry(unit_cell = (15.67, 25.37, 35.68, 90, 90, 90),
space_group_symbol = "P 21 21 21")
structure = xray.structure(crystal_symmetry = symmetry)
ma = structure.structure_factors(d_min = 1.5,
anomalous_flag = False).f_calc()
mi = ma.indices()
# ================================================================= TEST-1
alpha = flex.double(mi.size())
beta = flex.double(mi.size())
d_obs = flex.double(mi.size())
d_calc = flex.double(mi.size())
# define test set reflections
flags=flex.int(beta.size(), 0)
k=0
for i in range(flags.size()):
k=k+1
if (k !=10):
flags[i]=0
else:
k=0
flags[i]=1
for i in range(1,mi.size()+1):
d_obs [i-1] = i*1.5
d_calc[i-1] = i*1.0
beta [i-1] = i*500.0
alpha [i-1] = float(i) / float(i + 1)
obj = max_lik.fom_and_phase_error(
f_obs = d_obs,
f_model = d_calc,
alpha = alpha,
beta = beta,
epsilons = ma.epsilons().data().as_double(),
centric_flags = ma.centric_flags().data())
per = obj.phase_error()
fom = obj.fom()
assert approx_equal(flex.max(per) , 89.9325000127 , 1.e-4)
assert approx_equal(flex.min(per) , 5.37565067746e-05 , 1.e-4)
assert approx_equal(flex.mean(per), 20.7942460698 , 1.e-4)
assert approx_equal(flex.max(fom) , 0.999999402705 , 1.e-4)
assert approx_equal(flex.min(fom) , 0.000749999859375 , 1.e-4)
assert approx_equal(flex.mean(fom), 0.858269037582 , 1.e-4)
def run():
test_1()
test_2()
test_3()
test_4()
print(format_cpu_times())
if (__name__ == "__main__"):
run() | 0.544559 | 0.425247 |
import arcpy
import sys
import pyodbc
import datetime
# field names
X_fld = 'X'
Y_fld = 'Y'
PRECINCT_ID_fld = 'PRECINCT_ID'
COUNTY_ID_fld = 'COUNTY_ID'
RESIDENCE_ID_fld = 'RESIDENCE_ID'
VistaID_fld = 'VistaID'
try:
db = sys.argv[1]
db_username = sys.argv[2]
db_password = sys.argv[3]
db_server = sys.argv[4]
county_num = sys.argv[5]
res_id = sys.argv[6]
except IndexError:
db = raw_input('Database Instance (e.g. test, live, dev, etc..): ')
db_username = raw_input('Database Username: ')
db_password = <PASSWORD>_input('Database Password: ')
db_server = raw_input('Database Server:Port/ServiceName: ')
county_num = raw_input('County Number: ')
res_id = raw_input('Residence ID: ')
log_file_location = r'\\<machine name>\v1\Apps\VISTA\Working Directory\Services\ResidencePrecinctUpdate' + r'\\' + county_num+ '_' + db + '_' + datetime.datetime.now().strftime("%Y%m%d") + '.log'
ResCounty_file_location = r'\\<machine name>\v1\Apps\VISTA\Working Directory\Services\ResidencePrecinctUpdate' + r'\\' + county_num + '_' + db + '_Residence-County_Issues' + '_' + datetime.datetime.now().strftime("%Y%m%d") + '.log'
with open(log_file_location, "a+") as log_file:
log_file.write("Beginning process - " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " \n")
counties = r'SGID10.sde\SGID10.BOUNDARIES.Counties'
vista_ballot_areas = r'SGID10.sde\SGID10.POLITICAL.VistaBallotAreas'
precincts_table = r'vista_' + db + '.odc\GV_VISTA.PRECINCTS'
residences_table = r'vista_' + db + '.odc\GV_VISTA.RESIDENCES'
print('Running GIS update process.')
log_file.write('Running GIS update process. \n')
#print('Making temporary Residences table view.')
log_file.write('Making temporary Residences table view. \n')
query = '{} = {}'.format(COUNTY_ID_fld, county_num)
resquery = query + ' AND ' + '{} IN ({})'.format(RESIDENCE_ID_fld, res_id)
xy_table = arcpy.MakeQueryTable_management([residences_table], 'xy_table', 'USE_KEY_FIELDS', 'GV_VISTA.RESIDENCES.RESIDENCE_ID', where_clause=resquery)
log_file.write('Query: ' + resquery + " \n")
#print('Setting precinct name to id')
log_file.write('Setting precinct name to id \n')
precinct_table = arcpy.MakeQueryTable_management([precincts_table], 'precinct_table', 'USE_KEY_FIELDS', 'GV_VISTA.PRECINCTS.PRECINCT_ID', where_clause=query)
precinct_name_to_id = {}
with arcpy.da.SearchCursor(precinct_table, [PRECINCT_ID_fld, 'PRECINCT']) as scur:
for row in scur:
if row[0] is not None:
if row[0] > 0:
log_file.write(' Setting ' + str(row[1]) + ' to ' + str(row[0]) + ' \n')
precinct_name_to_id[row[1]] = row[0]
else:
log_file.write(' Cannot set ' + str(row[0]) + ' to ' + str(row[0]) + ' \n')
else:
log_file.write(' Setting NONE to ' + str(row[0]) + ' \n')
print('Creating the [XY] layer')
log_file.write('Creating the [XY] layer \n')
xy_layer = arcpy.MakeXYEventLayer_management(xy_table, X_fld, Y_fld, 'xy_layer', arcpy.SpatialReference(26912))
print('Setting GIS identity')
log_file.write('Setting GIS identity for counties. \n')
identityCounties = arcpy.Identity_analysis(xy_layer, counties, 'in_memory\identity_counties')
i = 0
print("Validating Residnce and County IDs.")
log_file.write('Validating Residnce and County IDs. \n')
with open(ResCounty_file_location, "a+") as ResCounty_file:
with arcpy.da.SearchCursor(identityCounties, ['COUNTYNBR', COUNTY_ID_fld, RESIDENCE_ID_fld]) as cur:
for row in cur:
if row[0] is not None:
resID = str(row[2])
countyID = str(row[0])
if countyID.startswith('0'):
countyID = countyID.replace('0','')
if countyID != '':
gisCountyID = str(row[1]).replace('.0','')
if countyID != gisCountyID:
print('Residence ID [' + resID + '] belongs to County ['+ countyID + ']' + ' - GIS County [' + gisCountyID + '].')
log_file.write('Residence ID [' + resID + '] belongs to County ['+ countyID + '] \n')
ResCounty_file.write('Residence ID [' + resID + '] belongs to County ['+ countyID + '] \n')
i = i + 1
else:
print('Residence ID [' + resID + '] has invalid X and/or Y coordinates.')
log_file.write('Residence ID [' + resID + '] has invalid X and/or Y coordinates. \n')
ResCounty_file.write('Residence ID [' + resID + '] has invalid X and/or Y coordinates. \n')
i = i + 1
ResCounty_file.close()
if i == 0:
print('Setting GIS identity')
log_file.write('Setting GIS identity for vista ballot areas. \n')
identity = arcpy.Identity_analysis(xy_layer, vista_ballot_areas, 'in_memory\identity')
print('Building GIS Residence to Precinct Mapping table.')
log_file.write('Building GIS Residence to Precinct Mapping table. \n')
res_to_precinct_dict = {}
with arcpy.da.SearchCursor(identity, [RESIDENCE_ID_fld, VistaID_fld]) as scur:
for row in scur:
if row[1] is not None:
if str(row[1]) <> '':
log_file.write(' Mapping ' + str(row[0]) + ' to ' + str(row[1]) + ' \n')
res_to_precinct_dict[row[0]] = row[1]
else:
log_file.write(' Cannot map ' + str(row[0]) + ' to ' + str(row[1]) + ' \n')
else:
log_file.write(' Mapping NONE to ' + str(row[0]) + ' \n')
print('Updating Precinct IDs')
log_file.write('Updating VISTA Database \n')
with arcpy.da.SearchCursor(xy_table, [RESIDENCE_ID_fld]) as cur:
connection = pyodbc.connect('Driver={Microsoft ODBC for Oracle};UID=' + db_username + ';PWD=' + db_password + ';SERVER='+ db_server)
cursor = connection.cursor()
for row in cur:
log_file.write(' \n')
if row[0] is not None:
log_file.write('Residence ID: ' + str(row[0]) + ' \n')
if row[0] > 0:
res_statement = """
SELECT PRECINCT_ID, COUNTY_ID
FROM GV_VISTA.RESIDENCES
WHERE RESIDENCE_ID = {}
AND COUNTY_ID = {}
""".format(row[0],county_num)
log_file.write(' Query: ' + str(res_statement) + ' \n')
res_rows = cursor.execute(res_statement).fetchone()
if res_rows:
if str(county_num) == str(res_rows.COUNTY_ID):
log_file.write(' Updating Precinct ID: \n')
log_file.write(' Old: ' + str(res_rows.PRECINCT_ID) + ' \n')
try:
new_precinct_id = precinct_name_to_id[res_to_precinct_dict[row[0]]]
except KeyError as error:
print('ERROR: issue with res id: {}. error: {}'.format(row[0], error) + ' \n')
log_file.write('ERROR: issue with res id: {}. \n Message: {}'.format(row[0], error) + ' \n')
continue
log_file.write(' New: ' + str(new_precinct_id) + ' \n')
statement = """
UPDATE GV_VISTA.RESIDENCES
SET PRECINCT_ID = {}
WHERE RESIDENCE_ID = {}
""".format(new_precinct_id, row[0])
log_file.write(' Query: ' + str(statement) + ' \n')
cursor.execute(statement)
connection.commit()
log_file.write(' Commit Successful \n')
log_file.write(' Recording only changes to repository \n')
if res_rows.PRECINCT_ID != new_precinct_id:
evr_connection = pyodbc.connect('Driver={Microsoft ODBC for Oracle};UID=GV_EVR;PWD=<password>;SERVER=<server>:1521/tgvdv')
evr_cursor = evr_connection.cursor()
evr_statement = """INSERT INTO GV_EVR.RESIDENCE_CHANGE_DETAILS
(KEY,TABLE_NAME,FIELD_NAME,TRIGGERED_ACTION,FROM_VALUE,TO_VALUE,CHANGED_BY,RESIDENCE_ID)
VALUES({},'RESIDENCES','PRECINCT_ID','INSERT',{},{},'VISTA.Services.Residence.PrecinctUpdate',{})""".format(row[0],res_rows.PRECINCT_ID,new_precinct_id,row[0])
evr_cursor.execute(evr_statement)
log_file.write(' Query: ' + str(statement) + ' \n')
evr_connection.commit()
log_file.write(' Commit Successful. \n')
else:
print('Residence ID [' + str(row[0]) + '] belongs to County ['+ str(res_rows.COUNTY_ID) + ']')
log_file.write('Residence ID [' + str(row[0]) + '] belongs to County ['+ str(res_rows.COUNTY_ID) + '] \n')
with open(ResCounty_file_location, "a+") as ResCounty_file2:
ResCounty_file2.write('Residence ID [' + str(row[0]) + '] belongs to County ['+ str(res_rows.COUNTY_ID) + '] \n')
ResCounty_file2.close()
else:
print('Residence ID not found in VISTA.')
log_file.write('Residence ID not found in VISTA. \n')
else:
print('Residence ID not found in VISTA. \n')
log_file.write('Residence ID not found in VISTA. \n')
else:
print("No rows to update \n")
log_file.write("No rows to update \n")
else:
log_file.write("County and residence validation issues. \n")
log_file.write("Ending process - " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") +" \n")
log_file.close()
print('*** Precinct IDs updated for this batch. ***')
print(' ')
print(' ') | scripts/DJScript.py | import arcpy
import sys
import pyodbc
import datetime
# field names
X_fld = 'X'
Y_fld = 'Y'
PRECINCT_ID_fld = 'PRECINCT_ID'
COUNTY_ID_fld = 'COUNTY_ID'
RESIDENCE_ID_fld = 'RESIDENCE_ID'
VistaID_fld = 'VistaID'
try:
db = sys.argv[1]
db_username = sys.argv[2]
db_password = sys.argv[3]
db_server = sys.argv[4]
county_num = sys.argv[5]
res_id = sys.argv[6]
except IndexError:
db = raw_input('Database Instance (e.g. test, live, dev, etc..): ')
db_username = raw_input('Database Username: ')
db_password = <PASSWORD>_input('Database Password: ')
db_server = raw_input('Database Server:Port/ServiceName: ')
county_num = raw_input('County Number: ')
res_id = raw_input('Residence ID: ')
log_file_location = r'\\<machine name>\v1\Apps\VISTA\Working Directory\Services\ResidencePrecinctUpdate' + r'\\' + county_num+ '_' + db + '_' + datetime.datetime.now().strftime("%Y%m%d") + '.log'
ResCounty_file_location = r'\\<machine name>\v1\Apps\VISTA\Working Directory\Services\ResidencePrecinctUpdate' + r'\\' + county_num + '_' + db + '_Residence-County_Issues' + '_' + datetime.datetime.now().strftime("%Y%m%d") + '.log'
with open(log_file_location, "a+") as log_file:
log_file.write("Beginning process - " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " \n")
counties = r'SGID10.sde\SGID10.BOUNDARIES.Counties'
vista_ballot_areas = r'SGID10.sde\SGID10.POLITICAL.VistaBallotAreas'
precincts_table = r'vista_' + db + '.odc\GV_VISTA.PRECINCTS'
residences_table = r'vista_' + db + '.odc\GV_VISTA.RESIDENCES'
print('Running GIS update process.')
log_file.write('Running GIS update process. \n')
#print('Making temporary Residences table view.')
log_file.write('Making temporary Residences table view. \n')
query = '{} = {}'.format(COUNTY_ID_fld, county_num)
resquery = query + ' AND ' + '{} IN ({})'.format(RESIDENCE_ID_fld, res_id)
xy_table = arcpy.MakeQueryTable_management([residences_table], 'xy_table', 'USE_KEY_FIELDS', 'GV_VISTA.RESIDENCES.RESIDENCE_ID', where_clause=resquery)
log_file.write('Query: ' + resquery + " \n")
#print('Setting precinct name to id')
log_file.write('Setting precinct name to id \n')
precinct_table = arcpy.MakeQueryTable_management([precincts_table], 'precinct_table', 'USE_KEY_FIELDS', 'GV_VISTA.PRECINCTS.PRECINCT_ID', where_clause=query)
precinct_name_to_id = {}
with arcpy.da.SearchCursor(precinct_table, [PRECINCT_ID_fld, 'PRECINCT']) as scur:
for row in scur:
if row[0] is not None:
if row[0] > 0:
log_file.write(' Setting ' + str(row[1]) + ' to ' + str(row[0]) + ' \n')
precinct_name_to_id[row[1]] = row[0]
else:
log_file.write(' Cannot set ' + str(row[0]) + ' to ' + str(row[0]) + ' \n')
else:
log_file.write(' Setting NONE to ' + str(row[0]) + ' \n')
print('Creating the [XY] layer')
log_file.write('Creating the [XY] layer \n')
xy_layer = arcpy.MakeXYEventLayer_management(xy_table, X_fld, Y_fld, 'xy_layer', arcpy.SpatialReference(26912))
print('Setting GIS identity')
log_file.write('Setting GIS identity for counties. \n')
identityCounties = arcpy.Identity_analysis(xy_layer, counties, 'in_memory\identity_counties')
i = 0
print("Validating Residnce and County IDs.")
log_file.write('Validating Residnce and County IDs. \n')
with open(ResCounty_file_location, "a+") as ResCounty_file:
with arcpy.da.SearchCursor(identityCounties, ['COUNTYNBR', COUNTY_ID_fld, RESIDENCE_ID_fld]) as cur:
for row in cur:
if row[0] is not None:
resID = str(row[2])
countyID = str(row[0])
if countyID.startswith('0'):
countyID = countyID.replace('0','')
if countyID != '':
gisCountyID = str(row[1]).replace('.0','')
if countyID != gisCountyID:
print('Residence ID [' + resID + '] belongs to County ['+ countyID + ']' + ' - GIS County [' + gisCountyID + '].')
log_file.write('Residence ID [' + resID + '] belongs to County ['+ countyID + '] \n')
ResCounty_file.write('Residence ID [' + resID + '] belongs to County ['+ countyID + '] \n')
i = i + 1
else:
print('Residence ID [' + resID + '] has invalid X and/or Y coordinates.')
log_file.write('Residence ID [' + resID + '] has invalid X and/or Y coordinates. \n')
ResCounty_file.write('Residence ID [' + resID + '] has invalid X and/or Y coordinates. \n')
i = i + 1
ResCounty_file.close()
if i == 0:
print('Setting GIS identity')
log_file.write('Setting GIS identity for vista ballot areas. \n')
identity = arcpy.Identity_analysis(xy_layer, vista_ballot_areas, 'in_memory\identity')
print('Building GIS Residence to Precinct Mapping table.')
log_file.write('Building GIS Residence to Precinct Mapping table. \n')
res_to_precinct_dict = {}
with arcpy.da.SearchCursor(identity, [RESIDENCE_ID_fld, VistaID_fld]) as scur:
for row in scur:
if row[1] is not None:
if str(row[1]) <> '':
log_file.write(' Mapping ' + str(row[0]) + ' to ' + str(row[1]) + ' \n')
res_to_precinct_dict[row[0]] = row[1]
else:
log_file.write(' Cannot map ' + str(row[0]) + ' to ' + str(row[1]) + ' \n')
else:
log_file.write(' Mapping NONE to ' + str(row[0]) + ' \n')
print('Updating Precinct IDs')
log_file.write('Updating VISTA Database \n')
with arcpy.da.SearchCursor(xy_table, [RESIDENCE_ID_fld]) as cur:
connection = pyodbc.connect('Driver={Microsoft ODBC for Oracle};UID=' + db_username + ';PWD=' + db_password + ';SERVER='+ db_server)
cursor = connection.cursor()
for row in cur:
log_file.write(' \n')
if row[0] is not None:
log_file.write('Residence ID: ' + str(row[0]) + ' \n')
if row[0] > 0:
res_statement = """
SELECT PRECINCT_ID, COUNTY_ID
FROM GV_VISTA.RESIDENCES
WHERE RESIDENCE_ID = {}
AND COUNTY_ID = {}
""".format(row[0],county_num)
log_file.write(' Query: ' + str(res_statement) + ' \n')
res_rows = cursor.execute(res_statement).fetchone()
if res_rows:
if str(county_num) == str(res_rows.COUNTY_ID):
log_file.write(' Updating Precinct ID: \n')
log_file.write(' Old: ' + str(res_rows.PRECINCT_ID) + ' \n')
try:
new_precinct_id = precinct_name_to_id[res_to_precinct_dict[row[0]]]
except KeyError as error:
print('ERROR: issue with res id: {}. error: {}'.format(row[0], error) + ' \n')
log_file.write('ERROR: issue with res id: {}. \n Message: {}'.format(row[0], error) + ' \n')
continue
log_file.write(' New: ' + str(new_precinct_id) + ' \n')
statement = """
UPDATE GV_VISTA.RESIDENCES
SET PRECINCT_ID = {}
WHERE RESIDENCE_ID = {}
""".format(new_precinct_id, row[0])
log_file.write(' Query: ' + str(statement) + ' \n')
cursor.execute(statement)
connection.commit()
log_file.write(' Commit Successful \n')
log_file.write(' Recording only changes to repository \n')
if res_rows.PRECINCT_ID != new_precinct_id:
evr_connection = pyodbc.connect('Driver={Microsoft ODBC for Oracle};UID=GV_EVR;PWD=<password>;SERVER=<server>:1521/tgvdv')
evr_cursor = evr_connection.cursor()
evr_statement = """INSERT INTO GV_EVR.RESIDENCE_CHANGE_DETAILS
(KEY,TABLE_NAME,FIELD_NAME,TRIGGERED_ACTION,FROM_VALUE,TO_VALUE,CHANGED_BY,RESIDENCE_ID)
VALUES({},'RESIDENCES','PRECINCT_ID','INSERT',{},{},'VISTA.Services.Residence.PrecinctUpdate',{})""".format(row[0],res_rows.PRECINCT_ID,new_precinct_id,row[0])
evr_cursor.execute(evr_statement)
log_file.write(' Query: ' + str(statement) + ' \n')
evr_connection.commit()
log_file.write(' Commit Successful. \n')
else:
print('Residence ID [' + str(row[0]) + '] belongs to County ['+ str(res_rows.COUNTY_ID) + ']')
log_file.write('Residence ID [' + str(row[0]) + '] belongs to County ['+ str(res_rows.COUNTY_ID) + '] \n')
with open(ResCounty_file_location, "a+") as ResCounty_file2:
ResCounty_file2.write('Residence ID [' + str(row[0]) + '] belongs to County ['+ str(res_rows.COUNTY_ID) + '] \n')
ResCounty_file2.close()
else:
print('Residence ID not found in VISTA.')
log_file.write('Residence ID not found in VISTA. \n')
else:
print('Residence ID not found in VISTA. \n')
log_file.write('Residence ID not found in VISTA. \n')
else:
print("No rows to update \n")
log_file.write("No rows to update \n")
else:
log_file.write("County and residence validation issues. \n")
log_file.write("Ending process - " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") +" \n")
log_file.close()
print('*** Precinct IDs updated for this batch. ***')
print(' ')
print(' ') | 0.091489 | 0.090053 |
import llnl.util.tty as tty
class Libsigsegv(AutotoolsPackage, GNUMirrorPackage):
"""GNU libsigsegv is a library for handling page faults in user mode."""
homepage = "https://www.gnu.org/software/libsigsegv/"
gnu_mirror_path = "libsigsegv/libsigsegv-2.12.tar.gz"
version('2.12', sha256='3ae1af359eebaa4ffc5896a1aee3568c052c99879316a1ab57f8fe1789c390b6')
version('2.11', sha256='dd7c2eb2ef6c47189406d562c1dc0f96f2fc808036834d596075d58377e37a18')
version('2.10', sha256='8460a4a3dd4954c3d96d7a4f5dd5bc4d9b76f5754196aa245287553b26d2199a')
patch('patch.new_config_guess', when='@2.10')
test_requires_compiler = True
def configure_args(self):
return ['--enable-shared']
extra_install_tests = 'tests/.libs'
@run_after('install')
def setup_build_tests(self):
"""Copy the build test files after the package is installed to an
install test subdirectory for use during `spack test run`."""
self.cache_extra_test_sources(self.extra_install_tests)
def _run_smoke_tests(self):
"""Build and run the added smoke (install) test."""
data_dir = self.test_suite.current_test_data_dir
prog = 'smoke_test'
src = data_dir.join('{0}.c'.format(prog))
options = [
'-I{0}'.format(self.prefix.include),
src,
'-o',
prog,
'-L{0}'.format(self.prefix.lib),
'-lsigsegv',
'{0}{1}'.format(self.compiler.cc_rpath_arg, self.prefix.lib)]
reason = 'test: checking ability to link to the library'
self.run_test('cc', options, [], installed=False, purpose=reason)
# Now run the program and confirm the output matches expectations
expected = get_escaped_text_output(data_dir.join('smoke_test.out'))
reason = 'test: checking ability to use the library'
self.run_test(prog, [], expected, purpose=reason)
def _run_build_tests(self):
"""Run selected build tests."""
passed = 'Test passed'
checks = {
'sigsegv1': [passed],
'sigsegv2': [passed],
'sigsegv3': ['caught', passed],
'stackoverflow1': ['recursion', 'Stack overflow', passed],
'stackoverflow2': ['recursion', 'overflow', 'violation', passed],
}
for exe, expected in checks.items():
reason = 'test: checking {0} output'.format(exe)
self.run_test(exe, [], expected, installed=True, purpose=reason,
skip_missing=True)
def test(self):
"""Perform smoke tests on the installed package."""
tty.debug('Expected results currently based on simple {0} builds'
.format(self.name))
if not self.spec.satisfies('@2.10:2.12'):
tty.debug('Expected results have not been confirmed for {0} {1}'
.format(self.name, self.spec.version))
# Run the simple built-in smoke test
self._run_smoke_tests()
# Run test programs pulled from the build
self._run_build_tests() | var/spack/repos/builtin/packages/libsigsegv/package.py |
import llnl.util.tty as tty
class Libsigsegv(AutotoolsPackage, GNUMirrorPackage):
"""GNU libsigsegv is a library for handling page faults in user mode."""
homepage = "https://www.gnu.org/software/libsigsegv/"
gnu_mirror_path = "libsigsegv/libsigsegv-2.12.tar.gz"
version('2.12', sha256='3ae1af359eebaa4ffc5896a1aee3568c052c99879316a1ab57f8fe1789c390b6')
version('2.11', sha256='dd7c2eb2ef6c47189406d562c1dc0f96f2fc808036834d596075d58377e37a18')
version('2.10', sha256='8460a4a3dd4954c3d96d7a4f5dd5bc4d9b76f5754196aa245287553b26d2199a')
patch('patch.new_config_guess', when='@2.10')
test_requires_compiler = True
def configure_args(self):
return ['--enable-shared']
extra_install_tests = 'tests/.libs'
@run_after('install')
def setup_build_tests(self):
"""Copy the build test files after the package is installed to an
install test subdirectory for use during `spack test run`."""
self.cache_extra_test_sources(self.extra_install_tests)
def _run_smoke_tests(self):
"""Build and run the added smoke (install) test."""
data_dir = self.test_suite.current_test_data_dir
prog = 'smoke_test'
src = data_dir.join('{0}.c'.format(prog))
options = [
'-I{0}'.format(self.prefix.include),
src,
'-o',
prog,
'-L{0}'.format(self.prefix.lib),
'-lsigsegv',
'{0}{1}'.format(self.compiler.cc_rpath_arg, self.prefix.lib)]
reason = 'test: checking ability to link to the library'
self.run_test('cc', options, [], installed=False, purpose=reason)
# Now run the program and confirm the output matches expectations
expected = get_escaped_text_output(data_dir.join('smoke_test.out'))
reason = 'test: checking ability to use the library'
self.run_test(prog, [], expected, purpose=reason)
def _run_build_tests(self):
"""Run selected build tests."""
passed = 'Test passed'
checks = {
'sigsegv1': [passed],
'sigsegv2': [passed],
'sigsegv3': ['caught', passed],
'stackoverflow1': ['recursion', 'Stack overflow', passed],
'stackoverflow2': ['recursion', 'overflow', 'violation', passed],
}
for exe, expected in checks.items():
reason = 'test: checking {0} output'.format(exe)
self.run_test(exe, [], expected, installed=True, purpose=reason,
skip_missing=True)
def test(self):
"""Perform smoke tests on the installed package."""
tty.debug('Expected results currently based on simple {0} builds'
.format(self.name))
if not self.spec.satisfies('@2.10:2.12'):
tty.debug('Expected results have not been confirmed for {0} {1}'
.format(self.name, self.spec.version))
# Run the simple built-in smoke test
self._run_smoke_tests()
# Run test programs pulled from the build
self._run_build_tests() | 0.63624 | 0.316171 |
lines = int(input())
table = []
for i in range(lines):
table.append(list(map(int, input().split(" "))))
def rotate(deg, table):
cout = []
if deg == 180:
for i in range(lines):
cout.append(table[i][::-1])
cout = cout[::-1]
elif deg == 90:
for i in range(lines):
foo = []
for x in range(lines):
foo.append(table[-(x + 1)][i])
cout.append(foo)
elif deg == 270:
for i in range(lines):
foo = []
for x in range(lines):
foo.append(table[x][-(i + 1)])
cout.append(foo)
else:
return table
return cout
def get_degree(table):
for i in range(lines): # Top
if table[1][i] < table[0][i]:
break
for x in range(lines - 1):
if table[i][x] < table[i][x + 1]:
break
else:
if i == lines - 1:
return 270
continue
break
for i in range(lines): # Bottom
if table[-2][i] < table[-1][i]:
break
for x in range(lines - 1):
if table[-(i + 1)][x] > table[-(i + 1)][x + 1]:
break
else:
if i == lines - 1:
return 90
continue
break
for i in range(lines): # left
if table[i][1] < table[i][0]:
break
for x in range(lines - 1):
if table[x][i] > table[x + 1][i]:
break
else:
if i == lines - 1:
return 0
continue
break
for i in range(lines): # right
if table[i][-2] < table[i][-1]:
break
for x in range(lines - 1):
if table[x][-(i + 1)] < table[x + 1][-(i + 1)]:
break
else:
if i == lines - 1:
return 180
continue
break
degree = get_degree(table)
cout = rotate(degree, table)
for row in cout:
print(*row) | archive/2018/Problem J4: Sunflowers.py | lines = int(input())
table = []
for i in range(lines):
table.append(list(map(int, input().split(" "))))
def rotate(deg, table):
cout = []
if deg == 180:
for i in range(lines):
cout.append(table[i][::-1])
cout = cout[::-1]
elif deg == 90:
for i in range(lines):
foo = []
for x in range(lines):
foo.append(table[-(x + 1)][i])
cout.append(foo)
elif deg == 270:
for i in range(lines):
foo = []
for x in range(lines):
foo.append(table[x][-(i + 1)])
cout.append(foo)
else:
return table
return cout
def get_degree(table):
for i in range(lines): # Top
if table[1][i] < table[0][i]:
break
for x in range(lines - 1):
if table[i][x] < table[i][x + 1]:
break
else:
if i == lines - 1:
return 270
continue
break
for i in range(lines): # Bottom
if table[-2][i] < table[-1][i]:
break
for x in range(lines - 1):
if table[-(i + 1)][x] > table[-(i + 1)][x + 1]:
break
else:
if i == lines - 1:
return 90
continue
break
for i in range(lines): # left
if table[i][1] < table[i][0]:
break
for x in range(lines - 1):
if table[x][i] > table[x + 1][i]:
break
else:
if i == lines - 1:
return 0
continue
break
for i in range(lines): # right
if table[i][-2] < table[i][-1]:
break
for x in range(lines - 1):
if table[x][-(i + 1)] < table[x + 1][-(i + 1)]:
break
else:
if i == lines - 1:
return 180
continue
break
degree = get_degree(table)
cout = rotate(degree, table)
for row in cout:
print(*row) | 0.179926 | 0.229104 |
import math
import sys
import numpy as np
import typeguard
from loguru import logger
def set_result_logger_level():
if "RESULT" not in logger._core.levels:
logger.level("RESULT", no=60, color="<cyan>")
def millify(num, precision=0):
"""Humanize number (e.g., 30000 --> 30k).
Taken from https://github.com/azaitsev/millify/tree/master/millify"""
millnames = ['', 'k', 'M', 'B', 'T', 'P', 'E', 'Z', 'Y']
num = float(num)
millidx = max(
0,
min(
len(millnames) - 1,
int(math.floor(0 if num == 0 else math.log10(abs(num)) / 3)),
),
)
result = '{:.{precision}f}'.format(num / 10 ** (3 * millidx), precision=precision)
return '{0}{dx}'.format(result, dx=millnames[millidx])
def check_type(value, expected_type, argname=None):
"""Ensure that value matches expected_type.
Needed as Python currently doesn't have out of the box support for type checking using the typing module:
https://stackoverflow.com/questions/55503673/how-do-i-check-if-a-value-matches-a-type-in-python
Args:
value: value to be checked against `expected_type`
expected_type: a class or generic type instance
argname: name of the argument to check; used for error messages
Returns:
True if the type is correct, otherwise False
"""
if argname is None:
argname = 'variable'
try:
typeguard.check_type(argname, value, expected_type)
return True
except:
return False
def search_sequence_numpy(arr, seq):
"""Find sequence in an array using NumPy only.
Parameters
----------
arr : input 1D array
seq : input 1D array
Output
------
Output : 1D Array of indices in the input array that satisfy the
matching of input sequence in the input array.
In case of no match, an empty list is returned.
Taken from https://stackoverflow.com/questions/36522220/searching-a-sequence-in-a-numpy-array/36535397#36535397
"""
# Store sizes of input array and sequence
Na, Nseq = arr.size, seq.size
# Range of sequence
r_seq = np.arange(Nseq)
# Create a 2D array of sliding indices across the entire length of input array.
# Match up with the input sequence & get the matching starting indices.
M = (arr[np.arange(Na - Nseq + 1)[:, None] + r_seq] == seq).all(1)
# Get the range of those indices as final output
if M.any() > 0:
return np.where(np.convolve(M, np.ones((Nseq), dtype=int)) > 0)[0]
else:
return [] # No match found
def count_dict_values(d):
return sum(len(v) for v in d.values())
def set_loguru_level(level="DEBUG"):
logger.remove()
logger.add(sys.stderr, level=level)
def get_correlation_str(scores, ground_truth, func, label, include_pvalue=False):
r, p = func(scores, ground_truth)
res = f"{label}: {r:.3f}"
if include_pvalue:
res += f" ({p=:.5f})"
return res
def is_time_id_necessary(time_embedding_type):
"""Return true if the given time embedding type involves a time_id input"""
return "attention" in time_embedding_type | utils.py | import math
import sys
import numpy as np
import typeguard
from loguru import logger
def set_result_logger_level():
if "RESULT" not in logger._core.levels:
logger.level("RESULT", no=60, color="<cyan>")
def millify(num, precision=0):
"""Humanize number (e.g., 30000 --> 30k).
Taken from https://github.com/azaitsev/millify/tree/master/millify"""
millnames = ['', 'k', 'M', 'B', 'T', 'P', 'E', 'Z', 'Y']
num = float(num)
millidx = max(
0,
min(
len(millnames) - 1,
int(math.floor(0 if num == 0 else math.log10(abs(num)) / 3)),
),
)
result = '{:.{precision}f}'.format(num / 10 ** (3 * millidx), precision=precision)
return '{0}{dx}'.format(result, dx=millnames[millidx])
def check_type(value, expected_type, argname=None):
"""Ensure that value matches expected_type.
Needed as Python currently doesn't have out of the box support for type checking using the typing module:
https://stackoverflow.com/questions/55503673/how-do-i-check-if-a-value-matches-a-type-in-python
Args:
value: value to be checked against `expected_type`
expected_type: a class or generic type instance
argname: name of the argument to check; used for error messages
Returns:
True if the type is correct, otherwise False
"""
if argname is None:
argname = 'variable'
try:
typeguard.check_type(argname, value, expected_type)
return True
except:
return False
def search_sequence_numpy(arr, seq):
"""Find sequence in an array using NumPy only.
Parameters
----------
arr : input 1D array
seq : input 1D array
Output
------
Output : 1D Array of indices in the input array that satisfy the
matching of input sequence in the input array.
In case of no match, an empty list is returned.
Taken from https://stackoverflow.com/questions/36522220/searching-a-sequence-in-a-numpy-array/36535397#36535397
"""
# Store sizes of input array and sequence
Na, Nseq = arr.size, seq.size
# Range of sequence
r_seq = np.arange(Nseq)
# Create a 2D array of sliding indices across the entire length of input array.
# Match up with the input sequence & get the matching starting indices.
M = (arr[np.arange(Na - Nseq + 1)[:, None] + r_seq] == seq).all(1)
# Get the range of those indices as final output
if M.any() > 0:
return np.where(np.convolve(M, np.ones((Nseq), dtype=int)) > 0)[0]
else:
return [] # No match found
def count_dict_values(d):
return sum(len(v) for v in d.values())
def set_loguru_level(level="DEBUG"):
logger.remove()
logger.add(sys.stderr, level=level)
def get_correlation_str(scores, ground_truth, func, label, include_pvalue=False):
r, p = func(scores, ground_truth)
res = f"{label}: {r:.3f}"
if include_pvalue:
res += f" ({p=:.5f})"
return res
def is_time_id_necessary(time_embedding_type):
"""Return true if the given time embedding type involves a time_id input"""
return "attention" in time_embedding_type | 0.661923 | 0.52342 |
import copy
import numpy as np
import numpy.linalg as la
import scipy
import time
from src.opt_trace import Trace, StochasticTrace
from src.utils import set_seed
SEED = 42
MAX_SEED = 10000000
class Optimizer:
"""
Base class for optimization algorithms. Provides methods to run them,
save the trace and plot the results.
"""
def __init__(self, loss, t_max=np.inf, it_max=np.inf, trace_len=200, tolerance=0, line_search=None, use_prox=True):
if t_max is np.inf and it_max is np.inf:
it_max = 100
print('The number of iterations is set to 100.')
self.loss = loss
self.t_max = t_max
self.it_max = it_max
self.trace_len = trace_len
self.tolerance = tolerance
self.line_search = line_search
if line_search is not None:
line_search.reset(self)
self.use_prox = use_prox and (self.loss.regularizer is not None)
self.initialized = False
self.x_old_tol = None
self.trace = Trace(loss=loss)
def run(self, x0):
if not self.initialized:
self.init_run(x0)
self.initialized = True
while not self.check_convergence():
if self.tolerance > 0:
self.x_old_tol = copy.deepcopy(self.x)
self.step()
self.save_checkpoint()
return self.trace
def check_convergence(self):
no_it_left = self.it >= self.it_max
no_time_left = time.perf_counter()-self.t_start >= self.t_max
if self.tolerance > 0:
tolerance_met = self.x_old_tol is not None and self.loss.norm(self.x-self.x_old_tol) < self.tolerance
else:
tolerance_met = False
return no_it_left or no_time_left or tolerance_met
def step(self):
pass
def init_run(self, x0):
self.dim = x0.shape[0]
self.x = copy.deepcopy(x0)
self.trace.xs = [copy.deepcopy(x0)]
self.trace.its = [0]
self.trace.ts = [0]
if self.line_search is not None:
self.trace.ls_its = [0]
self.trace.lrs = [self.line_search.lr]
self.it = 0
self.t = 0
self.t_start = time.perf_counter()
self.time_progress = 0
self.iterations_progress = 0
self.max_progress = 0
def save_checkpoint(self, first_iterations=10):
self.it += 1
self.t = time.perf_counter() - self.t_start
self.time_progress = int((self.trace_len-first_iterations) * self.t / self.t_max)
self.iterations_progress = int((self.trace_len-first_iterations) * (self.it / self.it_max))
if (max(self.time_progress, self.iterations_progress) > self.max_progress) or (self.it <= first_iterations):
self.update_trace()
self.max_progress = max(self.time_progress, self.iterations_progress)
def update_trace(self):
self.trace.xs.append(copy.deepcopy(self.x))
self.trace.ts.append(self.t)
self.trace.its.append(self.it)
if self.line_search is not None:
self.trace.ls_its.append(self.line_search.it)
self.trace.lrs.append(self.line_search.lr)
def compute_loss_of_iterates(self):
self.trace.compute_loss_of_iterates()
def reset(self):
self.initialized = False
self.x_old_tol = None
self.trace = Trace(loss=loss)
class StochasticOptimizer(Optimizer):
"""
Base class for stochastic optimization algorithms.
The class has the same methods as Optimizer and, in addition, uses
multiple seeds to run the experiments.
"""
def __init__(self, loss, n_seeds=1, seeds=None, *args, **kwargs):
super(StochasticOptimizer, self).__init__(loss=loss, *args, **kwargs)
self.seeds = seeds
if not seeds:
np.random.seed(SEED)
self.seeds = np.random.choice(MAX_SEED, size=n_seeds, replace=False)
self.finished_seeds = []
self.trace = StochasticTrace(loss=loss)
self.seed = None
def run(self, *args, **kwargs):
for seed in self.seeds:
if seed in self.finished_seeds:
continue
if self.line_search is not None:
self.line_search.reset()
set_seed(seed)
self.seed = seed
self.trace.init_seed()
super(StochasticOptimizer, self).run(*args, **kwargs)
self.trace.append_seed_results(seed)
self.finished_seeds.append(seed)
self.initialized = False
self.seed = None
return self.trace
def add_seeds(self, n_extra_seeds=1):
np.random.seed(SEED)
n_seeds = len(self.seeds) + n_extra_seeds
self.seeds = np.random.choice(MAX_SEED, size=n_seeds, replace=False)
self.loss_is_computed = False | code/src/optimizer.py | import copy
import numpy as np
import numpy.linalg as la
import scipy
import time
from src.opt_trace import Trace, StochasticTrace
from src.utils import set_seed
SEED = 42
MAX_SEED = 10000000
class Optimizer:
"""
Base class for optimization algorithms. Provides methods to run them,
save the trace and plot the results.
"""
def __init__(self, loss, t_max=np.inf, it_max=np.inf, trace_len=200, tolerance=0, line_search=None, use_prox=True):
if t_max is np.inf and it_max is np.inf:
it_max = 100
print('The number of iterations is set to 100.')
self.loss = loss
self.t_max = t_max
self.it_max = it_max
self.trace_len = trace_len
self.tolerance = tolerance
self.line_search = line_search
if line_search is not None:
line_search.reset(self)
self.use_prox = use_prox and (self.loss.regularizer is not None)
self.initialized = False
self.x_old_tol = None
self.trace = Trace(loss=loss)
def run(self, x0):
if not self.initialized:
self.init_run(x0)
self.initialized = True
while not self.check_convergence():
if self.tolerance > 0:
self.x_old_tol = copy.deepcopy(self.x)
self.step()
self.save_checkpoint()
return self.trace
def check_convergence(self):
no_it_left = self.it >= self.it_max
no_time_left = time.perf_counter()-self.t_start >= self.t_max
if self.tolerance > 0:
tolerance_met = self.x_old_tol is not None and self.loss.norm(self.x-self.x_old_tol) < self.tolerance
else:
tolerance_met = False
return no_it_left or no_time_left or tolerance_met
def step(self):
pass
def init_run(self, x0):
self.dim = x0.shape[0]
self.x = copy.deepcopy(x0)
self.trace.xs = [copy.deepcopy(x0)]
self.trace.its = [0]
self.trace.ts = [0]
if self.line_search is not None:
self.trace.ls_its = [0]
self.trace.lrs = [self.line_search.lr]
self.it = 0
self.t = 0
self.t_start = time.perf_counter()
self.time_progress = 0
self.iterations_progress = 0
self.max_progress = 0
def save_checkpoint(self, first_iterations=10):
self.it += 1
self.t = time.perf_counter() - self.t_start
self.time_progress = int((self.trace_len-first_iterations) * self.t / self.t_max)
self.iterations_progress = int((self.trace_len-first_iterations) * (self.it / self.it_max))
if (max(self.time_progress, self.iterations_progress) > self.max_progress) or (self.it <= first_iterations):
self.update_trace()
self.max_progress = max(self.time_progress, self.iterations_progress)
def update_trace(self):
self.trace.xs.append(copy.deepcopy(self.x))
self.trace.ts.append(self.t)
self.trace.its.append(self.it)
if self.line_search is not None:
self.trace.ls_its.append(self.line_search.it)
self.trace.lrs.append(self.line_search.lr)
def compute_loss_of_iterates(self):
self.trace.compute_loss_of_iterates()
def reset(self):
self.initialized = False
self.x_old_tol = None
self.trace = Trace(loss=loss)
class StochasticOptimizer(Optimizer):
"""
Base class for stochastic optimization algorithms.
The class has the same methods as Optimizer and, in addition, uses
multiple seeds to run the experiments.
"""
def __init__(self, loss, n_seeds=1, seeds=None, *args, **kwargs):
super(StochasticOptimizer, self).__init__(loss=loss, *args, **kwargs)
self.seeds = seeds
if not seeds:
np.random.seed(SEED)
self.seeds = np.random.choice(MAX_SEED, size=n_seeds, replace=False)
self.finished_seeds = []
self.trace = StochasticTrace(loss=loss)
self.seed = None
def run(self, *args, **kwargs):
for seed in self.seeds:
if seed in self.finished_seeds:
continue
if self.line_search is not None:
self.line_search.reset()
set_seed(seed)
self.seed = seed
self.trace.init_seed()
super(StochasticOptimizer, self).run(*args, **kwargs)
self.trace.append_seed_results(seed)
self.finished_seeds.append(seed)
self.initialized = False
self.seed = None
return self.trace
def add_seeds(self, n_extra_seeds=1):
np.random.seed(SEED)
n_seeds = len(self.seeds) + n_extra_seeds
self.seeds = np.random.choice(MAX_SEED, size=n_seeds, replace=False)
self.loss_is_computed = False | 0.746693 | 0.220133 |
import asyncio
import logging
from typing import Optional
from asyncio import StreamReader, StreamWriter
from .packet import Packet
from .exceptions import \
AuthenticationException, NulLResponseException, MaxRetriesExceedException
_DEFAULT_RCON_PORT = 25575
# Sent to server
_CMD_LOGIN = 3
_CMD_RUN = 2
# Received from the server
_CMD_RESPONSE = 0
_CMD_AUTH_RESPONSE = 2
class AsyncRCON:
"""
Handles RCON TCP connection and command sending
and receiving.
Raises:
AuthenticationException
NulLResponseException
Arguments:
addr {str} -- RCON server address and port (i.e.: localhost, localhost:25575, 172.16.58.3:6543)
passwd {<PASSWORD>} -- <PASSWORD>
Keyword Arguments:
max_command_retries {Optional[int]} -- Maximum ammount of failed command retries (default: {10})
"""
_addr: str
_port: int
_passwd: str
_max_command_retries: int
_auto_reconnect: bool
_encoding: str
_writer: StreamWriter
_reader: StreamReader
_logger: logging.Logger
def __init__(self, addr: str, passwd: str,
max_command_retries: Optional[int] = 10,
auto_reconnect: Optional[bool] = True,
encoding: Optional[str] = 'utf-8'):
self._passwd = <PASSWORD>
addr_split = addr.split(':', 1)
self._addr = addr_split[0]
self._port = int(addr_split[1]) if len(addr_split) > 1 \
else _DEFAULT_RCON_PORT
self._max_command_retries = max_command_retries
self._auto_reconnect = auto_reconnect
self._logger = logging.getLogger('asyncrcon')
self._encoding = encoding
async def open_connection(self):
"""|coro|
Open connection event loop and log
in to the RCON server.
Raises:
AuthenticationException
"""
self._reader, self._writer = await asyncio.open_connection(
self._addr, self._port)
await self._send(Packet(0, _CMD_LOGIN, self._passwd))
packet = await self._receive()
# Some server always send an empty response first
if packet.cmd == _CMD_RESPONSE and len(packet.payload) == 0:
self._logger.debug("Got empty response in open_connection, waiting for another packet")
# Throw it away and get a new one
packet = await self._receive()
# Now check for an auth response next from the server
if packet.cmd != _CMD_AUTH_RESPONSE or packet.ident == -1:
raise AuthenticationException
async def command(self, cmd: str) -> str:
"""|coro|
Execute a command over RCON and wait
for response. If the command reponse is
empty or error
Arguments:
cmd {str} -- command literal
Raises:
MaxRetriesExceedException
Returns:
str -- RCON server response (may be empty in some cases)
"""
await self._send_command(cmd)
for _ in range(0, 10):
try:
return await self._rec_command()
except NulLResponseException:
self._logger.debug('retry')
self.close()
await self.open_connection()
await self._send_command(cmd)
continue
raise MaxRetriesExceedException
async def command_with_one_response(self, cmd):
await self._send(Packet(0, _CMD_RUN, cmd))
return (await self._receive()).payload
def close(self):
"""
Close the socket connection to the
RCON server.
"""
self._writer.close()
async def wait_closed(self):
await self._writer.wait_closed()
async def _send_command(self, cmd: str):
"""
Command sending wrapper.
Sends the actual command package and another
invalid package to trigger reponse with ident
'0' to register end of response from the server.
Arguments:
cmd {str} -- command literal
"""
await self._send(Packet(0, _CMD_RUN, cmd))
await self._send(Packet(1, _CMD_RESPONSE, ''))
async def _rec_command(self) -> str:
"""|coro|
Receive multi-packet command response.
Returns:
str -- command response
"""
res = ''
while True:
packet = await self._receive()
self._logger.debug('Recv Packet ID is #%d', packet.ident)
if packet.ident != 0:
break
res += packet.payload
return res
async def _receive(self) -> Packet:
"""|coro|
Receive single packet.
Raises:
NulLResponseException
Returns:
Packet -- response data packet
"""
data = b''
self._logger.debug('--> start recv')
while True:
packet, ln = Packet.decode(data, charset=self._encoding)
if packet is not None:
self._logger.debug('--> finished recv')
return packet
while len(data) < ln:
try:
chunk = await self._reader.read(ln - len(data))
except OSError as e:
if not self._auto_reconnect:
raise e
self._logger.warning('Connection was closed. Try reconnecting...')
self.close()
await self.open_connection()
if len(chunk) == 0:
raise NulLResponseException()
data += chunk
self._logger.debug('package {}, {}, {}'.format(data, len(data), ln))
async def _send(self, packet: Packet):
"""
Send encoded data packet.
Arguments:
packet {Packet} -- data packet
"""
self._logger.debug('<-- send {}'.format(packet.payload))
self._writer.write(packet.encode(charset=self._encoding))
await self._writer.drain() | asyncrcon/rcon.py | import asyncio
import logging
from typing import Optional
from asyncio import StreamReader, StreamWriter
from .packet import Packet
from .exceptions import \
AuthenticationException, NulLResponseException, MaxRetriesExceedException
_DEFAULT_RCON_PORT = 25575
# Sent to server
_CMD_LOGIN = 3
_CMD_RUN = 2
# Received from the server
_CMD_RESPONSE = 0
_CMD_AUTH_RESPONSE = 2
class AsyncRCON:
"""
Handles RCON TCP connection and command sending
and receiving.
Raises:
AuthenticationException
NulLResponseException
Arguments:
addr {str} -- RCON server address and port (i.e.: localhost, localhost:25575, 172.16.58.3:6543)
passwd {<PASSWORD>} -- <PASSWORD>
Keyword Arguments:
max_command_retries {Optional[int]} -- Maximum ammount of failed command retries (default: {10})
"""
_addr: str
_port: int
_passwd: str
_max_command_retries: int
_auto_reconnect: bool
_encoding: str
_writer: StreamWriter
_reader: StreamReader
_logger: logging.Logger
def __init__(self, addr: str, passwd: str,
max_command_retries: Optional[int] = 10,
auto_reconnect: Optional[bool] = True,
encoding: Optional[str] = 'utf-8'):
self._passwd = <PASSWORD>
addr_split = addr.split(':', 1)
self._addr = addr_split[0]
self._port = int(addr_split[1]) if len(addr_split) > 1 \
else _DEFAULT_RCON_PORT
self._max_command_retries = max_command_retries
self._auto_reconnect = auto_reconnect
self._logger = logging.getLogger('asyncrcon')
self._encoding = encoding
async def open_connection(self):
"""|coro|
Open connection event loop and log
in to the RCON server.
Raises:
AuthenticationException
"""
self._reader, self._writer = await asyncio.open_connection(
self._addr, self._port)
await self._send(Packet(0, _CMD_LOGIN, self._passwd))
packet = await self._receive()
# Some server always send an empty response first
if packet.cmd == _CMD_RESPONSE and len(packet.payload) == 0:
self._logger.debug("Got empty response in open_connection, waiting for another packet")
# Throw it away and get a new one
packet = await self._receive()
# Now check for an auth response next from the server
if packet.cmd != _CMD_AUTH_RESPONSE or packet.ident == -1:
raise AuthenticationException
async def command(self, cmd: str) -> str:
"""|coro|
Execute a command over RCON and wait
for response. If the command reponse is
empty or error
Arguments:
cmd {str} -- command literal
Raises:
MaxRetriesExceedException
Returns:
str -- RCON server response (may be empty in some cases)
"""
await self._send_command(cmd)
for _ in range(0, 10):
try:
return await self._rec_command()
except NulLResponseException:
self._logger.debug('retry')
self.close()
await self.open_connection()
await self._send_command(cmd)
continue
raise MaxRetriesExceedException
async def command_with_one_response(self, cmd):
await self._send(Packet(0, _CMD_RUN, cmd))
return (await self._receive()).payload
def close(self):
"""
Close the socket connection to the
RCON server.
"""
self._writer.close()
async def wait_closed(self):
await self._writer.wait_closed()
async def _send_command(self, cmd: str):
"""
Command sending wrapper.
Sends the actual command package and another
invalid package to trigger reponse with ident
'0' to register end of response from the server.
Arguments:
cmd {str} -- command literal
"""
await self._send(Packet(0, _CMD_RUN, cmd))
await self._send(Packet(1, _CMD_RESPONSE, ''))
async def _rec_command(self) -> str:
"""|coro|
Receive multi-packet command response.
Returns:
str -- command response
"""
res = ''
while True:
packet = await self._receive()
self._logger.debug('Recv Packet ID is #%d', packet.ident)
if packet.ident != 0:
break
res += packet.payload
return res
async def _receive(self) -> Packet:
"""|coro|
Receive single packet.
Raises:
NulLResponseException
Returns:
Packet -- response data packet
"""
data = b''
self._logger.debug('--> start recv')
while True:
packet, ln = Packet.decode(data, charset=self._encoding)
if packet is not None:
self._logger.debug('--> finished recv')
return packet
while len(data) < ln:
try:
chunk = await self._reader.read(ln - len(data))
except OSError as e:
if not self._auto_reconnect:
raise e
self._logger.warning('Connection was closed. Try reconnecting...')
self.close()
await self.open_connection()
if len(chunk) == 0:
raise NulLResponseException()
data += chunk
self._logger.debug('package {}, {}, {}'.format(data, len(data), ln))
async def _send(self, packet: Packet):
"""
Send encoded data packet.
Arguments:
packet {Packet} -- data packet
"""
self._logger.debug('<-- send {}'.format(packet.payload))
self._writer.write(packet.encode(charset=self._encoding))
await self._writer.drain() | 0.683314 | 0.083068 |
import enum
import functools
import json
import os
import time
from typing import Any, Callable, Dict, List, Optional, Tuple
import dataclasses
import numpy as onp
from aqt.utils import tfevent_utils
EventSeries = tfevent_utils.EventSeries
# Type Aliases
# Nested dict mapping from component (first key), attribute (second key) to
# events stored in EventSeries. E.g. component = 'train', attribute = 'loss'.
_AllEvents = Dict[str, Dict[str, EventSeries]]
# Nested dict mapping from component (first key), attribute (second key) to
# aggregated metric (float). E.g. component = 'train', attribute = 'loss'.
_AllAggMetrics = Dict[str, Dict[str, float]]
@enum.unique
class MinOrMax(enum.Enum):
"""Aggregation function to use for finding early stopping step."""
MIN = enum.auto() # use min value for early stopping step.
MAX = enum.auto() # use max value for early stopping step.
def get_func(self):
"""Returns function associated with enum option. See parent class."""
if self == MinOrMax.MIN:
return onp.nanargmin
elif self == MinOrMax.MAX:
return onp.nanargmax
else:
raise ValueError('MinOrMax enum option not recognized.')
@enum.unique
class SmoothingKernel(enum.Enum):
"""Kernel function to use for smoothing."""
# RECTANGULAR:Every value in symmetric window weighted equally. Values
# outside the window are not included in average.
# TRIANGULAR: Every value in symmetric window weighted as a linear function of
# absolute distance to kernel center. Values outside the window are not
# included in average.
RECTANGULAR = enum.auto()
TRIANGULAR = enum.auto()
def rectangular_kernel(self, x, window_size_in_steps):
"""Rectangular kernel for moving window average.
All values in window are equally weighted.
Args:
x: Distance to kernel center in steps.
window_size_in_steps: Size of the window to average over.
Returns:
Unnormalized weight to use for averaging, e.g. in `np.average()`.
Raises:
ValueError: If window_size_in_steps arg is less than 1.
"""
if window_size_in_steps < 1:
raise ValueError('window_size_in_steps has to be >= 1.')
if abs(x) <= window_size_in_steps / 2:
return 1.0
else:
return 0.0
def triangular_kernel(self, x, window_size_in_steps):
"""Triangular kernel for moving window average.
The weight is a linear function of the absolute distance to the kernel
center.
Args:
x: Distance to kernel center in steps.
window_size_in_steps: Size of the window to average over.
Returns:
Unnormalized weight to use for averaging, e.g. in `np.average()`.
Raises:
ValueError: If window_size_in_steps arg is less than 1.
"""
if window_size_in_steps < 1:
raise ValueError('window_size_in_steps has to be >= 1.')
return max(0.0, window_size_in_steps / 2 - abs(x))
def get_func(self,
window_size_in_steps = None):
"""Returns function associated with enum option. See parent class."""
if self == SmoothingKernel.RECTANGULAR:
if window_size_in_steps is None:
raise ValueError('For rectangular smoothing_kernel '
'window_size_in_steps must be provided.')
return functools.partial(
self.rectangular_kernel, window_size_in_steps=window_size_in_steps)
elif self == SmoothingKernel.TRIANGULAR:
if window_size_in_steps is None:
raise ValueError('For triangular smoothing_kernel '
'window_size_in_steps must be provided.')
return functools.partial(
self.triangular_kernel, window_size_in_steps=window_size_in_steps)
else:
raise ValueError('SmoothingKernel enum option not recognized.')
@dataclasses.dataclass
class ExperimentReport:
"""Report for a single experiment run based on its TFEvents files."""
# Model directory corresponding to single run, with TFEvents files to
# generate report from.
model_dir: str
# Metrics at early stop step, with smoothing applied.
# If NaN values present, then this field will
# be left None, but unsmoothed_metrics will still be reported.
# maps component name (e.g. eval) to metrics dict, which in turn maps
# attribute name to scalar value.
metrics: Optional[_AllAggMetrics]
# Metrics without smoothing at early stop step.
# maps component name (e.g. eval) to metrics dict, which in turn maps
# attribute name to scalar value.
unsmoothed_metrics: Optional[_AllAggMetrics]
# Step at which early_stop_attr in early_stop_ds_dir is minimized. Scalars are
# reported at this step.
early_stop_step: int
# Number of training steps. In combination with early_stop_step, can help
# determine whether training converged and started to overfit.
num_train_steps: int
# Arguments passed into create_end_of_training_report(), the function that
# created this report.
# Included here because the arguments can impact the reported metrics, e.g.
# which attribute was used to find the early stopping step.
report_query_args: Dict[str, Any]
# Human-readable experiment name.
experiment_name: Optional[str] = None
# Name of user who launched the experiment.
user_name: Optional[str] = None
# When experiment was launched, formatted as '%Y%m%dT%H%M%S'.
launch_time: Optional[str] = None
# Evaluation frequency. How often summaries were saved to file.
eval_freq: Optional[int] = None
# If any metrics contain NaN values, first step at which a NaN value occurs.
first_nan_step: Optional[int] = None
# Tensorboard ID or URL.
tensorboard_id: Optional[str] = None
def check_for_nans(event_series, start_step):
"""Finds step >= start_step at which first NaN value occurs if there are any.
Args:
event_series: list of tuples (step, value).
start_step: After which step to check for NaNs.
Returns:
Step at which first NaN value occurs, or None otherwise.
"""
keep_indices = (event_series.steps >= start_step)
event_series.steps = event_series.steps[keep_indices]
event_series.values = event_series.values[keep_indices]
nan_indices = onp.argwhere(onp.isnan(event_series.values))
if nan_indices.size:
return int(event_series.steps[onp.min(nan_indices)])
return None
def check_all_events_for_nans(all_events):
"""Finds step at which first NaN value occurs if there are any.
Args:
all_events: Nested dict mapping from component, attribute, to EventSeries.
Returns:
Step at which first NaN value occurs, or None otherwise.
"""
first_nan_step = None
for events_dict in all_events.values():
for events in events_dict.values():
cur_first_nan_step = check_for_nans(events, start_step=0)
if cur_first_nan_step is None:
continue
if first_nan_step is None:
first_nan_step = cur_first_nan_step
else:
first_nan_step = min(first_nan_step, cur_first_nan_step)
return first_nan_step
def find_early_stop_step(event_series,
early_stop_func,
start_step):
"""Finds step >= start_step at which event_series is minimized.
Args:
event_series: list of tuples (step, value).
early_stop_func: Aggregator function to use to find early_stop_step.
start_step: After which step to include values in moving average.
Returns:
Step at which moving average of series is minimized.
"""
keep_indices = (event_series.steps >= start_step)
event_series.steps = event_series.steps[keep_indices]
event_series.values = event_series.values[keep_indices]
if event_series.steps.size == 0:
raise ValueError('event_series does not have events after start_step.')
if onp.all(onp.isnan(event_series.values)):
return start_step
early_stop_idx = early_stop_func(event_series.values)
return int(event_series.steps[early_stop_idx])
def apply_smoothing_about_step(events, step,
kernel_fn):
"""Applies smoothing of event values for a single step.
Args:
events: list of tuples (step, value).
step: Step to apply smoothing about.
kernel_fn: Kernel function to use for smoothing.
Returns:
Smoothed value at step.
Raises:
ValueError: If NaN values present in events.values.
"""
if check_for_nans(events, start_step=0) is not None:
raise ValueError(
'NaN values encountered in smoothing, which is not supported.')
weights = onp.vectorize(kernel_fn)(events.steps - step)
return float(onp.average(events.values, weights=weights))
def apply_smoothing(events,
kernel_fn):
"""Applies smoothing of event values over all steps.
Args:
events: list of tuples (step, value).
kernel_fn: Kernel function to use for smoothing.
Returns:
Smoothed events for all steps in steps arg.
"""
smoothed_events = EventSeries(
name=events.name,
steps=onp.array([], dtype=int),
values=onp.array([]),
wall_times=None)
for i in range(len(events.steps)):
smoothed_events.steps = onp.append(smoothed_events.steps, events.steps[i])
smoothed_value = apply_smoothing_about_step(
events=events, step=events.steps[i], kernel_fn=kernel_fn)
smoothed_events.values = onp.append(smoothed_events.values, smoothed_value)
return smoothed_events
def get_agg_metrics_at_step(
all_events, step,
smoothing_kernel_fn):
"""Computes aggregated metrics from EventSeries dicts at early stop step.
Args:
all_events: Nested dict mapping from component, attribute, to EventSeries.
step: Step at which to get event values to compute aggregated metrics.
smoothing_kernel_fn: If None, no smoothing will be applied. If any NaNs are
present, has to be set to None, otherwise ValueError will be raised.
Returns:
dict mapping from (component, attribute) to aggregated scalar metric.
"""
all_agg_metrics = {}
for component, events_dict in all_events.items():
agg_metrics_dict = {}
for attr, events in events_dict.items():
if smoothing_kernel_fn is None:
index = onp.argmin(onp.abs(events.steps - step))
agg_metrics_dict[attr] = events.values[index]
else:
agg_metrics_dict[attr] = apply_smoothing_about_step(
events, step=step, kernel_fn=smoothing_kernel_fn)
all_agg_metrics[str(component)] = agg_metrics_dict
return all_agg_metrics
def compute_agg_metrics_from_events(
all_events,
early_stop_component,
early_stop_attr,
early_stop_agg,
smoothing_kernel,
window_size_in_steps = None,
start_step = 0
):
"""Computes aggregated metrics from EventSeries dicts.
Args:
all_events: Nested dict mapping from component, attribute, to EventSeries.
early_stop_component: Which component to use to find early_stop_step.
early_stop_attr: Attribute to find minimum or maximum of, e.g. 'perplexity'.
early_stop_agg: Which aggregator to use to find early_stop_step. See
MinOrMax class for enum options.
smoothing_kernel: Which kernel to use for smoothing. See SmoothingKernel
class for enum options.
window_size_in_steps: Only applicable to some kernels, including
'rectangular' kernel. Number of steps to average over.
start_step: After which step to consider early stopping, e.g. if set to 100,
only steps >= 100 will be considered.
Returns:
Tuple of dict mapping from (component, attribute) to aggregated scalar
metric and early_stop_step.
"""
first_nan_step = check_all_events_for_nans(all_events=all_events)
early_stop_func = early_stop_agg.get_func()
early_stop_events = all_events[early_stop_component][early_stop_attr]
if first_nan_step is None:
# Apply smoothing to early stop component events.
smoothing_kernel_func = smoothing_kernel.get_func(
window_size_in_steps=window_size_in_steps)
early_stop_events = apply_smoothing(
events=early_stop_events, kernel_fn=smoothing_kernel_func)
early_stop_step = find_early_stop_step(
early_stop_events, early_stop_func=early_stop_func, start_step=start_step)
all_agg_metrics_unsmoothed = get_agg_metrics_at_step(
all_events=all_events, step=early_stop_step, smoothing_kernel_fn=None)
if first_nan_step is None:
# Only get smoothed metrics if no NaN values found.
all_metrics_smoothed = get_agg_metrics_at_step(
all_events=all_events,
step=early_stop_step,
smoothing_kernel_fn=smoothing_kernel_func)
else:
all_metrics_smoothed = None
return all_agg_metrics_unsmoothed, all_metrics_smoothed, early_stop_step, first_nan_step
def create_end_of_training_report_oss(
model_dir,
eval_freq,
num_train_steps,
early_stop_attr,
early_stop_agg,
smoothing_kernel,
early_stop_ds_dir = None,
other_ds_dirs = None,
tags_to_include = None,
window_size_in_steps = 1,
start_step = 0,
experiment_name = None,
user_name = None,
launch_time = None,
tensorboard_id = None,
):
"""Creates an experiment report from TFEvents data after training completion.
Args:
model_dir: A model directory corresponding to a single model run, with
TFEvent file(s) and a single hparams_config file. The TFEvent files can
either be stored directly in model_dir, or in subdirectories in model_dir,
but not both.
eval_freq: Frequency of event saving.
num_train_steps: Number of training steps.
early_stop_attr: Attribute to find minimum or maximum of, e.g. 'perplexity'.
early_stop_agg: Which aggregator to use to find early_stop_step. See
MinOrMax class for enum options.
smoothing_kernel: Which kernel to use for smoothing. See SmoothingKernel
class for enum options.
early_stop_ds_dir: The events subdir in model_dir to use to find
early_stop_step if model_dir has subdirs. The early_stop_attr within
early_stop_ds_dir will be used to find the early_stop_step.
other_ds_dirs: List of other subdirs in model_dir with events to report.
tags_to_include: List of event tags that should be included.
window_size_in_steps: Number of steps to average over. Should be multiple of
eval_freq. If set to 1, no averaging will be applied.
start_step: After which step to consider early stopping, e.g. if set to 100,
only steps >= 100 will be considered.
experiment_name: Human-readable experiment name.
user_name: Name of user who launched the experiment.
launch_time: When experiment was launched, formatted as '%Y%m%dT%H%M%S'.
tensorboard_id: Tensorboard ID, e.g. URL to tensorboard dev, if applicable.
Returns:
An ExperimentReport dataclass instance.
"""
# Saving report query args, to be included in the report.
report_query_args = {
'early_stop_attr': early_stop_attr,
'early_stop_agg': early_stop_agg.name,
'early_stop_ds_dir': early_stop_ds_dir,
'other_ds_dirs': other_ds_dirs,
'tags_to_include': tags_to_include,
'smoothing_kernel': smoothing_kernel.name,
'window_size_in_steps': window_size_in_steps,
'start_step': start_step,
}
all_events = {}
early_stop_component = None
# If subdirs provided
if early_stop_ds_dir is not None or other_ds_dirs is not None:
if early_stop_ds_dir is None:
raise ValueError(
'If other_ds_dirs is not None, early_stop_ds_dir has to be '
'provided.')
early_stop_events = tfevent_utils.get_parsed_tfevents(
os.path.join(model_dir, early_stop_ds_dir), tags_to_include)
early_stop_component = early_stop_ds_dir
all_events[early_stop_component] = early_stop_events
if other_ds_dirs is not None:
for ds_dir in other_ds_dirs:
if ds_dir is not None:
all_events[ds_dir] = tfevent_utils.get_parsed_tfevents(
os.path.join(model_dir, ds_dir), tags_to_include)
else:
# If no subdirs provided, will assume that there are no subcomponents.
# For consistency with the case when we do have components, we store the
# events under the dummy component 'all'.
early_stop_component = 'all'
all_events[early_stop_component] = tfevent_utils.get_parsed_tfevents(
model_dir, tags_to_include)
all_agg_metrics_unsmoothed, all_agg_metrics_smoothed, early_stop_step, first_nan_step = compute_agg_metrics_from_events(
all_events=all_events,
early_stop_component=early_stop_component,
early_stop_attr=early_stop_attr,
early_stop_agg=early_stop_agg,
smoothing_kernel=smoothing_kernel,
window_size_in_steps=window_size_in_steps,
start_step=start_step)
report = ExperimentReport(
model_dir=model_dir,
metrics=all_agg_metrics_smoothed,
unsmoothed_metrics=all_agg_metrics_unsmoothed,
early_stop_step=early_stop_step,
num_train_steps=num_train_steps,
eval_freq=eval_freq,
first_nan_step=first_nan_step,
experiment_name=experiment_name,
user_name=user_name,
launch_time=launch_time,
tensorboard_id=tensorboard_id,
report_query_args=report_query_args,
)
return report | aqt/utils/report_utils.py | import enum
import functools
import json
import os
import time
from typing import Any, Callable, Dict, List, Optional, Tuple
import dataclasses
import numpy as onp
from aqt.utils import tfevent_utils
EventSeries = tfevent_utils.EventSeries
# Type Aliases
# Nested dict mapping from component (first key), attribute (second key) to
# events stored in EventSeries. E.g. component = 'train', attribute = 'loss'.
_AllEvents = Dict[str, Dict[str, EventSeries]]
# Nested dict mapping from component (first key), attribute (second key) to
# aggregated metric (float). E.g. component = 'train', attribute = 'loss'.
_AllAggMetrics = Dict[str, Dict[str, float]]
@enum.unique
class MinOrMax(enum.Enum):
"""Aggregation function to use for finding early stopping step."""
MIN = enum.auto() # use min value for early stopping step.
MAX = enum.auto() # use max value for early stopping step.
def get_func(self):
"""Returns function associated with enum option. See parent class."""
if self == MinOrMax.MIN:
return onp.nanargmin
elif self == MinOrMax.MAX:
return onp.nanargmax
else:
raise ValueError('MinOrMax enum option not recognized.')
@enum.unique
class SmoothingKernel(enum.Enum):
"""Kernel function to use for smoothing."""
# RECTANGULAR:Every value in symmetric window weighted equally. Values
# outside the window are not included in average.
# TRIANGULAR: Every value in symmetric window weighted as a linear function of
# absolute distance to kernel center. Values outside the window are not
# included in average.
RECTANGULAR = enum.auto()
TRIANGULAR = enum.auto()
def rectangular_kernel(self, x, window_size_in_steps):
"""Rectangular kernel for moving window average.
All values in window are equally weighted.
Args:
x: Distance to kernel center in steps.
window_size_in_steps: Size of the window to average over.
Returns:
Unnormalized weight to use for averaging, e.g. in `np.average()`.
Raises:
ValueError: If window_size_in_steps arg is less than 1.
"""
if window_size_in_steps < 1:
raise ValueError('window_size_in_steps has to be >= 1.')
if abs(x) <= window_size_in_steps / 2:
return 1.0
else:
return 0.0
def triangular_kernel(self, x, window_size_in_steps):
"""Triangular kernel for moving window average.
The weight is a linear function of the absolute distance to the kernel
center.
Args:
x: Distance to kernel center in steps.
window_size_in_steps: Size of the window to average over.
Returns:
Unnormalized weight to use for averaging, e.g. in `np.average()`.
Raises:
ValueError: If window_size_in_steps arg is less than 1.
"""
if window_size_in_steps < 1:
raise ValueError('window_size_in_steps has to be >= 1.')
return max(0.0, window_size_in_steps / 2 - abs(x))
def get_func(self,
window_size_in_steps = None):
"""Returns function associated with enum option. See parent class."""
if self == SmoothingKernel.RECTANGULAR:
if window_size_in_steps is None:
raise ValueError('For rectangular smoothing_kernel '
'window_size_in_steps must be provided.')
return functools.partial(
self.rectangular_kernel, window_size_in_steps=window_size_in_steps)
elif self == SmoothingKernel.TRIANGULAR:
if window_size_in_steps is None:
raise ValueError('For triangular smoothing_kernel '
'window_size_in_steps must be provided.')
return functools.partial(
self.triangular_kernel, window_size_in_steps=window_size_in_steps)
else:
raise ValueError('SmoothingKernel enum option not recognized.')
@dataclasses.dataclass
class ExperimentReport:
"""Report for a single experiment run based on its TFEvents files."""
# Model directory corresponding to single run, with TFEvents files to
# generate report from.
model_dir: str
# Metrics at early stop step, with smoothing applied.
# If NaN values present, then this field will
# be left None, but unsmoothed_metrics will still be reported.
# maps component name (e.g. eval) to metrics dict, which in turn maps
# attribute name to scalar value.
metrics: Optional[_AllAggMetrics]
# Metrics without smoothing at early stop step.
# maps component name (e.g. eval) to metrics dict, which in turn maps
# attribute name to scalar value.
unsmoothed_metrics: Optional[_AllAggMetrics]
# Step at which early_stop_attr in early_stop_ds_dir is minimized. Scalars are
# reported at this step.
early_stop_step: int
# Number of training steps. In combination with early_stop_step, can help
# determine whether training converged and started to overfit.
num_train_steps: int
# Arguments passed into create_end_of_training_report(), the function that
# created this report.
# Included here because the arguments can impact the reported metrics, e.g.
# which attribute was used to find the early stopping step.
report_query_args: Dict[str, Any]
# Human-readable experiment name.
experiment_name: Optional[str] = None
# Name of user who launched the experiment.
user_name: Optional[str] = None
# When experiment was launched, formatted as '%Y%m%dT%H%M%S'.
launch_time: Optional[str] = None
# Evaluation frequency. How often summaries were saved to file.
eval_freq: Optional[int] = None
# If any metrics contain NaN values, first step at which a NaN value occurs.
first_nan_step: Optional[int] = None
# Tensorboard ID or URL.
tensorboard_id: Optional[str] = None
def check_for_nans(event_series, start_step):
"""Finds step >= start_step at which first NaN value occurs if there are any.
Args:
event_series: list of tuples (step, value).
start_step: After which step to check for NaNs.
Returns:
Step at which first NaN value occurs, or None otherwise.
"""
keep_indices = (event_series.steps >= start_step)
event_series.steps = event_series.steps[keep_indices]
event_series.values = event_series.values[keep_indices]
nan_indices = onp.argwhere(onp.isnan(event_series.values))
if nan_indices.size:
return int(event_series.steps[onp.min(nan_indices)])
return None
def check_all_events_for_nans(all_events):
"""Finds step at which first NaN value occurs if there are any.
Args:
all_events: Nested dict mapping from component, attribute, to EventSeries.
Returns:
Step at which first NaN value occurs, or None otherwise.
"""
first_nan_step = None
for events_dict in all_events.values():
for events in events_dict.values():
cur_first_nan_step = check_for_nans(events, start_step=0)
if cur_first_nan_step is None:
continue
if first_nan_step is None:
first_nan_step = cur_first_nan_step
else:
first_nan_step = min(first_nan_step, cur_first_nan_step)
return first_nan_step
def find_early_stop_step(event_series,
early_stop_func,
start_step):
"""Finds step >= start_step at which event_series is minimized.
Args:
event_series: list of tuples (step, value).
early_stop_func: Aggregator function to use to find early_stop_step.
start_step: After which step to include values in moving average.
Returns:
Step at which moving average of series is minimized.
"""
keep_indices = (event_series.steps >= start_step)
event_series.steps = event_series.steps[keep_indices]
event_series.values = event_series.values[keep_indices]
if event_series.steps.size == 0:
raise ValueError('event_series does not have events after start_step.')
if onp.all(onp.isnan(event_series.values)):
return start_step
early_stop_idx = early_stop_func(event_series.values)
return int(event_series.steps[early_stop_idx])
def apply_smoothing_about_step(events, step,
kernel_fn):
"""Applies smoothing of event values for a single step.
Args:
events: list of tuples (step, value).
step: Step to apply smoothing about.
kernel_fn: Kernel function to use for smoothing.
Returns:
Smoothed value at step.
Raises:
ValueError: If NaN values present in events.values.
"""
if check_for_nans(events, start_step=0) is not None:
raise ValueError(
'NaN values encountered in smoothing, which is not supported.')
weights = onp.vectorize(kernel_fn)(events.steps - step)
return float(onp.average(events.values, weights=weights))
def apply_smoothing(events,
kernel_fn):
"""Applies smoothing of event values over all steps.
Args:
events: list of tuples (step, value).
kernel_fn: Kernel function to use for smoothing.
Returns:
Smoothed events for all steps in steps arg.
"""
smoothed_events = EventSeries(
name=events.name,
steps=onp.array([], dtype=int),
values=onp.array([]),
wall_times=None)
for i in range(len(events.steps)):
smoothed_events.steps = onp.append(smoothed_events.steps, events.steps[i])
smoothed_value = apply_smoothing_about_step(
events=events, step=events.steps[i], kernel_fn=kernel_fn)
smoothed_events.values = onp.append(smoothed_events.values, smoothed_value)
return smoothed_events
def get_agg_metrics_at_step(
all_events, step,
smoothing_kernel_fn):
"""Computes aggregated metrics from EventSeries dicts at early stop step.
Args:
all_events: Nested dict mapping from component, attribute, to EventSeries.
step: Step at which to get event values to compute aggregated metrics.
smoothing_kernel_fn: If None, no smoothing will be applied. If any NaNs are
present, has to be set to None, otherwise ValueError will be raised.
Returns:
dict mapping from (component, attribute) to aggregated scalar metric.
"""
all_agg_metrics = {}
for component, events_dict in all_events.items():
agg_metrics_dict = {}
for attr, events in events_dict.items():
if smoothing_kernel_fn is None:
index = onp.argmin(onp.abs(events.steps - step))
agg_metrics_dict[attr] = events.values[index]
else:
agg_metrics_dict[attr] = apply_smoothing_about_step(
events, step=step, kernel_fn=smoothing_kernel_fn)
all_agg_metrics[str(component)] = agg_metrics_dict
return all_agg_metrics
def compute_agg_metrics_from_events(
all_events,
early_stop_component,
early_stop_attr,
early_stop_agg,
smoothing_kernel,
window_size_in_steps = None,
start_step = 0
):
"""Computes aggregated metrics from EventSeries dicts.
Args:
all_events: Nested dict mapping from component, attribute, to EventSeries.
early_stop_component: Which component to use to find early_stop_step.
early_stop_attr: Attribute to find minimum or maximum of, e.g. 'perplexity'.
early_stop_agg: Which aggregator to use to find early_stop_step. See
MinOrMax class for enum options.
smoothing_kernel: Which kernel to use for smoothing. See SmoothingKernel
class for enum options.
window_size_in_steps: Only applicable to some kernels, including
'rectangular' kernel. Number of steps to average over.
start_step: After which step to consider early stopping, e.g. if set to 100,
only steps >= 100 will be considered.
Returns:
Tuple of dict mapping from (component, attribute) to aggregated scalar
metric and early_stop_step.
"""
first_nan_step = check_all_events_for_nans(all_events=all_events)
early_stop_func = early_stop_agg.get_func()
early_stop_events = all_events[early_stop_component][early_stop_attr]
if first_nan_step is None:
# Apply smoothing to early stop component events.
smoothing_kernel_func = smoothing_kernel.get_func(
window_size_in_steps=window_size_in_steps)
early_stop_events = apply_smoothing(
events=early_stop_events, kernel_fn=smoothing_kernel_func)
early_stop_step = find_early_stop_step(
early_stop_events, early_stop_func=early_stop_func, start_step=start_step)
all_agg_metrics_unsmoothed = get_agg_metrics_at_step(
all_events=all_events, step=early_stop_step, smoothing_kernel_fn=None)
if first_nan_step is None:
# Only get smoothed metrics if no NaN values found.
all_metrics_smoothed = get_agg_metrics_at_step(
all_events=all_events,
step=early_stop_step,
smoothing_kernel_fn=smoothing_kernel_func)
else:
all_metrics_smoothed = None
return all_agg_metrics_unsmoothed, all_metrics_smoothed, early_stop_step, first_nan_step
def create_end_of_training_report_oss(
model_dir,
eval_freq,
num_train_steps,
early_stop_attr,
early_stop_agg,
smoothing_kernel,
early_stop_ds_dir = None,
other_ds_dirs = None,
tags_to_include = None,
window_size_in_steps = 1,
start_step = 0,
experiment_name = None,
user_name = None,
launch_time = None,
tensorboard_id = None,
):
"""Creates an experiment report from TFEvents data after training completion.
Args:
model_dir: A model directory corresponding to a single model run, with
TFEvent file(s) and a single hparams_config file. The TFEvent files can
either be stored directly in model_dir, or in subdirectories in model_dir,
but not both.
eval_freq: Frequency of event saving.
num_train_steps: Number of training steps.
early_stop_attr: Attribute to find minimum or maximum of, e.g. 'perplexity'.
early_stop_agg: Which aggregator to use to find early_stop_step. See
MinOrMax class for enum options.
smoothing_kernel: Which kernel to use for smoothing. See SmoothingKernel
class for enum options.
early_stop_ds_dir: The events subdir in model_dir to use to find
early_stop_step if model_dir has subdirs. The early_stop_attr within
early_stop_ds_dir will be used to find the early_stop_step.
other_ds_dirs: List of other subdirs in model_dir with events to report.
tags_to_include: List of event tags that should be included.
window_size_in_steps: Number of steps to average over. Should be multiple of
eval_freq. If set to 1, no averaging will be applied.
start_step: After which step to consider early stopping, e.g. if set to 100,
only steps >= 100 will be considered.
experiment_name: Human-readable experiment name.
user_name: Name of user who launched the experiment.
launch_time: When experiment was launched, formatted as '%Y%m%dT%H%M%S'.
tensorboard_id: Tensorboard ID, e.g. URL to tensorboard dev, if applicable.
Returns:
An ExperimentReport dataclass instance.
"""
# Saving report query args, to be included in the report.
report_query_args = {
'early_stop_attr': early_stop_attr,
'early_stop_agg': early_stop_agg.name,
'early_stop_ds_dir': early_stop_ds_dir,
'other_ds_dirs': other_ds_dirs,
'tags_to_include': tags_to_include,
'smoothing_kernel': smoothing_kernel.name,
'window_size_in_steps': window_size_in_steps,
'start_step': start_step,
}
all_events = {}
early_stop_component = None
# If subdirs provided
if early_stop_ds_dir is not None or other_ds_dirs is not None:
if early_stop_ds_dir is None:
raise ValueError(
'If other_ds_dirs is not None, early_stop_ds_dir has to be '
'provided.')
early_stop_events = tfevent_utils.get_parsed_tfevents(
os.path.join(model_dir, early_stop_ds_dir), tags_to_include)
early_stop_component = early_stop_ds_dir
all_events[early_stop_component] = early_stop_events
if other_ds_dirs is not None:
for ds_dir in other_ds_dirs:
if ds_dir is not None:
all_events[ds_dir] = tfevent_utils.get_parsed_tfevents(
os.path.join(model_dir, ds_dir), tags_to_include)
else:
# If no subdirs provided, will assume that there are no subcomponents.
# For consistency with the case when we do have components, we store the
# events under the dummy component 'all'.
early_stop_component = 'all'
all_events[early_stop_component] = tfevent_utils.get_parsed_tfevents(
model_dir, tags_to_include)
all_agg_metrics_unsmoothed, all_agg_metrics_smoothed, early_stop_step, first_nan_step = compute_agg_metrics_from_events(
all_events=all_events,
early_stop_component=early_stop_component,
early_stop_attr=early_stop_attr,
early_stop_agg=early_stop_agg,
smoothing_kernel=smoothing_kernel,
window_size_in_steps=window_size_in_steps,
start_step=start_step)
report = ExperimentReport(
model_dir=model_dir,
metrics=all_agg_metrics_smoothed,
unsmoothed_metrics=all_agg_metrics_unsmoothed,
early_stop_step=early_stop_step,
num_train_steps=num_train_steps,
eval_freq=eval_freq,
first_nan_step=first_nan_step,
experiment_name=experiment_name,
user_name=user_name,
launch_time=launch_time,
tensorboard_id=tensorboard_id,
report_query_args=report_query_args,
)
return report | 0.911451 | 0.406067 |
import traceback
from nova.openstack.common.report.models import with_default_views as mwdv
from nova.openstack.common.report.views.text import threading as text_views
class StackTraceModel(mwdv.ModelWithDefaultViews):
"""A Stack Trace Model
This model holds data from a python stack trace,
commonly extracted from running thread information
:param stack_state: the python stack_state object
"""
def __init__(self, stack_state):
super(StackTraceModel, self).__init__(
text_view=text_views.StackTraceView())
if (stack_state is not None):
self['lines'] = [
{'filename': fn, 'line': ln, 'name': nm, 'code': cd}
for fn, ln, nm, cd in traceback.extract_stack(stack_state)
]
# FIXME(flepied): under Python3 f_exc_type doesn't exist
# anymore so we lose information about exceptions
if getattr(stack_state, 'f_exc_type', None) is not None:
self['root_exception'] = {
'type': stack_state.f_exc_type,
'value': stack_state.f_exc_value}
else:
self['root_exception'] = None
else:
self['lines'] = []
self['root_exception'] = None
class ThreadModel(mwdv.ModelWithDefaultViews):
"""A Thread Model
This model holds data for information about an
individual thread. It holds both a thread id,
as well as a stack trace for the thread
.. seealso::
Class :class:`StackTraceModel`
:param int thread_id: the id of the thread
:param stack: the python stack state for the current thread
"""
# threadId, stack in sys._current_frams().items()
def __init__(self, thread_id, stack):
super(ThreadModel, self).__init__(text_view=text_views.ThreadView())
self['thread_id'] = thread_id
self['stack_trace'] = StackTraceModel(stack)
class GreenThreadModel(mwdv.ModelWithDefaultViews):
"""A Green Thread Model
This model holds data for information about an
individual thread. Unlike the thread model,
it holds just a stack trace, since green threads
do not have thread ids.
.. seealso::
Class :class:`StackTraceModel`
:param stack: the python stack state for the green thread
"""
# gr in greenpool.coroutines_running --> gr.gr_frame
def __init__(self, stack):
super(GreenThreadModel, self).__init__(
{'stack_trace': StackTraceModel(stack)},
text_view=text_views.GreenThreadView()) | nova/openstack/common/report/models/threading.py | import traceback
from nova.openstack.common.report.models import with_default_views as mwdv
from nova.openstack.common.report.views.text import threading as text_views
class StackTraceModel(mwdv.ModelWithDefaultViews):
"""A Stack Trace Model
This model holds data from a python stack trace,
commonly extracted from running thread information
:param stack_state: the python stack_state object
"""
def __init__(self, stack_state):
super(StackTraceModel, self).__init__(
text_view=text_views.StackTraceView())
if (stack_state is not None):
self['lines'] = [
{'filename': fn, 'line': ln, 'name': nm, 'code': cd}
for fn, ln, nm, cd in traceback.extract_stack(stack_state)
]
# FIXME(flepied): under Python3 f_exc_type doesn't exist
# anymore so we lose information about exceptions
if getattr(stack_state, 'f_exc_type', None) is not None:
self['root_exception'] = {
'type': stack_state.f_exc_type,
'value': stack_state.f_exc_value}
else:
self['root_exception'] = None
else:
self['lines'] = []
self['root_exception'] = None
class ThreadModel(mwdv.ModelWithDefaultViews):
"""A Thread Model
This model holds data for information about an
individual thread. It holds both a thread id,
as well as a stack trace for the thread
.. seealso::
Class :class:`StackTraceModel`
:param int thread_id: the id of the thread
:param stack: the python stack state for the current thread
"""
# threadId, stack in sys._current_frams().items()
def __init__(self, thread_id, stack):
super(ThreadModel, self).__init__(text_view=text_views.ThreadView())
self['thread_id'] = thread_id
self['stack_trace'] = StackTraceModel(stack)
class GreenThreadModel(mwdv.ModelWithDefaultViews):
"""A Green Thread Model
This model holds data for information about an
individual thread. Unlike the thread model,
it holds just a stack trace, since green threads
do not have thread ids.
.. seealso::
Class :class:`StackTraceModel`
:param stack: the python stack state for the green thread
"""
# gr in greenpool.coroutines_running --> gr.gr_frame
def __init__(self, stack):
super(GreenThreadModel, self).__init__(
{'stack_trace': StackTraceModel(stack)},
text_view=text_views.GreenThreadView()) | 0.488283 | 0.249893 |
from __future__ import print_function, division
# This is the original Python 2.7 build file, used in building GlowScript
# according to the scheme described in docs/MakingNewVersion.txt.
# A more sophisticated build program is build_cli.py contributed by <NAME>.
"""This python program converts various parts of glowscript from the most
convenient format for modification into the most convenient format for
deployment.
* Take shaders from shaders/*.shader and combine them into lib/glow/shaders.gen.js
TODO
* Come up with a less painful model for development than running this after every change
* Combine and minify lib/*.js into ide.min.js, run.min.js, and embed.min.js
"""
from glob import glob
import re, os, subprocess
shader_file = ["Export({ shaders: {"]
for fn in glob("shaders/*.shader"):
name = re.match(r"^shaders[/\\]([^.]+).shader$", fn).group(1)
f = open(fn, "rt").read()
shader_file.append( '"' + name + '":' + repr(f) + "," )
shader_file.append("}});")
shader_file = "\n".join(shader_file)
open("lib/glow/shaders.gen.js", "wb").write(shader_file)
version = "2.7"
# TODO: Extract this information from run.js
glowscript_libraries = {
"run": [
"../lib/jquery/"+"2.1"+"/jquery.mousewheel.js", # use 2.1 lib with later versions
"../lib/flot/jquery.flot.js",
"../lib/flot/jquery.flot.crosshair_GS.js",
"../lib/plotly.js",
"../lib/opentype/poly2tri.js",
"../lib/opentype/opentype.js",
"../lib/glMatrix.js",
"../lib/webgl-utils.js",
"../lib/glow/property.js",
"../lib/glow/vectors.js",
"../lib/glow/mesh.js",
"../lib/glow/canvas.js",
"../lib/glow/orbital_camera.js",
"../lib/glow/autoscale.js",
"../lib/glow/WebGLRenderer.js",
"../lib/glow/graph.js",
"../lib/glow/color.js",
"../lib/glow/shapespaths.js",
"../lib/glow/primitives.js",
"../lib/glow/api_misc.js",
"../lib/glow/extrude.js",
"../lib/glow/shaders.gen.js",
# Unfortunately, uglify currently cannot handle function*, an ES6 feature in the es6 version of transform.js.
# Tried using babel to make an ES5 version of transform.js, to be able to uglify, but uglify failed again.
# Later: uglify-es does seem to handle ES6 but fails on RSrun; see below.
# So let's use the older version of Streamline:
"../lib/compiling/transform.js" # needed at run time as well as during compiling
],
"compile": [
"../lib/coffee-script.js",
"../lib/compiling/GScompiler.js",
"../lib/compiling/acorn.es.js",
"../lib/compiling/papercomp.js",
"../lib/compiling/transform.js" # also needed here, for creating JS for embedding in other web site
],
"RScompile": [
"../lib/compiling/GScompiler.js",
"../lib/rapydscript/compiler.js",
"../lib/compiling/acorn.es.js",
"../lib/compiling/papercomp.js",
"../lib/compiling/transform.js" # also needed here, for creating JS for embedding in other web site
],
"RSrun": [
"../lib/rapydscript/runtime.js",
],
"ide": []
}
def combine(inlibs):
# Apparently uglify moves the following string to the end of the package.
# "(function(){x})();" appears at the both the start and the end of the package.
all = [
"/*This is a combined, compressed file. Look at https://github.com/BruceSherwood/glowscript for source code and copyright information.*/",
";(function(){})();"
]
for fn in inlibs:
if fn.startswith("../"): fn = fn[3:]
all.append( open(fn, "r").read() )
return "\n".join(all)
env = os.environ.copy()
env["NODE_PATH"] = "build-tools/UglifyJS"
def minify(inlibs, inlibs_nomin, outlib):
all = combine(inlibs)
outf = open(outlib, "wb")
if True: # minify if True
uglify = subprocess.Popen( "build-tools/node.exe build-tools/Uglify-ES/uglify-es/bin/uglifyjs",
stdin=subprocess.PIPE,
stdout=outf,
stderr=outf, # write uglify errors into output file
env=env
)
uglify.communicate( all )
rc = uglify.wait()
if rc != 0:
print("Something went wrong")
else:
outf.write(all)
outf.write( combine(inlibs_nomin) )
outf.close()
minify( glowscript_libraries["run"], [], "package/glow." + version + ".min.js" )
print('Finished glow run-time package\n')
minify( glowscript_libraries["compile"], [], "package/compiler." + version + ".min.js" )
print('Finished JavaScript compiler package\n')
minify( glowscript_libraries["RScompile"], [], "package/RScompiler." + version + ".min.js" )
print('Finished RapydScript compiler package\n')
# For GlowScript 2.6 runtime.js had the encoding "UCS-2 LE BOM" which the Uglify
# machinery could not handle. Using (on Windows) notepad++ the encoding was changed
# to "UTF-8" which solved the problem.
minify( glowscript_libraries["RSrun"], [], "package/RSrun." + version + ".min.js" )
print('Finished RapydScript run-time package') | glowscript-fix_helix_canvas_error/build_original.py | from __future__ import print_function, division
# This is the original Python 2.7 build file, used in building GlowScript
# according to the scheme described in docs/MakingNewVersion.txt.
# A more sophisticated build program is build_cli.py contributed by <NAME>.
"""This python program converts various parts of glowscript from the most
convenient format for modification into the most convenient format for
deployment.
* Take shaders from shaders/*.shader and combine them into lib/glow/shaders.gen.js
TODO
* Come up with a less painful model for development than running this after every change
* Combine and minify lib/*.js into ide.min.js, run.min.js, and embed.min.js
"""
from glob import glob
import re, os, subprocess
shader_file = ["Export({ shaders: {"]
for fn in glob("shaders/*.shader"):
name = re.match(r"^shaders[/\\]([^.]+).shader$", fn).group(1)
f = open(fn, "rt").read()
shader_file.append( '"' + name + '":' + repr(f) + "," )
shader_file.append("}});")
shader_file = "\n".join(shader_file)
open("lib/glow/shaders.gen.js", "wb").write(shader_file)
version = "2.7"
# TODO: Extract this information from run.js
glowscript_libraries = {
"run": [
"../lib/jquery/"+"2.1"+"/jquery.mousewheel.js", # use 2.1 lib with later versions
"../lib/flot/jquery.flot.js",
"../lib/flot/jquery.flot.crosshair_GS.js",
"../lib/plotly.js",
"../lib/opentype/poly2tri.js",
"../lib/opentype/opentype.js",
"../lib/glMatrix.js",
"../lib/webgl-utils.js",
"../lib/glow/property.js",
"../lib/glow/vectors.js",
"../lib/glow/mesh.js",
"../lib/glow/canvas.js",
"../lib/glow/orbital_camera.js",
"../lib/glow/autoscale.js",
"../lib/glow/WebGLRenderer.js",
"../lib/glow/graph.js",
"../lib/glow/color.js",
"../lib/glow/shapespaths.js",
"../lib/glow/primitives.js",
"../lib/glow/api_misc.js",
"../lib/glow/extrude.js",
"../lib/glow/shaders.gen.js",
# Unfortunately, uglify currently cannot handle function*, an ES6 feature in the es6 version of transform.js.
# Tried using babel to make an ES5 version of transform.js, to be able to uglify, but uglify failed again.
# Later: uglify-es does seem to handle ES6 but fails on RSrun; see below.
# So let's use the older version of Streamline:
"../lib/compiling/transform.js" # needed at run time as well as during compiling
],
"compile": [
"../lib/coffee-script.js",
"../lib/compiling/GScompiler.js",
"../lib/compiling/acorn.es.js",
"../lib/compiling/papercomp.js",
"../lib/compiling/transform.js" # also needed here, for creating JS for embedding in other web site
],
"RScompile": [
"../lib/compiling/GScompiler.js",
"../lib/rapydscript/compiler.js",
"../lib/compiling/acorn.es.js",
"../lib/compiling/papercomp.js",
"../lib/compiling/transform.js" # also needed here, for creating JS for embedding in other web site
],
"RSrun": [
"../lib/rapydscript/runtime.js",
],
"ide": []
}
def combine(inlibs):
# Apparently uglify moves the following string to the end of the package.
# "(function(){x})();" appears at the both the start and the end of the package.
all = [
"/*This is a combined, compressed file. Look at https://github.com/BruceSherwood/glowscript for source code and copyright information.*/",
";(function(){})();"
]
for fn in inlibs:
if fn.startswith("../"): fn = fn[3:]
all.append( open(fn, "r").read() )
return "\n".join(all)
env = os.environ.copy()
env["NODE_PATH"] = "build-tools/UglifyJS"
def minify(inlibs, inlibs_nomin, outlib):
all = combine(inlibs)
outf = open(outlib, "wb")
if True: # minify if True
uglify = subprocess.Popen( "build-tools/node.exe build-tools/Uglify-ES/uglify-es/bin/uglifyjs",
stdin=subprocess.PIPE,
stdout=outf,
stderr=outf, # write uglify errors into output file
env=env
)
uglify.communicate( all )
rc = uglify.wait()
if rc != 0:
print("Something went wrong")
else:
outf.write(all)
outf.write( combine(inlibs_nomin) )
outf.close()
minify( glowscript_libraries["run"], [], "package/glow." + version + ".min.js" )
print('Finished glow run-time package\n')
minify( glowscript_libraries["compile"], [], "package/compiler." + version + ".min.js" )
print('Finished JavaScript compiler package\n')
minify( glowscript_libraries["RScompile"], [], "package/RScompiler." + version + ".min.js" )
print('Finished RapydScript compiler package\n')
# For GlowScript 2.6 runtime.js had the encoding "UCS-2 LE BOM" which the Uglify
# machinery could not handle. Using (on Windows) notepad++ the encoding was changed
# to "UTF-8" which solved the problem.
minify( glowscript_libraries["RSrun"], [], "package/RSrun." + version + ".min.js" )
print('Finished RapydScript run-time package') | 0.331444 | 0.184657 |
import genprog.core as gp
import genprog.evolution as gpevo
from typing import Dict, List, Any, Set, Optional, Union, Tuple
import numpy as np
import vision_genprog.utilities
import cv2
import logging
possible_types = ['grayscale_image', 'color_image', 'binary_image',
'float', 'int', 'bool', 'vector2', 'kernel3x3']
# parametersList = [minFloat, maxFloat, minInt, maxInt, width, height]
class Interpreter(gp.Interpreter):
def __init__(self, primitive_functions_tree, image_shapeHWC):
super().__init__(primitive_functions_tree)
self.image_shapeHWC = image_shapeHWC
def FunctionDefinition(self, functionName: str, argumentsList: List[Any]) -> Any:
if functionName == 'threshold':
_, thresholdedImg = cv2.threshold(argumentsList[0], argumentsList[1], 255, cv2.THRESH_BINARY)
return thresholdedImg
elif functionName == 'mask_sum':
return cv2.countNonZero(argumentsList[0])
elif functionName.startswith('tunnel'):
return argumentsList[0]
elif functionName == 'concat_floats':
vector2 = np.array([argumentsList[0], argumentsList[1]])
return vector2
elif functionName == 'mask_average':
mask_shapeHW = argumentsList[0].shape
return cv2.countNonZero(argumentsList[0])/(mask_shapeHW[0] * mask_shapeHW[1])
elif functionName == 'sobel1_x':
sobelImg = cv2.Sobel(argumentsList[0], ddepth=cv2.CV_32F, dx=1, dy=0, ksize=3)
return (128 + argumentsList[1] * sobelImg).astype(np.uint8)
elif functionName == 'sobel1_y':
sobelImg = cv2.Sobel(argumentsList[0], ddepth=cv2.CV_32F, dx=0, dy=1, ksize=3)
return (128 + argumentsList[1] * sobelImg).astype(np.uint8)
elif functionName == 'erode':
erosion_kernel = np.ones((3, 3), np.uint8)
return cv2.erode(argumentsList[0], erosion_kernel)
elif functionName == 'dilate':
dilation_kernel = np.ones((3, 3), np.uint8)
return cv2.dilate(argumentsList[0], dilation_kernel)
elif functionName == 'mask_image':
return cv2.min(argumentsList[0], argumentsList[1])
elif functionName == 'image_average0to1':
return np.mean(argumentsList[0])/255
elif functionName == 'blur3':
return cv2.blur(argumentsList[0], ksize=(3, 3))
elif functionName == 'laplacian1':
return cv2.Laplacian(argumentsList[0], ddepth=cv2.CV_8U, ksize=1)
elif functionName == 'laplacian3':
return cv2.Laplacian(argumentsList[0], ddepth=cv2.CV_8U, ksize=3)
elif functionName == 'min':
return cv2.min(argumentsList[0], argumentsList[1])
elif functionName == 'max':
return cv2.max(argumentsList[0], argumentsList[1])
elif functionName == 'linear_combination':
# w0 * a0 + w1 * a1 + b
return (argumentsList[0] * argumentsList[1] + argumentsList[2] * argumentsList[3] + argumentsList[4]).astype(np.uint8)
elif functionName == 'intersection':
return cv2.min(argumentsList[0], argumentsList[1])
elif functionName == 'union':
return cv2.max(argumentsList[0], argumentsList[1])
elif functionName == 'inverse_mask':
return 255 - argumentsList[0]
elif functionName == 'scharr1_x':
scharrImg = cv2.Scharr(argumentsList[0], ddepth=cv2.CV_32F, dx=1, dy=0)
return (128 + argumentsList[1] * scharrImg).astype(np.uint8)
elif functionName == 'scharr1_y':
scharrImg = cv2.Scharr(argumentsList[0], ddepth=cv2.CV_32F, dx=0, dy=1)
return (128 + argumentsList[1] * scharrImg).astype(np.uint8)
elif functionName == 'correlation3x3':
return cv2.filter2D(argumentsList[0], ddepth=cv2.CV_8U, kernel=argumentsList[1])
elif functionName == 'average_kernel3x3':
return (argumentsList[0] + argumentsList[1])/2
elif functionName == 'max_kernel3x3':
return cv2.max(argumentsList[0], argumentsList[1])
elif functionName == 'min_kernel3x3':
return cv2.min(argumentsList[0], argumentsList[1])
elif functionName == 'intersection_over_union':
intersectionImg = cv2.min(argumentsList[0], argumentsList[1])
unionImg = cv2.max(argumentsList[0], argumentsList[1])
union_area = cv2.countNonZero(unionImg)
if union_area == 0:
return 0
else:
return cv2.countNonZero(intersectionImg)/union_area
elif functionName == 'canny':
return cv2.Canny(argumentsList[0], argumentsList[1], argumentsList[2])
elif functionName == 'corner_harris':
harrisImg = cv2.cornerHarris(argumentsList[0], blockSize=2, ksize=3, k=0.04)
harris_min = np.min(harrisImg)
harris_max = np.max(harrisImg)
if harris_max == harris_min:
harris_normalized = 255 * (harrisImg - harris_min)
else:
harris_normalized = 255 * (harrisImg - harris_min)/(harris_max - harris_min)
return harris_normalized.astype(np.uint8)
else:
raise NotImplementedError("image_processing.Interpreter.FunctionDefinition(): Not implemented function '{}'".format(functionName))
def CreateConstant(self, returnType: str, parametersList: Optional[ List[Any] ] ) -> str:
if returnType == 'grayscale_image':
if len(parametersList) < 6:
raise ValueError(
"image_processing.Interpreter.CreateConstant(): Creating a '{}': len(parametersList) ({}) < 6".format(
returnType, len(parametersList)))
min_value = np.random.randint(parametersList[2], parametersList[3])
max_value = np.random.randint(parametersList[2], parametersList[3])
random_img = np.random.randint(min(min_value, max_value), max(min_value, max_value), self.image_shapeHWC)
return vision_genprog.utilities.ArrayToString(random_img)
elif returnType == 'color_image':
if len(parametersList) < 6:
raise ValueError(
"image_processing.Interpreter.CreateConstant(): Creating a '{}': len(parametersList) ({}) < 6".format(
returnType, len(parametersList)))
#black_img = np.zeros((parametersList[5], parametersList[4], 3), dtype=np.uint8)
min_value = np.random.randint(parametersList[2], parametersList[3])
max_value = np.random.randint(parametersList[2], parametersList[3])
random_img = np.random.randint(min(min_value, max_value), max(min_value, max_value), self.image_shapeHWC)
return vision_genprog.utilities.ArrayToString(random_img)
elif returnType == 'binary_image':
if len(parametersList) < 6:
raise ValueError(
"image_processing.Interpreter.CreateConstant(): Creating a '{}': len(parametersList) ({}) < 6".format(
returnType, len(parametersList)))
random_img = 255 * np.random.randint(0, 2, self.image_shapeHWC)
return vision_genprog.utilities.ArrayToString(random_img)
elif returnType == 'kernel3x3':
kernel = np.random.uniform(parametersList[0], parametersList[1], (3, 3))
kernel = (kernel - kernel.mean())/kernel.std() # Standardization
return vision_genprog.utilities.ArrayToString(kernel)
elif returnType == 'float':
if len(parametersList) < 2:
raise ValueError("image_processing.Interpreter.CreateConstant(): Creating a '{}': len(parametersList) ({}) < 2".format(returnType, len(parametersList)))
value = np.random.uniform(parametersList[0], parametersList[1])
return str(value)
elif returnType == 'int':
if len(parametersList) < 4:
raise ValueError(
"image_processing.Interpreter.CreateConstant(): Creating a '{}': len(parametersList) ({}) < 4".format(
returnType, len(parametersList)))
value = np.random.randint(parametersList[2], parametersList[3] + 1)
return str(value)
elif returnType == 'bool':
if np.random.randint(0, 2) == 0:
return 'true'
else:
return 'false'
else:
raise NotImplementedError("image_processing.Interpreter.CreateConstant(): Not implemented return type '{}'".format(returnType))
def PossibleTypes(self) -> List[str]:
return possible_types
def TypeConverter(self, type: str, value: str):
if type == 'grayscale_image' or type == 'color_image' or type == 'binary_image':
array1D = vision_genprog.utilities.StringTo1DArray(value)
return np.reshape(array1D.astype(np.uint8), self.image_shapeHWC)
elif type == 'int':
return int(value)
elif type == 'float':
return float(value)
elif type == 'bool':
if value.upper() == 'TRUE':
return True
else:
return False
elif type == 'vector2':
array1D = vision_genprog.utilities.StringTo1DArray(value)
return np.reshape(array1D, (2,))
elif type == 'kernel3x3':
array1D = vision_genprog.utilities.StringTo1DArray(value)
return np.reshape(array1D, (3, 3))
else:
raise NotImplementedError("image_processing.Interpreter.TypeConverter(): Not implemented type '{}'".format(type)) | src/vision_genprog/tasks/image_processing.py | import genprog.core as gp
import genprog.evolution as gpevo
from typing import Dict, List, Any, Set, Optional, Union, Tuple
import numpy as np
import vision_genprog.utilities
import cv2
import logging
possible_types = ['grayscale_image', 'color_image', 'binary_image',
'float', 'int', 'bool', 'vector2', 'kernel3x3']
# parametersList = [minFloat, maxFloat, minInt, maxInt, width, height]
class Interpreter(gp.Interpreter):
def __init__(self, primitive_functions_tree, image_shapeHWC):
super().__init__(primitive_functions_tree)
self.image_shapeHWC = image_shapeHWC
def FunctionDefinition(self, functionName: str, argumentsList: List[Any]) -> Any:
if functionName == 'threshold':
_, thresholdedImg = cv2.threshold(argumentsList[0], argumentsList[1], 255, cv2.THRESH_BINARY)
return thresholdedImg
elif functionName == 'mask_sum':
return cv2.countNonZero(argumentsList[0])
elif functionName.startswith('tunnel'):
return argumentsList[0]
elif functionName == 'concat_floats':
vector2 = np.array([argumentsList[0], argumentsList[1]])
return vector2
elif functionName == 'mask_average':
mask_shapeHW = argumentsList[0].shape
return cv2.countNonZero(argumentsList[0])/(mask_shapeHW[0] * mask_shapeHW[1])
elif functionName == 'sobel1_x':
sobelImg = cv2.Sobel(argumentsList[0], ddepth=cv2.CV_32F, dx=1, dy=0, ksize=3)
return (128 + argumentsList[1] * sobelImg).astype(np.uint8)
elif functionName == 'sobel1_y':
sobelImg = cv2.Sobel(argumentsList[0], ddepth=cv2.CV_32F, dx=0, dy=1, ksize=3)
return (128 + argumentsList[1] * sobelImg).astype(np.uint8)
elif functionName == 'erode':
erosion_kernel = np.ones((3, 3), np.uint8)
return cv2.erode(argumentsList[0], erosion_kernel)
elif functionName == 'dilate':
dilation_kernel = np.ones((3, 3), np.uint8)
return cv2.dilate(argumentsList[0], dilation_kernel)
elif functionName == 'mask_image':
return cv2.min(argumentsList[0], argumentsList[1])
elif functionName == 'image_average0to1':
return np.mean(argumentsList[0])/255
elif functionName == 'blur3':
return cv2.blur(argumentsList[0], ksize=(3, 3))
elif functionName == 'laplacian1':
return cv2.Laplacian(argumentsList[0], ddepth=cv2.CV_8U, ksize=1)
elif functionName == 'laplacian3':
return cv2.Laplacian(argumentsList[0], ddepth=cv2.CV_8U, ksize=3)
elif functionName == 'min':
return cv2.min(argumentsList[0], argumentsList[1])
elif functionName == 'max':
return cv2.max(argumentsList[0], argumentsList[1])
elif functionName == 'linear_combination':
# w0 * a0 + w1 * a1 + b
return (argumentsList[0] * argumentsList[1] + argumentsList[2] * argumentsList[3] + argumentsList[4]).astype(np.uint8)
elif functionName == 'intersection':
return cv2.min(argumentsList[0], argumentsList[1])
elif functionName == 'union':
return cv2.max(argumentsList[0], argumentsList[1])
elif functionName == 'inverse_mask':
return 255 - argumentsList[0]
elif functionName == 'scharr1_x':
scharrImg = cv2.Scharr(argumentsList[0], ddepth=cv2.CV_32F, dx=1, dy=0)
return (128 + argumentsList[1] * scharrImg).astype(np.uint8)
elif functionName == 'scharr1_y':
scharrImg = cv2.Scharr(argumentsList[0], ddepth=cv2.CV_32F, dx=0, dy=1)
return (128 + argumentsList[1] * scharrImg).astype(np.uint8)
elif functionName == 'correlation3x3':
return cv2.filter2D(argumentsList[0], ddepth=cv2.CV_8U, kernel=argumentsList[1])
elif functionName == 'average_kernel3x3':
return (argumentsList[0] + argumentsList[1])/2
elif functionName == 'max_kernel3x3':
return cv2.max(argumentsList[0], argumentsList[1])
elif functionName == 'min_kernel3x3':
return cv2.min(argumentsList[0], argumentsList[1])
elif functionName == 'intersection_over_union':
intersectionImg = cv2.min(argumentsList[0], argumentsList[1])
unionImg = cv2.max(argumentsList[0], argumentsList[1])
union_area = cv2.countNonZero(unionImg)
if union_area == 0:
return 0
else:
return cv2.countNonZero(intersectionImg)/union_area
elif functionName == 'canny':
return cv2.Canny(argumentsList[0], argumentsList[1], argumentsList[2])
elif functionName == 'corner_harris':
harrisImg = cv2.cornerHarris(argumentsList[0], blockSize=2, ksize=3, k=0.04)
harris_min = np.min(harrisImg)
harris_max = np.max(harrisImg)
if harris_max == harris_min:
harris_normalized = 255 * (harrisImg - harris_min)
else:
harris_normalized = 255 * (harrisImg - harris_min)/(harris_max - harris_min)
return harris_normalized.astype(np.uint8)
else:
raise NotImplementedError("image_processing.Interpreter.FunctionDefinition(): Not implemented function '{}'".format(functionName))
def CreateConstant(self, returnType: str, parametersList: Optional[ List[Any] ] ) -> str:
if returnType == 'grayscale_image':
if len(parametersList) < 6:
raise ValueError(
"image_processing.Interpreter.CreateConstant(): Creating a '{}': len(parametersList) ({}) < 6".format(
returnType, len(parametersList)))
min_value = np.random.randint(parametersList[2], parametersList[3])
max_value = np.random.randint(parametersList[2], parametersList[3])
random_img = np.random.randint(min(min_value, max_value), max(min_value, max_value), self.image_shapeHWC)
return vision_genprog.utilities.ArrayToString(random_img)
elif returnType == 'color_image':
if len(parametersList) < 6:
raise ValueError(
"image_processing.Interpreter.CreateConstant(): Creating a '{}': len(parametersList) ({}) < 6".format(
returnType, len(parametersList)))
#black_img = np.zeros((parametersList[5], parametersList[4], 3), dtype=np.uint8)
min_value = np.random.randint(parametersList[2], parametersList[3])
max_value = np.random.randint(parametersList[2], parametersList[3])
random_img = np.random.randint(min(min_value, max_value), max(min_value, max_value), self.image_shapeHWC)
return vision_genprog.utilities.ArrayToString(random_img)
elif returnType == 'binary_image':
if len(parametersList) < 6:
raise ValueError(
"image_processing.Interpreter.CreateConstant(): Creating a '{}': len(parametersList) ({}) < 6".format(
returnType, len(parametersList)))
random_img = 255 * np.random.randint(0, 2, self.image_shapeHWC)
return vision_genprog.utilities.ArrayToString(random_img)
elif returnType == 'kernel3x3':
kernel = np.random.uniform(parametersList[0], parametersList[1], (3, 3))
kernel = (kernel - kernel.mean())/kernel.std() # Standardization
return vision_genprog.utilities.ArrayToString(kernel)
elif returnType == 'float':
if len(parametersList) < 2:
raise ValueError("image_processing.Interpreter.CreateConstant(): Creating a '{}': len(parametersList) ({}) < 2".format(returnType, len(parametersList)))
value = np.random.uniform(parametersList[0], parametersList[1])
return str(value)
elif returnType == 'int':
if len(parametersList) < 4:
raise ValueError(
"image_processing.Interpreter.CreateConstant(): Creating a '{}': len(parametersList) ({}) < 4".format(
returnType, len(parametersList)))
value = np.random.randint(parametersList[2], parametersList[3] + 1)
return str(value)
elif returnType == 'bool':
if np.random.randint(0, 2) == 0:
return 'true'
else:
return 'false'
else:
raise NotImplementedError("image_processing.Interpreter.CreateConstant(): Not implemented return type '{}'".format(returnType))
def PossibleTypes(self) -> List[str]:
return possible_types
def TypeConverter(self, type: str, value: str):
if type == 'grayscale_image' or type == 'color_image' or type == 'binary_image':
array1D = vision_genprog.utilities.StringTo1DArray(value)
return np.reshape(array1D.astype(np.uint8), self.image_shapeHWC)
elif type == 'int':
return int(value)
elif type == 'float':
return float(value)
elif type == 'bool':
if value.upper() == 'TRUE':
return True
else:
return False
elif type == 'vector2':
array1D = vision_genprog.utilities.StringTo1DArray(value)
return np.reshape(array1D, (2,))
elif type == 'kernel3x3':
array1D = vision_genprog.utilities.StringTo1DArray(value)
return np.reshape(array1D, (3, 3))
else:
raise NotImplementedError("image_processing.Interpreter.TypeConverter(): Not implemented type '{}'".format(type)) | 0.677687 | 0.448547 |
import ssl
import logging
import datetime
import pytz
from multidict import CIMultiDictProxy
from typing import List, Optional
from cryptoxlib.CryptoXLibClient import CryptoXLibClient, RestCallType
from cryptoxlib.clients.bitpanda import enums
from cryptoxlib.clients.bitpanda.exceptions import BitpandaRestException, BitpandaException
from cryptoxlib.clients.bitpanda.functions import map_pair
from cryptoxlib.Pair import Pair
from cryptoxlib.WebsocketMgr import WebsocketMgr, Subscription
from cryptoxlib.clients.bitpanda.BitpandaWebsocket import BitpandaWebsocket
LOG = logging.getLogger(__name__)
class BitpandaClient(CryptoXLibClient):
REST_API_URI = "https://api.exchange.bitpanda.com/public/v1/"
def __init__(self, api_key: str = None, api_trace_log: bool = False,
ssl_context: ssl.SSLContext = None) -> None:
super().__init__(api_trace_log, ssl_context)
self.api_key = api_key
def _get_rest_api_uri(self) -> str:
return self.REST_API_URI
def _sign_payload(self, rest_call_type: RestCallType, resource: str, data: dict = None, params: dict = None, headers: dict = None) -> None:
headers["Authorization"] = "Bearer " + self.api_key
def _preprocess_rest_response(self, status_code: int, headers: 'CIMultiDictProxy[str]', body: Optional[dict]) -> None:
if str(status_code)[0] != '2':
raise BitpandaRestException(status_code, body)
def _get_websocket_mgr(self, subscriptions: List[Subscription], startup_delay_ms: int = 0,
ssl_context = None) -> WebsocketMgr:
return BitpandaWebsocket(subscriptions = subscriptions, api_key = self.api_key, ssl_context = ssl_context,
startup_delay_ms = startup_delay_ms)
async def get_currencies(self) -> dict:
return await self._create_get("currencies")
async def get_fee_groups(self) -> dict:
return await self._create_get("fees")
async def get_account_balances(self) -> dict:
return await self._create_get("account/balances", signed = True)
async def get_account_fees(self) -> dict:
return await self._create_get("account/fees", signed = True)
async def get_account_orders(self, from_timestamp: datetime.datetime = None, to_timestamp: datetime.datetime = None,
pair: Pair = None, with_cancelled_and_rejected: str = None,
with_just_filled_inactive: str = None,
with_just_orders: str = None, max_page_size: str = None, cursor: str = None) -> dict:
params = BitpandaClient._clean_request_params({
"with_cancelled_and_rejected": with_cancelled_and_rejected,
"with_just_filled_inactive": with_just_filled_inactive,
"with_just_orders": with_just_orders,
"max_page_size": max_page_size,
"cursor": cursor,
})
if pair is not None:
params["instrument_code"] = map_pair(pair)
if from_timestamp is not None:
params["from"] = from_timestamp.astimezone(pytz.utc).isoformat()
if to_timestamp is not None:
params["to"] = to_timestamp.astimezone(pytz.utc).isoformat()
return await self._create_get("account/orders", params = params, signed = True)
async def get_account_order(self, order_id: str) -> dict:
return await self._create_get("account/orders/" + order_id, signed = True)
async def get_account_order_trades(self, order_id: str) -> dict:
return await self._create_get("account/orders/" + order_id + "/trades", signed = True)
async def get_account_trades(self, from_timestamp: datetime.datetime = None, to_timestamp: datetime.datetime = None,
pair: Pair = None, max_page_size: str = None, cursor: str = None) -> dict:
params = BitpandaClient._clean_request_params({
"max_page_size": max_page_size,
"cursor": cursor,
})
if pair is not None:
params["instrument_code"] = map_pair(pair)
if from_timestamp is not None:
params["from"] = from_timestamp.astimezone(pytz.utc).isoformat()
if to_timestamp is not None:
params["to"] = to_timestamp.astimezone(pytz.utc).isoformat()
return await self._create_get("account/trades", params = params, signed = True)
async def get_account_trade(self, trade_id: str) -> dict:
return await self._create_get("account/trades/" + trade_id, signed = True)
async def get_account_trading_volume(self) -> dict:
return await self._create_get("account/trading-volume", signed = True)
async def create_market_order(self, pair: Pair, side: enums.OrderSide, amount: str, client_id: str = None) -> dict:
data = {
"instrument_code": map_pair(pair),
"side": side.value,
"type": enums.OrderType.MARKET.value,
"amount": amount
}
if client_id is not None:
data['client_id'] = client_id
return await self._create_post("account/orders", data = data, signed = True)
async def create_limit_order(self, pair: Pair, side: enums.OrderSide, amount: str, limit_price: str,
time_in_force: enums.TimeInForce = None, client_id: str = None) -> dict:
data = {
"instrument_code": map_pair(pair),
"side": side.value,
"type": enums.OrderType.LIMIT.value,
"amount": amount,
"price": limit_price
}
if client_id is not None:
data['client_id'] = client_id
if time_in_force is not None:
data['time_in_force'] = time_in_force.value
return await self._create_post("account/orders", data = data, signed = True)
async def create_stop_limit_order(self, pair: Pair, side: enums.OrderSide, amount: str, limit_price: str,
stop_price: str,
time_in_force: enums.TimeInForce = None, client_id: str = None) -> dict:
data = {
"instrument_code": map_pair(pair),
"side": side.value,
"type": enums.OrderType.STOP_LIMIT.value,
"amount": amount,
"price": limit_price,
"trigger_price": stop_price
}
if client_id is not None:
data['client_id'] = client_id
if time_in_force is not None:
data['time_in_force'] = time_in_force.value
return await self._create_post("account/orders", data = data, signed = True)
async def delete_account_orders(self, pair: Pair = None, ids: List[str] = None) -> dict:
params = {}
if pair is not None:
params["instrument_code"] = map_pair(pair)
if ids is not None:
params['ids'] = ','.join(ids)
return await self._create_delete("account/orders", params = params, signed = True)
async def delete_account_order(self, order_id: str = None, client_id: str = None) -> dict:
if order_id is None and client_id is None:
raise BitpandaException('One of order_id/client_id has to be provided.')
if order_id is not None and client_id is not None:
raise BitpandaException('Only one of order_id/client_id can be provided.')
if order_id is not None:
return await self._create_delete("account/orders/" + order_id, signed = True)
else:
return await self._create_delete("account/orders/client/" + client_id, signed = True)
async def update_order(self, amount: str, order_id: str = None, client_id: str = None) -> dict:
if order_id is None and client_id is None:
raise BitpandaException('One of order_id/client_id has to be provided.')
if order_id is not None and client_id is not None:
raise BitpandaException('Only one of order_id/client_id can be provided.')
data = {
"amount": amount
}
if order_id is not None:
return await self._create_put("account/orders/" + order_id, data = data, signed = True)
else:
return await self._create_put("account/orders/client/" + client_id, data = data, signed = True)
async def get_candlesticks(self, pair: Pair, unit: enums.TimeUnit, period: str, from_timestamp: datetime.datetime,
to_timestamp: datetime.datetime) -> dict:
params = {
"unit": unit.value,
"period": period,
"from": from_timestamp.astimezone(pytz.utc).isoformat(),
"to": to_timestamp.astimezone(pytz.utc).isoformat(),
}
return await self._create_get("candlesticks/" + map_pair(pair), params = params)
async def get_instruments(self) -> dict:
return await self._create_get("instruments")
async def get_order_book(self, pair: Pair, level: str = None, depth: str = None) -> dict:
params = BitpandaClient._clean_request_params({
"level": level,
"depth": depth
})
return await self._create_get("order-book/" + map_pair(pair), params = params)
async def get_time(self) -> dict:
return await self._create_get("time")
async def get_market_tickers(self) -> dict:
return await self._create_get("market-ticker")
async def get_market_ticker(self, pair: Pair) -> dict:
return await self._create_get("market-ticker/" + map_pair(pair))
async def get_price_tick(self, pair: Pair, from_timestamp: datetime.datetime = None,
to_timestamp: datetime.datetime = None) -> dict:
params = {}
if from_timestamp is not None:
params['from'] = from_timestamp.astimezone(pytz.utc).isoformat()
if to_timestamp is not None:
params['to'] = to_timestamp.astimezone(pytz.utc).isoformat()
return await self._create_get("price-ticks/" + map_pair(pair), params = params)
async def create_deposit_crypto_address(self, currency: str) -> dict:
data = {
"currency": currency
}
return await self._create_post("account/deposit/crypto", data = data, signed = True)
async def get_deposit_crypto_address(self, currency: str) -> dict:
return await self._create_get("account/deposit/crypto/" + currency, signed = True)
async def get_fiat_deposit_info(self) -> dict:
return await self._create_get("account/deposit/fiat/EUR", signed = True)
async def withdraw_crypto(self, currency: str, amount: str, address: str, destination_tag: str = None) -> dict:
data = {
'currency': currency,
'amount': amount,
'recipient': {
'address': address
}
}
if destination_tag is not None:
data['recipient']['destination_tag'] = destination_tag
return await self._create_post("account/withdraw/crypto", data = data, signed = True)
async def withdraw_fiat(self, currency: str, amount: str, payout_account_id: str) -> dict:
data = {
'currency': currency,
'amount': amount,
'payout_account_id': payout_account_id
}
return await self._create_post("account/withdraw/fiat", data = data, signed = True)
async def get_deposits(self, from_timestamp: datetime.datetime = None,
to_timestamp: datetime.datetime = None,
currency: str = None,
max_page_size: int = None,
cursor: int = None) -> dict:
params = self._clean_request_params({
'currency_code': currency,
'max_page_size': max_page_size,
'cursor': cursor
})
if from_timestamp is not None:
params['from'] = from_timestamp.astimezone(pytz.utc).isoformat()
if to_timestamp is not None:
params['to'] = to_timestamp.astimezone(pytz.utc).isoformat()
return await self._create_get("account/deposits", params = params, signed = True)
async def get_bitpanda_deposits(self, from_timestamp: datetime.datetime = None,
to_timestamp: datetime.datetime = None,
currency: str = None,
max_page_size: int = None,
cursor: int = None) -> dict:
params = self._clean_request_params({
'currency_code': currency,
'max_page_size': max_page_size,
'cursor': cursor
})
if from_timestamp is not None:
params['from'] = from_timestamp.astimezone(pytz.utc).isoformat()
if to_timestamp is not None:
params['to'] = to_timestamp.astimezone(pytz.utc).isoformat()
return await self._create_get("account/deposits/bitpanda", params = params, signed = True)
async def get_withdrawals(self, from_timestamp: datetime.datetime = None,
to_timestamp: datetime.datetime = None,
currency: str = None,
max_page_size: int = None,
cursor: int = None) -> dict:
params = self._clean_request_params({
'currency_code': currency,
'max_page_size': max_page_size,
'cursor': cursor
})
if from_timestamp is not None:
params['from'] = from_timestamp.astimezone(pytz.utc).isoformat()
if to_timestamp is not None:
params['to'] = to_timestamp.astimezone(pytz.utc).isoformat()
return await self._create_get("account/withdrawals", params = params, signed = True)
async def get_bitpanda_withdrawals(self, from_timestamp: datetime.datetime = None,
to_timestamp: datetime.datetime = None,
currency: str = None,
max_page_size: int = None,
cursor: int = None) -> dict:
params = self._clean_request_params({
'currency_code': currency,
'max_page_size': max_page_size,
'cursor': cursor
})
if from_timestamp is not None:
params['from'] = from_timestamp.astimezone(pytz.utc).isoformat()
if to_timestamp is not None:
params['to'] = to_timestamp.astimezone(pytz.utc).isoformat()
return await self._create_get("account/withdrawals/bitpanda", params = params, signed = True)
async def toggle_best_fee_collection(self, indicator: bool) -> dict:
data = {
'collect_fees_in_best': indicator
}
return await self._create_post("account/fees", data = data, signed = True)
async def auto_cancel_all_orders(self, timeout_ms: int) -> dict:
data = {
'timeout': timeout_ms
}
return await self._create_post("account/orders/cancel-all-after", data = data, signed = True)
async def delete_auto_cancel_all_orders(self) -> dict:
return await self._create_delete("account/orders/cancel-all-after", signed = True) | cryptoxlib/clients/bitpanda/BitpandaClient.py | import ssl
import logging
import datetime
import pytz
from multidict import CIMultiDictProxy
from typing import List, Optional
from cryptoxlib.CryptoXLibClient import CryptoXLibClient, RestCallType
from cryptoxlib.clients.bitpanda import enums
from cryptoxlib.clients.bitpanda.exceptions import BitpandaRestException, BitpandaException
from cryptoxlib.clients.bitpanda.functions import map_pair
from cryptoxlib.Pair import Pair
from cryptoxlib.WebsocketMgr import WebsocketMgr, Subscription
from cryptoxlib.clients.bitpanda.BitpandaWebsocket import BitpandaWebsocket
LOG = logging.getLogger(__name__)
class BitpandaClient(CryptoXLibClient):
REST_API_URI = "https://api.exchange.bitpanda.com/public/v1/"
def __init__(self, api_key: str = None, api_trace_log: bool = False,
ssl_context: ssl.SSLContext = None) -> None:
super().__init__(api_trace_log, ssl_context)
self.api_key = api_key
def _get_rest_api_uri(self) -> str:
return self.REST_API_URI
def _sign_payload(self, rest_call_type: RestCallType, resource: str, data: dict = None, params: dict = None, headers: dict = None) -> None:
headers["Authorization"] = "Bearer " + self.api_key
def _preprocess_rest_response(self, status_code: int, headers: 'CIMultiDictProxy[str]', body: Optional[dict]) -> None:
if str(status_code)[0] != '2':
raise BitpandaRestException(status_code, body)
def _get_websocket_mgr(self, subscriptions: List[Subscription], startup_delay_ms: int = 0,
ssl_context = None) -> WebsocketMgr:
return BitpandaWebsocket(subscriptions = subscriptions, api_key = self.api_key, ssl_context = ssl_context,
startup_delay_ms = startup_delay_ms)
async def get_currencies(self) -> dict:
return await self._create_get("currencies")
async def get_fee_groups(self) -> dict:
return await self._create_get("fees")
async def get_account_balances(self) -> dict:
return await self._create_get("account/balances", signed = True)
async def get_account_fees(self) -> dict:
return await self._create_get("account/fees", signed = True)
async def get_account_orders(self, from_timestamp: datetime.datetime = None, to_timestamp: datetime.datetime = None,
pair: Pair = None, with_cancelled_and_rejected: str = None,
with_just_filled_inactive: str = None,
with_just_orders: str = None, max_page_size: str = None, cursor: str = None) -> dict:
params = BitpandaClient._clean_request_params({
"with_cancelled_and_rejected": with_cancelled_and_rejected,
"with_just_filled_inactive": with_just_filled_inactive,
"with_just_orders": with_just_orders,
"max_page_size": max_page_size,
"cursor": cursor,
})
if pair is not None:
params["instrument_code"] = map_pair(pair)
if from_timestamp is not None:
params["from"] = from_timestamp.astimezone(pytz.utc).isoformat()
if to_timestamp is not None:
params["to"] = to_timestamp.astimezone(pytz.utc).isoformat()
return await self._create_get("account/orders", params = params, signed = True)
async def get_account_order(self, order_id: str) -> dict:
return await self._create_get("account/orders/" + order_id, signed = True)
async def get_account_order_trades(self, order_id: str) -> dict:
return await self._create_get("account/orders/" + order_id + "/trades", signed = True)
async def get_account_trades(self, from_timestamp: datetime.datetime = None, to_timestamp: datetime.datetime = None,
pair: Pair = None, max_page_size: str = None, cursor: str = None) -> dict:
params = BitpandaClient._clean_request_params({
"max_page_size": max_page_size,
"cursor": cursor,
})
if pair is not None:
params["instrument_code"] = map_pair(pair)
if from_timestamp is not None:
params["from"] = from_timestamp.astimezone(pytz.utc).isoformat()
if to_timestamp is not None:
params["to"] = to_timestamp.astimezone(pytz.utc).isoformat()
return await self._create_get("account/trades", params = params, signed = True)
async def get_account_trade(self, trade_id: str) -> dict:
return await self._create_get("account/trades/" + trade_id, signed = True)
async def get_account_trading_volume(self) -> dict:
return await self._create_get("account/trading-volume", signed = True)
async def create_market_order(self, pair: Pair, side: enums.OrderSide, amount: str, client_id: str = None) -> dict:
data = {
"instrument_code": map_pair(pair),
"side": side.value,
"type": enums.OrderType.MARKET.value,
"amount": amount
}
if client_id is not None:
data['client_id'] = client_id
return await self._create_post("account/orders", data = data, signed = True)
async def create_limit_order(self, pair: Pair, side: enums.OrderSide, amount: str, limit_price: str,
time_in_force: enums.TimeInForce = None, client_id: str = None) -> dict:
data = {
"instrument_code": map_pair(pair),
"side": side.value,
"type": enums.OrderType.LIMIT.value,
"amount": amount,
"price": limit_price
}
if client_id is not None:
data['client_id'] = client_id
if time_in_force is not None:
data['time_in_force'] = time_in_force.value
return await self._create_post("account/orders", data = data, signed = True)
async def create_stop_limit_order(self, pair: Pair, side: enums.OrderSide, amount: str, limit_price: str,
stop_price: str,
time_in_force: enums.TimeInForce = None, client_id: str = None) -> dict:
data = {
"instrument_code": map_pair(pair),
"side": side.value,
"type": enums.OrderType.STOP_LIMIT.value,
"amount": amount,
"price": limit_price,
"trigger_price": stop_price
}
if client_id is not None:
data['client_id'] = client_id
if time_in_force is not None:
data['time_in_force'] = time_in_force.value
return await self._create_post("account/orders", data = data, signed = True)
async def delete_account_orders(self, pair: Pair = None, ids: List[str] = None) -> dict:
params = {}
if pair is not None:
params["instrument_code"] = map_pair(pair)
if ids is not None:
params['ids'] = ','.join(ids)
return await self._create_delete("account/orders", params = params, signed = True)
async def delete_account_order(self, order_id: str = None, client_id: str = None) -> dict:
if order_id is None and client_id is None:
raise BitpandaException('One of order_id/client_id has to be provided.')
if order_id is not None and client_id is not None:
raise BitpandaException('Only one of order_id/client_id can be provided.')
if order_id is not None:
return await self._create_delete("account/orders/" + order_id, signed = True)
else:
return await self._create_delete("account/orders/client/" + client_id, signed = True)
async def update_order(self, amount: str, order_id: str = None, client_id: str = None) -> dict:
if order_id is None and client_id is None:
raise BitpandaException('One of order_id/client_id has to be provided.')
if order_id is not None and client_id is not None:
raise BitpandaException('Only one of order_id/client_id can be provided.')
data = {
"amount": amount
}
if order_id is not None:
return await self._create_put("account/orders/" + order_id, data = data, signed = True)
else:
return await self._create_put("account/orders/client/" + client_id, data = data, signed = True)
async def get_candlesticks(self, pair: Pair, unit: enums.TimeUnit, period: str, from_timestamp: datetime.datetime,
to_timestamp: datetime.datetime) -> dict:
params = {
"unit": unit.value,
"period": period,
"from": from_timestamp.astimezone(pytz.utc).isoformat(),
"to": to_timestamp.astimezone(pytz.utc).isoformat(),
}
return await self._create_get("candlesticks/" + map_pair(pair), params = params)
async def get_instruments(self) -> dict:
return await self._create_get("instruments")
async def get_order_book(self, pair: Pair, level: str = None, depth: str = None) -> dict:
params = BitpandaClient._clean_request_params({
"level": level,
"depth": depth
})
return await self._create_get("order-book/" + map_pair(pair), params = params)
async def get_time(self) -> dict:
return await self._create_get("time")
async def get_market_tickers(self) -> dict:
return await self._create_get("market-ticker")
async def get_market_ticker(self, pair: Pair) -> dict:
return await self._create_get("market-ticker/" + map_pair(pair))
async def get_price_tick(self, pair: Pair, from_timestamp: datetime.datetime = None,
to_timestamp: datetime.datetime = None) -> dict:
params = {}
if from_timestamp is not None:
params['from'] = from_timestamp.astimezone(pytz.utc).isoformat()
if to_timestamp is not None:
params['to'] = to_timestamp.astimezone(pytz.utc).isoformat()
return await self._create_get("price-ticks/" + map_pair(pair), params = params)
async def create_deposit_crypto_address(self, currency: str) -> dict:
data = {
"currency": currency
}
return await self._create_post("account/deposit/crypto", data = data, signed = True)
async def get_deposit_crypto_address(self, currency: str) -> dict:
return await self._create_get("account/deposit/crypto/" + currency, signed = True)
async def get_fiat_deposit_info(self) -> dict:
return await self._create_get("account/deposit/fiat/EUR", signed = True)
async def withdraw_crypto(self, currency: str, amount: str, address: str, destination_tag: str = None) -> dict:
data = {
'currency': currency,
'amount': amount,
'recipient': {
'address': address
}
}
if destination_tag is not None:
data['recipient']['destination_tag'] = destination_tag
return await self._create_post("account/withdraw/crypto", data = data, signed = True)
async def withdraw_fiat(self, currency: str, amount: str, payout_account_id: str) -> dict:
data = {
'currency': currency,
'amount': amount,
'payout_account_id': payout_account_id
}
return await self._create_post("account/withdraw/fiat", data = data, signed = True)
async def get_deposits(self, from_timestamp: datetime.datetime = None,
to_timestamp: datetime.datetime = None,
currency: str = None,
max_page_size: int = None,
cursor: int = None) -> dict:
params = self._clean_request_params({
'currency_code': currency,
'max_page_size': max_page_size,
'cursor': cursor
})
if from_timestamp is not None:
params['from'] = from_timestamp.astimezone(pytz.utc).isoformat()
if to_timestamp is not None:
params['to'] = to_timestamp.astimezone(pytz.utc).isoformat()
return await self._create_get("account/deposits", params = params, signed = True)
async def get_bitpanda_deposits(self, from_timestamp: datetime.datetime = None,
to_timestamp: datetime.datetime = None,
currency: str = None,
max_page_size: int = None,
cursor: int = None) -> dict:
params = self._clean_request_params({
'currency_code': currency,
'max_page_size': max_page_size,
'cursor': cursor
})
if from_timestamp is not None:
params['from'] = from_timestamp.astimezone(pytz.utc).isoformat()
if to_timestamp is not None:
params['to'] = to_timestamp.astimezone(pytz.utc).isoformat()
return await self._create_get("account/deposits/bitpanda", params = params, signed = True)
async def get_withdrawals(self, from_timestamp: datetime.datetime = None,
to_timestamp: datetime.datetime = None,
currency: str = None,
max_page_size: int = None,
cursor: int = None) -> dict:
params = self._clean_request_params({
'currency_code': currency,
'max_page_size': max_page_size,
'cursor': cursor
})
if from_timestamp is not None:
params['from'] = from_timestamp.astimezone(pytz.utc).isoformat()
if to_timestamp is not None:
params['to'] = to_timestamp.astimezone(pytz.utc).isoformat()
return await self._create_get("account/withdrawals", params = params, signed = True)
async def get_bitpanda_withdrawals(self, from_timestamp: datetime.datetime = None,
to_timestamp: datetime.datetime = None,
currency: str = None,
max_page_size: int = None,
cursor: int = None) -> dict:
params = self._clean_request_params({
'currency_code': currency,
'max_page_size': max_page_size,
'cursor': cursor
})
if from_timestamp is not None:
params['from'] = from_timestamp.astimezone(pytz.utc).isoformat()
if to_timestamp is not None:
params['to'] = to_timestamp.astimezone(pytz.utc).isoformat()
return await self._create_get("account/withdrawals/bitpanda", params = params, signed = True)
async def toggle_best_fee_collection(self, indicator: bool) -> dict:
data = {
'collect_fees_in_best': indicator
}
return await self._create_post("account/fees", data = data, signed = True)
async def auto_cancel_all_orders(self, timeout_ms: int) -> dict:
data = {
'timeout': timeout_ms
}
return await self._create_post("account/orders/cancel-all-after", data = data, signed = True)
async def delete_auto_cancel_all_orders(self) -> dict:
return await self._create_delete("account/orders/cancel-all-after", signed = True) | 0.751648 | 0.162148 |
from typing import List, Optional
from qiskit.circuit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library.standard_gates import MCXGate
class OR(QuantumCircuit):
r"""A circuit implementing the logical OR operation on a number of qubits.
For the OR operation the state :math:`|1\rangle` is interpreted as ``True``. The result
qubit is flipped, if the state of any variable qubit is ``True``. The OR is implemented using
a multi-open-controlled X gate (i.e. flips if the state is :math:`|0\rangle`) and
applying an X gate on the result qubit.
Using a list of flags, qubits can be skipped or negated.
The OR gate without special flags:
.. jupyter-execute::
:hide-code:
from qiskit.circuit.library import OR
import qiskit.tools.jupyter
circuit = OR(5)
%circuit_library_info circuit
Using flags we can negate qubits or skip them. For instance, if we have 5 qubits and want to
return ``True`` if the first qubit is ``False`` or one of the last two are ``True`` we use the
flags ``[-1, 0, 0, 1, 1]``.
.. jupyter-execute::
:hide-code:
from qiskit.circuit.library import OR
import qiskit.tools.jupyter
circuit = OR(5, flags=[-1, 0, 0, 1, 1])
%circuit_library_info circuit
"""
def __init__(
self,
num_variable_qubits: int,
flags: Optional[List[int]] = None,
mcx_mode: str = "noancilla",
) -> None:
"""Create a new logical OR circuit.
Args:
num_variable_qubits: The qubits of which the OR is computed. The result will be written
into an additional result qubit.
flags: A list of +1/0/-1 marking negations or omissions of qubits.
mcx_mode: The mode to be used to implement the multi-controlled X gate.
"""
# store num_variables_qubits and flags
self.num_variable_qubits = num_variable_qubits
self.flags = flags
# add registers
qr_variable = QuantumRegister(num_variable_qubits, name="variable")
qr_result = QuantumRegister(1, name="result")
super().__init__(qr_variable, qr_result, name="or")
# determine the control qubits: all that have a nonzero flag
flags = flags or [1] * num_variable_qubits
control_qubits = [q for q, flag in zip(qr_variable, flags) if flag != 0]
# determine the qubits that need to be flipped (if a flag is > 0)
flip_qubits = [q for q, flag in zip(qr_variable, flags) if flag > 0]
# determine the number of ancillas
self.num_ancilla_qubits = MCXGate.get_num_ancilla_qubits(len(control_qubits), mode=mcx_mode)
if self.num_ancilla_qubits > 0:
qr_ancilla = QuantumRegister(self.num_ancilla_qubits, "ancilla")
self.add_register(qr_ancilla)
else:
qr_ancilla = []
self.x(qr_result)
if len(flip_qubits) > 0:
self.x(flip_qubits)
self.mcx(control_qubits, qr_result[:], qr_ancilla[:], mode=mcx_mode)
if len(flip_qubits) > 0:
self.x(flip_qubits) | qiskit/circuit/library/boolean_logic/quantum_or.py | from typing import List, Optional
from qiskit.circuit import QuantumRegister, QuantumCircuit
from qiskit.circuit.library.standard_gates import MCXGate
class OR(QuantumCircuit):
r"""A circuit implementing the logical OR operation on a number of qubits.
For the OR operation the state :math:`|1\rangle` is interpreted as ``True``. The result
qubit is flipped, if the state of any variable qubit is ``True``. The OR is implemented using
a multi-open-controlled X gate (i.e. flips if the state is :math:`|0\rangle`) and
applying an X gate on the result qubit.
Using a list of flags, qubits can be skipped or negated.
The OR gate without special flags:
.. jupyter-execute::
:hide-code:
from qiskit.circuit.library import OR
import qiskit.tools.jupyter
circuit = OR(5)
%circuit_library_info circuit
Using flags we can negate qubits or skip them. For instance, if we have 5 qubits and want to
return ``True`` if the first qubit is ``False`` or one of the last two are ``True`` we use the
flags ``[-1, 0, 0, 1, 1]``.
.. jupyter-execute::
:hide-code:
from qiskit.circuit.library import OR
import qiskit.tools.jupyter
circuit = OR(5, flags=[-1, 0, 0, 1, 1])
%circuit_library_info circuit
"""
def __init__(
self,
num_variable_qubits: int,
flags: Optional[List[int]] = None,
mcx_mode: str = "noancilla",
) -> None:
"""Create a new logical OR circuit.
Args:
num_variable_qubits: The qubits of which the OR is computed. The result will be written
into an additional result qubit.
flags: A list of +1/0/-1 marking negations or omissions of qubits.
mcx_mode: The mode to be used to implement the multi-controlled X gate.
"""
# store num_variables_qubits and flags
self.num_variable_qubits = num_variable_qubits
self.flags = flags
# add registers
qr_variable = QuantumRegister(num_variable_qubits, name="variable")
qr_result = QuantumRegister(1, name="result")
super().__init__(qr_variable, qr_result, name="or")
# determine the control qubits: all that have a nonzero flag
flags = flags or [1] * num_variable_qubits
control_qubits = [q for q, flag in zip(qr_variable, flags) if flag != 0]
# determine the qubits that need to be flipped (if a flag is > 0)
flip_qubits = [q for q, flag in zip(qr_variable, flags) if flag > 0]
# determine the number of ancillas
self.num_ancilla_qubits = MCXGate.get_num_ancilla_qubits(len(control_qubits), mode=mcx_mode)
if self.num_ancilla_qubits > 0:
qr_ancilla = QuantumRegister(self.num_ancilla_qubits, "ancilla")
self.add_register(qr_ancilla)
else:
qr_ancilla = []
self.x(qr_result)
if len(flip_qubits) > 0:
self.x(flip_qubits)
self.mcx(control_qubits, qr_result[:], qr_ancilla[:], mode=mcx_mode)
if len(flip_qubits) > 0:
self.x(flip_qubits) | 0.966252 | 0.843959 |
import os
import subprocess
import time
import transmissionrpc
def get_rpc_client():
port = 9292
password = r"{<PASSWORD>"
username = ""
address = '0.0.0.0'
tc = transmissionrpc.Client(address=address,
port=port,
user=username,
password=password)
return tc
def rpc_usage1():
'''
Tests addition/removal of torrent to transmission-daemon
'''
tc = get_rpc_client()
path = r'/home/rxhernandez/Downloads/ubuntu-19.10-desktop-amd64.iso.torrent'
'''
had to reverse engineer the following
t._fields
{'hashString': Field(value='e2467cbf021192c241367b892230dc1e05c0580e', dirty=False), 'id': Field(value=7, dirty=False), 'name': Field(value='ubuntu-19.10-desktop-amd64.iso', dirty=False)}
'''
torrent = tc.add_torrent(path)
print(tc.get_torrents(), flush=True)
tc.remove_torrent((torrent.id,))
print(tc.get_torrents())
def get_torrent_hash(path):
cmd = 'transmission-show'
args = [cmd, path]
byte_encoded_output = subprocess.check_output(args)
s = byte_encoded_output.decode('utf-8')
hash_line = None
for line in s.split('\n'):
if 'hash' in line.lower():
hash_line = line
if hash_line is None:
raise ValueError('The hash of the torrent could not be found')
hash = hash_line.split()[1]
return hash
def remove_any_existing_torrents(tc, path):
hash = get_torrent_hash(path)
for torrent in tc.get_torrents():
if torrent.hashString == hash:
print(f"Removing torrent with the name: {torrent.name}")
tc.remove_torrent((torrent.id,), delete_data=True)
return
print(f"No torrent found corresponding to the hash {hash} and path {path}")
def printed_progress(fn):
last_progress_update = 0
last_progress = -1
def wrapper(tc, torrent):
nonlocal last_progress_update
nonlocal last_progress
progress = fn(tc, torrent)
no_progress = last_progress == progress
substantial_progress = last_progress_update != int(progress)
if (int(progress) % 2 == 0 and substantial_progress) or no_progress:
print(progress)
last_progress_update = int(progress)
last_progress = progress
if no_progress:
print()
return progress
return wrapper
@printed_progress
def get_torrent_progress(tc, torrent):
try:
progress = tc.get_torrent(torrent.id).progress
except KeyError as e:
import traceback
print(traceback.format_exc())
return 0
return progress
def rpc_usage2():
tc = get_rpc_client()
#path = str(os.path.join(os.getcwd(), 'test.torrent'))
path = r'/home/rxhernandez/Downloads/ubuntu-19.10-desktop-amd64.iso.torrent'
remove_any_existing_torrents(tc, path)
torrent = tc.add_torrent(path)
progress = 0
while progress < 100:
progress = get_torrent_progress(tc, torrent)
print('Torrent Completed Downloading!')
tc.remove_torrent((torrent.id,), delete_data=True)
if __name__ == '__main__':
rpc_usage2() | sandbox/pdp2/TransmissionRpcTest.py | import os
import subprocess
import time
import transmissionrpc
def get_rpc_client():
port = 9292
password = r"{<PASSWORD>"
username = ""
address = '0.0.0.0'
tc = transmissionrpc.Client(address=address,
port=port,
user=username,
password=password)
return tc
def rpc_usage1():
'''
Tests addition/removal of torrent to transmission-daemon
'''
tc = get_rpc_client()
path = r'/home/rxhernandez/Downloads/ubuntu-19.10-desktop-amd64.iso.torrent'
'''
had to reverse engineer the following
t._fields
{'hashString': Field(value='e2467cbf021192c241367b892230dc1e05c0580e', dirty=False), 'id': Field(value=7, dirty=False), 'name': Field(value='ubuntu-19.10-desktop-amd64.iso', dirty=False)}
'''
torrent = tc.add_torrent(path)
print(tc.get_torrents(), flush=True)
tc.remove_torrent((torrent.id,))
print(tc.get_torrents())
def get_torrent_hash(path):
cmd = 'transmission-show'
args = [cmd, path]
byte_encoded_output = subprocess.check_output(args)
s = byte_encoded_output.decode('utf-8')
hash_line = None
for line in s.split('\n'):
if 'hash' in line.lower():
hash_line = line
if hash_line is None:
raise ValueError('The hash of the torrent could not be found')
hash = hash_line.split()[1]
return hash
def remove_any_existing_torrents(tc, path):
hash = get_torrent_hash(path)
for torrent in tc.get_torrents():
if torrent.hashString == hash:
print(f"Removing torrent with the name: {torrent.name}")
tc.remove_torrent((torrent.id,), delete_data=True)
return
print(f"No torrent found corresponding to the hash {hash} and path {path}")
def printed_progress(fn):
last_progress_update = 0
last_progress = -1
def wrapper(tc, torrent):
nonlocal last_progress_update
nonlocal last_progress
progress = fn(tc, torrent)
no_progress = last_progress == progress
substantial_progress = last_progress_update != int(progress)
if (int(progress) % 2 == 0 and substantial_progress) or no_progress:
print(progress)
last_progress_update = int(progress)
last_progress = progress
if no_progress:
print()
return progress
return wrapper
@printed_progress
def get_torrent_progress(tc, torrent):
try:
progress = tc.get_torrent(torrent.id).progress
except KeyError as e:
import traceback
print(traceback.format_exc())
return 0
return progress
def rpc_usage2():
tc = get_rpc_client()
#path = str(os.path.join(os.getcwd(), 'test.torrent'))
path = r'/home/rxhernandez/Downloads/ubuntu-19.10-desktop-amd64.iso.torrent'
remove_any_existing_torrents(tc, path)
torrent = tc.add_torrent(path)
progress = 0
while progress < 100:
progress = get_torrent_progress(tc, torrent)
print('Torrent Completed Downloading!')
tc.remove_torrent((torrent.id,), delete_data=True)
if __name__ == '__main__':
rpc_usage2() | 0.137388 | 0.090937 |
from genesis_upgrade_tests.test_base import GenesisHeightBasedSimpleTestsCase
from test_framework.height_based_test_framework import SimpleTestDefinition
from test_framework.script import CScript, OP_CAT, OP_DUP
from test_framework.cdefs import MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS, MAX_STACK_ELEMENTS_BEFORE_GENESIS, ELEMENT_OVERHEAD
class MaxStackSizeTestWithCustomSize(GenesisHeightBasedSimpleTestsCase):
# In all test cases, we have 2 elements on stack, which means that we have to add 2*32 bytes for covering ELEMENT_OVERHEAD
MAX_STACK_MEMORY_USAGE_POLICY = 500
MAX_STACK_MEMORY_USAGE_CONSENSUS = 600
ARGS = GenesisHeightBasedSimpleTestsCase.ARGS + \
['-maxstackmemoryusagepolicy=%d' % (MAX_STACK_MEMORY_USAGE_POLICY + 2 * ELEMENT_OVERHEAD),
'-maxstackmemoryusageconsensus=%d' % (MAX_STACK_MEMORY_USAGE_CONSENSUS + 2 * ELEMENT_OVERHEAD),
'-banscore=1000000', '-whitelist=127.0.0.1']
NAME = "Max stack size with custom maxstackmemoryusagepolicy and maxstackmemoryusageconsensus"
TESTS = [
# Before genesis, sum of concatenating elements sizes should be <= 520.
# For following cases, UTXO is made before genesis.
SimpleTestDefinition("PRE-GENESIS", CScript([b"a"*(MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS - 1), b"b", OP_CAT]),
"PRE-GENESIS", b""
),
SimpleTestDefinition("PRE-GENESIS", CScript([b"a"*MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS, b"b", OP_CAT]),
"PRE-GENESIS", b"",
p2p_reject_reason=b'genesis-script-verify-flag-failed (Push value size limit exceeded)',
block_reject_reason=b'blk-bad-inputs'
),
SimpleTestDefinition("PRE-GENESIS", CScript([b"a"*(MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS - 1), b"b", OP_CAT]),
"MEMPOOL AT GENESIS", b""
),
SimpleTestDefinition("PRE-GENESIS", CScript([b"a"*MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS, b"b", OP_CAT]),
"MEMPOOL AT GENESIS", b"",
p2p_reject_reason=b'genesis-script-verify-flag-failed (Push value size limit exceeded)',
block_reject_reason=b'blk-bad-inputs'
),
SimpleTestDefinition("PRE-GENESIS", CScript([b"a"*(MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS - 1), b"b", OP_CAT]),
"GENESIS", b""
),
SimpleTestDefinition("PRE-GENESIS", CScript([b"a"*MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS, b"b", OP_CAT]),
"GENESIS", b"",
p2p_reject_reason=b'genesis-script-verify-flag-failed (Push value size limit exceeded)',
block_reject_reason=b'blk-bad-inputs'
),
# UTXO is in block at height "MEMPOOL AT GENESIS" which means pre genesis rules apply to this block
SimpleTestDefinition("MEMPOOL AT GENESIS", CScript([b"a"*(MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS - 1), b"b", OP_CAT]),
"GENESIS", b"",
),
SimpleTestDefinition("MEMPOOL AT GENESIS", CScript([b"a"*MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS, b"b", OP_CAT]),
"GENESIS", b"",
p2p_reject_reason=b'genesis-script-verify-flag-failed (Push value size limit exceeded)',
block_reject_reason=b'blk-bad-inputs'
),
# For following cases, UTXO is made after genesis, so new rules apply here (500 bytes for policy and 600 bytes for consensus)
# At some point of performing OP_CAT the stack size is size_of_first + 2 * size_of_second which in our case produce stack oversized error
SimpleTestDefinition("GENESIS", CScript([b"a"*(MAX_STACK_MEMORY_USAGE_POLICY - 1), b"b", OP_CAT]),
"GENESIS", b""
),
SimpleTestDefinition("GENESIS", CScript([b"a"*MAX_STACK_MEMORY_USAGE_POLICY, b"b", OP_CAT]),
"GENESIS", b"",
p2p_reject_reason=b'non-mandatory-script-verify-flag (Stack size limit exceeded)',
block_reject_reason=None
),
SimpleTestDefinition("GENESIS", CScript([b"a"*(MAX_STACK_MEMORY_USAGE_CONSENSUS - 1), b"b", OP_CAT]),
"GENESIS", b"",
p2p_reject_reason=b'non-mandatory-script-verify-flag (Stack size limit exceeded)',
block_reject_reason=None
),
SimpleTestDefinition("GENESIS", CScript([b"a"*MAX_STACK_MEMORY_USAGE_CONSENSUS, b"b", OP_CAT]),
"GENESIS", b"",
p2p_reject_reason=b'mandatory-script-verify-flag-failed (Stack size limit exceeded)',
block_reject_reason=b'blk-bad-inputs'
),
]
class MaxStackSizeTestWithElementsCount(GenesisHeightBasedSimpleTestsCase):
ARGS = GenesisHeightBasedSimpleTestsCase.ARGS + ['-banscore=1000000', '-whitelist=127.0.0.1']
NAME = "Max stack size before genesis: MAX_STACK_ELEMENTS_COUNT limit"
TESTS = [
# Script did not clean its stack means that stack size limit checks were successful
# Usage of OP_DROP here would cause problems with MAX_OPS_PER_SCRIPT which is not configurable before genesis.
SimpleTestDefinition("PRE-GENESIS", CScript([b"a"]*MAX_STACK_ELEMENTS_BEFORE_GENESIS),
"PRE-GENESIS", b"",
p2p_reject_reason=b'non-mandatory-script-verify-flag (Script did not clean its stack)',
block_reject_reason=None
),
SimpleTestDefinition("PRE-GENESIS", CScript([b"a"]*(MAX_STACK_ELEMENTS_BEFORE_GENESIS + 1)),
"PRE-GENESIS", b"",
p2p_reject_reason=b'genesis-script-verify-flag-failed (Stack size limit exceeded)',
block_reject_reason=b'blk-bad-inputs'
),
SimpleTestDefinition("GENESIS", CScript([b"a"]*(MAX_STACK_ELEMENTS_BEFORE_GENESIS + 1)),
"GENESIS", b"",
p2p_reject_reason=b'non-mandatory-script-verify-flag (Script did not clean its stack)',
block_reject_reason=None
),
]
class MaxStackSizeTest(GenesisHeightBasedSimpleTestsCase):
ARGS = GenesisHeightBasedSimpleTestsCase.ARGS + ['-banscore=1000000', '-whitelist=127.0.0.1']
NAME = "Max stack size with default policy and consensus size"
# After genesis, default max stack memory usage is MAX_INT. For policy 100 MB.
# We mock big stack with the help of OP_DUP and OP_CAT combination which generates strings with the size of powers of 2.
# Transactions: 2^26 = 67 MB bytes (OK), 2^27 = 134 MB bytes (FAIL because > 100 MB)
TESTS = [
SimpleTestDefinition("PRE-GENESIS", CScript([b"a"] + [OP_DUP, OP_CAT]*18),
"PRE-GENESIS", b"",
p2p_reject_reason=b'genesis-script-verify-flag-failed (Push value size limit exceeded)',
block_reject_reason=b'blk-bad-inputs'
),
SimpleTestDefinition("GENESIS", CScript([b"a"] + [OP_DUP, OP_CAT]*26),
"GENESIS", b""
),
] | test/functional/genesis_upgrade_tests/max_stack_size.py |
from genesis_upgrade_tests.test_base import GenesisHeightBasedSimpleTestsCase
from test_framework.height_based_test_framework import SimpleTestDefinition
from test_framework.script import CScript, OP_CAT, OP_DUP
from test_framework.cdefs import MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS, MAX_STACK_ELEMENTS_BEFORE_GENESIS, ELEMENT_OVERHEAD
class MaxStackSizeTestWithCustomSize(GenesisHeightBasedSimpleTestsCase):
# In all test cases, we have 2 elements on stack, which means that we have to add 2*32 bytes for covering ELEMENT_OVERHEAD
MAX_STACK_MEMORY_USAGE_POLICY = 500
MAX_STACK_MEMORY_USAGE_CONSENSUS = 600
ARGS = GenesisHeightBasedSimpleTestsCase.ARGS + \
['-maxstackmemoryusagepolicy=%d' % (MAX_STACK_MEMORY_USAGE_POLICY + 2 * ELEMENT_OVERHEAD),
'-maxstackmemoryusageconsensus=%d' % (MAX_STACK_MEMORY_USAGE_CONSENSUS + 2 * ELEMENT_OVERHEAD),
'-banscore=1000000', '-whitelist=127.0.0.1']
NAME = "Max stack size with custom maxstackmemoryusagepolicy and maxstackmemoryusageconsensus"
TESTS = [
# Before genesis, sum of concatenating elements sizes should be <= 520.
# For following cases, UTXO is made before genesis.
SimpleTestDefinition("PRE-GENESIS", CScript([b"a"*(MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS - 1), b"b", OP_CAT]),
"PRE-GENESIS", b""
),
SimpleTestDefinition("PRE-GENESIS", CScript([b"a"*MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS, b"b", OP_CAT]),
"PRE-GENESIS", b"",
p2p_reject_reason=b'genesis-script-verify-flag-failed (Push value size limit exceeded)',
block_reject_reason=b'blk-bad-inputs'
),
SimpleTestDefinition("PRE-GENESIS", CScript([b"a"*(MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS - 1), b"b", OP_CAT]),
"MEMPOOL AT GENESIS", b""
),
SimpleTestDefinition("PRE-GENESIS", CScript([b"a"*MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS, b"b", OP_CAT]),
"MEMPOOL AT GENESIS", b"",
p2p_reject_reason=b'genesis-script-verify-flag-failed (Push value size limit exceeded)',
block_reject_reason=b'blk-bad-inputs'
),
SimpleTestDefinition("PRE-GENESIS", CScript([b"a"*(MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS - 1), b"b", OP_CAT]),
"GENESIS", b""
),
SimpleTestDefinition("PRE-GENESIS", CScript([b"a"*MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS, b"b", OP_CAT]),
"GENESIS", b"",
p2p_reject_reason=b'genesis-script-verify-flag-failed (Push value size limit exceeded)',
block_reject_reason=b'blk-bad-inputs'
),
# UTXO is in block at height "MEMPOOL AT GENESIS" which means pre genesis rules apply to this block
SimpleTestDefinition("MEMPOOL AT GENESIS", CScript([b"a"*(MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS - 1), b"b", OP_CAT]),
"GENESIS", b"",
),
SimpleTestDefinition("MEMPOOL AT GENESIS", CScript([b"a"*MAX_SCRIPT_ELEMENT_SIZE_BEFORE_GENESIS, b"b", OP_CAT]),
"GENESIS", b"",
p2p_reject_reason=b'genesis-script-verify-flag-failed (Push value size limit exceeded)',
block_reject_reason=b'blk-bad-inputs'
),
# For following cases, UTXO is made after genesis, so new rules apply here (500 bytes for policy and 600 bytes for consensus)
# At some point of performing OP_CAT the stack size is size_of_first + 2 * size_of_second which in our case produce stack oversized error
SimpleTestDefinition("GENESIS", CScript([b"a"*(MAX_STACK_MEMORY_USAGE_POLICY - 1), b"b", OP_CAT]),
"GENESIS", b""
),
SimpleTestDefinition("GENESIS", CScript([b"a"*MAX_STACK_MEMORY_USAGE_POLICY, b"b", OP_CAT]),
"GENESIS", b"",
p2p_reject_reason=b'non-mandatory-script-verify-flag (Stack size limit exceeded)',
block_reject_reason=None
),
SimpleTestDefinition("GENESIS", CScript([b"a"*(MAX_STACK_MEMORY_USAGE_CONSENSUS - 1), b"b", OP_CAT]),
"GENESIS", b"",
p2p_reject_reason=b'non-mandatory-script-verify-flag (Stack size limit exceeded)',
block_reject_reason=None
),
SimpleTestDefinition("GENESIS", CScript([b"a"*MAX_STACK_MEMORY_USAGE_CONSENSUS, b"b", OP_CAT]),
"GENESIS", b"",
p2p_reject_reason=b'mandatory-script-verify-flag-failed (Stack size limit exceeded)',
block_reject_reason=b'blk-bad-inputs'
),
]
class MaxStackSizeTestWithElementsCount(GenesisHeightBasedSimpleTestsCase):
ARGS = GenesisHeightBasedSimpleTestsCase.ARGS + ['-banscore=1000000', '-whitelist=127.0.0.1']
NAME = "Max stack size before genesis: MAX_STACK_ELEMENTS_COUNT limit"
TESTS = [
# Script did not clean its stack means that stack size limit checks were successful
# Usage of OP_DROP here would cause problems with MAX_OPS_PER_SCRIPT which is not configurable before genesis.
SimpleTestDefinition("PRE-GENESIS", CScript([b"a"]*MAX_STACK_ELEMENTS_BEFORE_GENESIS),
"PRE-GENESIS", b"",
p2p_reject_reason=b'non-mandatory-script-verify-flag (Script did not clean its stack)',
block_reject_reason=None
),
SimpleTestDefinition("PRE-GENESIS", CScript([b"a"]*(MAX_STACK_ELEMENTS_BEFORE_GENESIS + 1)),
"PRE-GENESIS", b"",
p2p_reject_reason=b'genesis-script-verify-flag-failed (Stack size limit exceeded)',
block_reject_reason=b'blk-bad-inputs'
),
SimpleTestDefinition("GENESIS", CScript([b"a"]*(MAX_STACK_ELEMENTS_BEFORE_GENESIS + 1)),
"GENESIS", b"",
p2p_reject_reason=b'non-mandatory-script-verify-flag (Script did not clean its stack)',
block_reject_reason=None
),
]
class MaxStackSizeTest(GenesisHeightBasedSimpleTestsCase):
ARGS = GenesisHeightBasedSimpleTestsCase.ARGS + ['-banscore=1000000', '-whitelist=127.0.0.1']
NAME = "Max stack size with default policy and consensus size"
# After genesis, default max stack memory usage is MAX_INT. For policy 100 MB.
# We mock big stack with the help of OP_DUP and OP_CAT combination which generates strings with the size of powers of 2.
# Transactions: 2^26 = 67 MB bytes (OK), 2^27 = 134 MB bytes (FAIL because > 100 MB)
TESTS = [
SimpleTestDefinition("PRE-GENESIS", CScript([b"a"] + [OP_DUP, OP_CAT]*18),
"PRE-GENESIS", b"",
p2p_reject_reason=b'genesis-script-verify-flag-failed (Push value size limit exceeded)',
block_reject_reason=b'blk-bad-inputs'
),
SimpleTestDefinition("GENESIS", CScript([b"a"] + [OP_DUP, OP_CAT]*26),
"GENESIS", b""
),
] | 0.446253 | 0.300771 |
import io
import os
from typing import NoReturn
import pytest
from engine.boards import Board, GenericBoard
from engine.constants import BOARDS
from tests import TEST_DIR, use_test_dir
from tests.engine import MOCK_CONFIG
class TestGenericBoard(object):
def setup_class(self) -> NoReturn:
self.conf_path = MOCK_CONFIG
self.p_name = "tmp"
self.res_path = os.path.join(TEST_DIR, self.p_name)
def setup_method(self) -> NoReturn:
self.board = GenericBoard(self.conf_path)
def test_GenericBoard(self) -> NoReturn:
with pytest.raises(AttributeError):
self.board.__dict__ # has no dict as __slots__
assert self.board.__slots__
def test_config_path(self) -> NoReturn:
assert self.board.config_path == self.conf_path, "invalid configs"
with pytest.raises(FileNotFoundError):
self.board.config_path = self.conf_path + ")@!O##K(D"
assert isinstance(self.board._v, dict), "invalid board configuration"
v = self.board._v
self.board._v = None
self.board.config_path = self.conf_path
assert self.board._v == v, "board isn't reseted"
# NOTE due to bug with passing params
def test_project_name(self) -> NoReturn:
for name in (self.p_name, (self.p_name,), ((self.p_name,),)):
self.board.project_name = name
assert self.board.project_name == self.p_name
def test_params(self) -> NoReturn:
params = self.board.params
assert params
assert isinstance(params, dict)
for key in params.keys():
assert isinstance(key, str)
def _test_as_archive(self) -> NoReturn:
with pytest.raises(AttributeError):
_ = self.board.as_archive
res = self.board.generate().as_archive
assert res
assert isinstance(res, io.Bytes)
def test_reset(self) -> NoReturn:
attributes = ("_sdc", "_qpf", "_qsf", "_v", "_func", "_functions",
"_mips_qsf", "_mips_v")
for attr in attributes:
delattr(self.board, attr)
assert not hasattr(self.board, attr), "attribute wasn't deleted"
self.board.reset()
for attr in attributes:
assert hasattr(self.board, attr), "attributes isn't reseted"
# [minor] TODO finish test
def test_setup(self) -> NoReturn:
board = self.board.setup()
assert not hasattr(board, "configs")
# [minor] TODO add more cases
def test_generate(self) -> NoReturn:
def check_generated(board: dict) -> NoReturn:
assert isinstance(board, GenericBoard)
assert board.configs
assert isinstance(board.configs, dict)
check_generated(self.board.generate())
check_generated(self.board.generate())
check_generated(self.board.generate(
flt={'key': True},
func={'Seven': True}
))
check_generated(self.board.generate(self.p_name))
check_generated(self.board.setup().generate())
def test_dump(self) -> NoReturn:
with pytest.raises(AttributeError):
self.board.dump()
with use_test_dir():
self.board.generate().dump(self.res_path)
assert os.path.exists(self.res_path)
for filename in self.board.configs:
assert os.path.exists(os.path.join(self.res_path, filename))
def test_archive(self) -> NoReturn:
with pytest.raises(AttributeError):
self.board.archive()
with use_test_dir():
self.board.generate().archive(self.res_path)
assert os.path.exists(self.res_path + ".tar")
class TestBoard(object):
def test_Board(self) -> NoReturn:
board = Board(BOARDS[0])
with pytest.raises(AttributeError):
board.__dict__ # has no dict as __slots__
assert board.__slots__
with pytest.raises(ValueError):
Board(BOARDS[0] * 2) # there is no such board | tests/engine/test_boards.py |
import io
import os
from typing import NoReturn
import pytest
from engine.boards import Board, GenericBoard
from engine.constants import BOARDS
from tests import TEST_DIR, use_test_dir
from tests.engine import MOCK_CONFIG
class TestGenericBoard(object):
def setup_class(self) -> NoReturn:
self.conf_path = MOCK_CONFIG
self.p_name = "tmp"
self.res_path = os.path.join(TEST_DIR, self.p_name)
def setup_method(self) -> NoReturn:
self.board = GenericBoard(self.conf_path)
def test_GenericBoard(self) -> NoReturn:
with pytest.raises(AttributeError):
self.board.__dict__ # has no dict as __slots__
assert self.board.__slots__
def test_config_path(self) -> NoReturn:
assert self.board.config_path == self.conf_path, "invalid configs"
with pytest.raises(FileNotFoundError):
self.board.config_path = self.conf_path + ")@!O##K(D"
assert isinstance(self.board._v, dict), "invalid board configuration"
v = self.board._v
self.board._v = None
self.board.config_path = self.conf_path
assert self.board._v == v, "board isn't reseted"
# NOTE due to bug with passing params
def test_project_name(self) -> NoReturn:
for name in (self.p_name, (self.p_name,), ((self.p_name,),)):
self.board.project_name = name
assert self.board.project_name == self.p_name
def test_params(self) -> NoReturn:
params = self.board.params
assert params
assert isinstance(params, dict)
for key in params.keys():
assert isinstance(key, str)
def _test_as_archive(self) -> NoReturn:
with pytest.raises(AttributeError):
_ = self.board.as_archive
res = self.board.generate().as_archive
assert res
assert isinstance(res, io.Bytes)
def test_reset(self) -> NoReturn:
attributes = ("_sdc", "_qpf", "_qsf", "_v", "_func", "_functions",
"_mips_qsf", "_mips_v")
for attr in attributes:
delattr(self.board, attr)
assert not hasattr(self.board, attr), "attribute wasn't deleted"
self.board.reset()
for attr in attributes:
assert hasattr(self.board, attr), "attributes isn't reseted"
# [minor] TODO finish test
def test_setup(self) -> NoReturn:
board = self.board.setup()
assert not hasattr(board, "configs")
# [minor] TODO add more cases
def test_generate(self) -> NoReturn:
def check_generated(board: dict) -> NoReturn:
assert isinstance(board, GenericBoard)
assert board.configs
assert isinstance(board.configs, dict)
check_generated(self.board.generate())
check_generated(self.board.generate())
check_generated(self.board.generate(
flt={'key': True},
func={'Seven': True}
))
check_generated(self.board.generate(self.p_name))
check_generated(self.board.setup().generate())
def test_dump(self) -> NoReturn:
with pytest.raises(AttributeError):
self.board.dump()
with use_test_dir():
self.board.generate().dump(self.res_path)
assert os.path.exists(self.res_path)
for filename in self.board.configs:
assert os.path.exists(os.path.join(self.res_path, filename))
def test_archive(self) -> NoReturn:
with pytest.raises(AttributeError):
self.board.archive()
with use_test_dir():
self.board.generate().archive(self.res_path)
assert os.path.exists(self.res_path + ".tar")
class TestBoard(object):
def test_Board(self) -> NoReturn:
board = Board(BOARDS[0])
with pytest.raises(AttributeError):
board.__dict__ # has no dict as __slots__
assert board.__slots__
with pytest.raises(ValueError):
Board(BOARDS[0] * 2) # there is no such board | 0.410756 | 0.448668 |
import logging
import os
import iris
from iris.analysis import MEAN
from iris.analysis.stats import pearsonr
from diagnostic import plot_diagnostic
from esmvaltool.diag_scripts.shared import group_metadata, run_diagnostic
logger = logging.getLogger(os.path.basename(__file__))
def get_provenance_record(attributes, ancestor_files, plot_type):
"""Create a provenance record describing the diagnostic data and plot."""
caption = ("Correlation of {long_name} between {dataset} and "
"{reference_dataset}.".format(**attributes))
record = {
'caption': caption,
'statistics': ['corr'],
'domains': ['global'],
'plot_type': plot_type,
'authors': [
'ande_bo',
],
'references': [
'acknow_project',
],
'ancestors': ancestor_files,
}
return record
def main(cfg):
"""Compute the time average for each input dataset."""
input_data = group_metadata(
cfg['input_data'].values(), 'standard_name', sort='dataset')
for standard_name in input_data:
logger.info("Processing variable %s", standard_name)
# Load reference dataset
for attributes in input_data[standard_name]:
if attributes['reference_dataset'] == attributes['dataset']:
reference_name = attributes['dataset']
logger.info("Using %s as a reference dataset", reference_name)
reference_filename = attributes['filename']
reference = iris.load_cube(reference_filename)
reference = reference.collapsed('time', MEAN)
logger.info("Reference cube:\n%s\n%s", reference_filename,
reference)
break
else:
raise ValueError("No reference_dataset defined in recipe.")
# Compute and plot correlation
for attributes in input_data[standard_name]:
if attributes['dataset'] == reference_name:
continue
logger.info("Processing dataset %s", attributes['dataset'])
filename = attributes['filename']
dataset = iris.load_cube(filename)
kwargs = cfg.get('pearsonr', {})
logger.info(
"Computing correlation with settings %s between "
"reference and cube:\n%s\n%s", kwargs, filename, dataset)
dataset = dataset.collapsed('time', MEAN)
cube = pearsonr(dataset, reference, **kwargs)
name = '{}_correlation_with_{}'.format(
os.path.splitext(os.path.basename(filename))[0],
reference_name)
provenance_record = get_provenance_record(
attributes,
ancestor_files=[reference_filename, filename],
plot_type=cfg['plot_type'])
plot_diagnostic(cube, name, provenance_record, cfg)
if __name__ == '__main__':
with run_diagnostic() as config:
main(config) | esmvaltool/diag_scripts/examples/correlate.py | import logging
import os
import iris
from iris.analysis import MEAN
from iris.analysis.stats import pearsonr
from diagnostic import plot_diagnostic
from esmvaltool.diag_scripts.shared import group_metadata, run_diagnostic
logger = logging.getLogger(os.path.basename(__file__))
def get_provenance_record(attributes, ancestor_files, plot_type):
"""Create a provenance record describing the diagnostic data and plot."""
caption = ("Correlation of {long_name} between {dataset} and "
"{reference_dataset}.".format(**attributes))
record = {
'caption': caption,
'statistics': ['corr'],
'domains': ['global'],
'plot_type': plot_type,
'authors': [
'ande_bo',
],
'references': [
'acknow_project',
],
'ancestors': ancestor_files,
}
return record
def main(cfg):
"""Compute the time average for each input dataset."""
input_data = group_metadata(
cfg['input_data'].values(), 'standard_name', sort='dataset')
for standard_name in input_data:
logger.info("Processing variable %s", standard_name)
# Load reference dataset
for attributes in input_data[standard_name]:
if attributes['reference_dataset'] == attributes['dataset']:
reference_name = attributes['dataset']
logger.info("Using %s as a reference dataset", reference_name)
reference_filename = attributes['filename']
reference = iris.load_cube(reference_filename)
reference = reference.collapsed('time', MEAN)
logger.info("Reference cube:\n%s\n%s", reference_filename,
reference)
break
else:
raise ValueError("No reference_dataset defined in recipe.")
# Compute and plot correlation
for attributes in input_data[standard_name]:
if attributes['dataset'] == reference_name:
continue
logger.info("Processing dataset %s", attributes['dataset'])
filename = attributes['filename']
dataset = iris.load_cube(filename)
kwargs = cfg.get('pearsonr', {})
logger.info(
"Computing correlation with settings %s between "
"reference and cube:\n%s\n%s", kwargs, filename, dataset)
dataset = dataset.collapsed('time', MEAN)
cube = pearsonr(dataset, reference, **kwargs)
name = '{}_correlation_with_{}'.format(
os.path.splitext(os.path.basename(filename))[0],
reference_name)
provenance_record = get_provenance_record(
attributes,
ancestor_files=[reference_filename, filename],
plot_type=cfg['plot_type'])
plot_diagnostic(cube, name, provenance_record, cfg)
if __name__ == '__main__':
with run_diagnostic() as config:
main(config) | 0.760651 | 0.288356 |
import mock
from neutron_lib import constants
from oslo_config import cfg
from neutron.agent.linux import dhcp
from neutron.agent.linux import ip_lib
from neutron.common import utils as common_utils
from neutron.conf.agent import common as config
from neutron.conf.agent import dhcp as dhcp_conf
from neutron.conf import common as common_conf
from neutron.conf.plugins.ml2.drivers import ovs_conf
from neutron.tests import base as tests_base
from neutron.tests.common import net_helpers
from neutron.tests.functional import base as functional_base
class TestDhcp(functional_base.BaseSudoTestCase):
def setUp(self):
super(TestDhcp, self).setUp()
conf = cfg.ConfigOpts()
config.register_interface_driver_opts_helper(conf)
config.register_interface_opts(conf)
conf.register_opts(common_conf.core_opts)
conf.register_opts(dhcp_conf.DHCP_AGENT_OPTS)
ovs_conf.register_ovs_opts(conf)
conf.set_override('interface_driver', 'openvswitch')
conf.set_override('host', 'foo-host')
self.conf = conf
br_int = self.useFixture(net_helpers.OVSBridgeFixture()).bridge
self.conf.set_override('integration_bridge', br_int.br_name, 'OVS')
def test_cleanup_stale_devices(self):
plugin = mock.MagicMock()
dev_mgr = dhcp.DeviceManager(self.conf, plugin)
network = {
'id': 'foo_id',
'tenant_id': 'foo_tenant',
'namespace': 'qdhcp-foo_id',
'ports': [],
'subnets': [tests_base.AttributeDict({'id': 'subnet_foo_id',
'enable_dhcp': True,
'ipv6_address_mode': None,
'ipv6_ra_mode': None,
'cidr': '10.0.0.0/24',
'ip_version':
constants.IP_VERSION_4,
'gateway_ip': '10.0.0.1'})]}
dhcp_port = {
'id': 'foo_port_id',
'mac_address': '10:22:33:44:55:67',
'fixed_ips': [tests_base.AttributeDict(
{'subnet_id': 'subnet_foo_id', 'ip_address': '10.0.0.1'})]
}
plugin.create_dhcp_port.return_value = tests_base.AttributeDict(
dhcp_port)
dev_mgr.driver.plug("foo_id",
"foo_id2",
"tapfoo_id2",
"10:22:33:44:55:68",
namespace="qdhcp-foo_id")
dev_mgr.driver.plug("foo_id",
"foo_id3",
"tapfoo_id3",
"10:22:33:44:55:69",
namespace="qdhcp-foo_id")
ipw = ip_lib.IPWrapper(namespace="qdhcp-foo_id")
devices = ipw.get_devices()
self.addCleanup(ipw.netns.delete, 'qdhcp-foo_id')
self.assertEqual(sorted(["tapfoo_id2", "tapfoo_id3"]),
sorted(map(str, devices)))
# setting up dhcp for the network
dev_mgr.setup(tests_base.AttributeDict(network))
common_utils.wait_until_true(
lambda: 1 == len(ipw.get_devices()),
timeout=5,
sleep=0.1,
exception=RuntimeError("only one non-loopback device must remain"))
devices = ipw.get_devices()
self.assertEqual("tapfoo_port_id", devices[0].name) | neutron/tests/functional/agent/linux/test_dhcp.py |
import mock
from neutron_lib import constants
from oslo_config import cfg
from neutron.agent.linux import dhcp
from neutron.agent.linux import ip_lib
from neutron.common import utils as common_utils
from neutron.conf.agent import common as config
from neutron.conf.agent import dhcp as dhcp_conf
from neutron.conf import common as common_conf
from neutron.conf.plugins.ml2.drivers import ovs_conf
from neutron.tests import base as tests_base
from neutron.tests.common import net_helpers
from neutron.tests.functional import base as functional_base
class TestDhcp(functional_base.BaseSudoTestCase):
def setUp(self):
super(TestDhcp, self).setUp()
conf = cfg.ConfigOpts()
config.register_interface_driver_opts_helper(conf)
config.register_interface_opts(conf)
conf.register_opts(common_conf.core_opts)
conf.register_opts(dhcp_conf.DHCP_AGENT_OPTS)
ovs_conf.register_ovs_opts(conf)
conf.set_override('interface_driver', 'openvswitch')
conf.set_override('host', 'foo-host')
self.conf = conf
br_int = self.useFixture(net_helpers.OVSBridgeFixture()).bridge
self.conf.set_override('integration_bridge', br_int.br_name, 'OVS')
def test_cleanup_stale_devices(self):
plugin = mock.MagicMock()
dev_mgr = dhcp.DeviceManager(self.conf, plugin)
network = {
'id': 'foo_id',
'tenant_id': 'foo_tenant',
'namespace': 'qdhcp-foo_id',
'ports': [],
'subnets': [tests_base.AttributeDict({'id': 'subnet_foo_id',
'enable_dhcp': True,
'ipv6_address_mode': None,
'ipv6_ra_mode': None,
'cidr': '10.0.0.0/24',
'ip_version':
constants.IP_VERSION_4,
'gateway_ip': '10.0.0.1'})]}
dhcp_port = {
'id': 'foo_port_id',
'mac_address': '10:22:33:44:55:67',
'fixed_ips': [tests_base.AttributeDict(
{'subnet_id': 'subnet_foo_id', 'ip_address': '10.0.0.1'})]
}
plugin.create_dhcp_port.return_value = tests_base.AttributeDict(
dhcp_port)
dev_mgr.driver.plug("foo_id",
"foo_id2",
"tapfoo_id2",
"10:22:33:44:55:68",
namespace="qdhcp-foo_id")
dev_mgr.driver.plug("foo_id",
"foo_id3",
"tapfoo_id3",
"10:22:33:44:55:69",
namespace="qdhcp-foo_id")
ipw = ip_lib.IPWrapper(namespace="qdhcp-foo_id")
devices = ipw.get_devices()
self.addCleanup(ipw.netns.delete, 'qdhcp-foo_id')
self.assertEqual(sorted(["tapfoo_id2", "tapfoo_id3"]),
sorted(map(str, devices)))
# setting up dhcp for the network
dev_mgr.setup(tests_base.AttributeDict(network))
common_utils.wait_until_true(
lambda: 1 == len(ipw.get_devices()),
timeout=5,
sleep=0.1,
exception=RuntimeError("only one non-loopback device must remain"))
devices = ipw.get_devices()
self.assertEqual("tapfoo_port_id", devices[0].name) | 0.496582 | 0.09611 |
# Add parent directory to path so that algobpy can be imported
import sys
sys.path.insert(0,'..')
from algobpy.parse import parseArgs
from pyteal import *
# source: https://github.com/algorand/smart-contracts/blob/master/devrel/poi/clawback-escrow.teal
def clawback_escrow(ASSET_ID, APP_ID):
# check properties of txGroup passed
group_tx_checks = And(
Global.group_size() == Int(3),
Gtxn[0].type_enum() == TxnType.ApplicationCall,
Gtxn[1].type_enum() == TxnType.AssetTransfer,
Gtxn[2].type_enum() == TxnType.Payment,
# this tx should be 2nd in group
Txn.group_index() == Int(1)
)
# check no rekeying etc
common_fields = And(
Gtxn[0].rekey_to() == Global.zero_address(),
Gtxn[1].rekey_to() == Global.zero_address(),
Gtxn[2].rekey_to() == Global.zero_address(),
Gtxn[0].close_remainder_to() == Global.zero_address(),
Gtxn[1].close_remainder_to() == Global.zero_address(),
Gtxn[2].close_remainder_to() == Global.zero_address(),
Gtxn[0].asset_close_to() == Global.zero_address(),
Gtxn[1].asset_close_to() == Global.zero_address(),
Gtxn[2].asset_close_to() == Global.zero_address()
)
# verify first transaction
# check level smart contract call - signed by asset sender
first_transaction_checks = And(
# check app_id passed through params
Gtxn[0].application_id() == Int(APP_ID),
Gtxn[0].sender() == Gtxn[2].sender(),
Gtxn[0].sender() == Gtxn[1].asset_sender()
)
# verify second transaction
# tx 1 - clawback transactions that moves the frozen asset from sender to receiver - signed by clawback-escrow
# verify the account sent in the accounts array is
# actually the receiver of the asset in asset xfer
second_transaction_checks = And(
Gtxn[0].accounts[1] == Gtxn[1].asset_receiver(),
# check asset_id passed through params
Gtxn[1].xfer_asset() == Int(ASSET_ID)
)
# verify third transaction
# tx 2 - payment transaction from sender to clawback-escrow to pay for the fee of the clawback
third_transaction_checks = And(
Gtxn[1].sender() == Gtxn[2].receiver(),
# verify the fee amount is good
Gtxn[2].amount() >= Gtxn[1].fee()
)
return And(
group_tx_checks,
common_fields,
first_transaction_checks,
second_transaction_checks,
third_transaction_checks
)
if __name__ == "__main__":
params = {
"ASSET_ID": 11,
"APP_ID": 22,
}
# Overwrite params if sys.argv[1] is passed
if(len(sys.argv) > 1):
params = parseArgs(sys.argv[1], params)
print(compileTeal(clawback_escrow(params["ASSET_ID"], params["APP_ID"]), Mode.Signature)) | examples/permissioned-token-freezing/assets/clawback-escrow.py |
# Add parent directory to path so that algobpy can be imported
import sys
sys.path.insert(0,'..')
from algobpy.parse import parseArgs
from pyteal import *
# source: https://github.com/algorand/smart-contracts/blob/master/devrel/poi/clawback-escrow.teal
def clawback_escrow(ASSET_ID, APP_ID):
# check properties of txGroup passed
group_tx_checks = And(
Global.group_size() == Int(3),
Gtxn[0].type_enum() == TxnType.ApplicationCall,
Gtxn[1].type_enum() == TxnType.AssetTransfer,
Gtxn[2].type_enum() == TxnType.Payment,
# this tx should be 2nd in group
Txn.group_index() == Int(1)
)
# check no rekeying etc
common_fields = And(
Gtxn[0].rekey_to() == Global.zero_address(),
Gtxn[1].rekey_to() == Global.zero_address(),
Gtxn[2].rekey_to() == Global.zero_address(),
Gtxn[0].close_remainder_to() == Global.zero_address(),
Gtxn[1].close_remainder_to() == Global.zero_address(),
Gtxn[2].close_remainder_to() == Global.zero_address(),
Gtxn[0].asset_close_to() == Global.zero_address(),
Gtxn[1].asset_close_to() == Global.zero_address(),
Gtxn[2].asset_close_to() == Global.zero_address()
)
# verify first transaction
# check level smart contract call - signed by asset sender
first_transaction_checks = And(
# check app_id passed through params
Gtxn[0].application_id() == Int(APP_ID),
Gtxn[0].sender() == Gtxn[2].sender(),
Gtxn[0].sender() == Gtxn[1].asset_sender()
)
# verify second transaction
# tx 1 - clawback transactions that moves the frozen asset from sender to receiver - signed by clawback-escrow
# verify the account sent in the accounts array is
# actually the receiver of the asset in asset xfer
second_transaction_checks = And(
Gtxn[0].accounts[1] == Gtxn[1].asset_receiver(),
# check asset_id passed through params
Gtxn[1].xfer_asset() == Int(ASSET_ID)
)
# verify third transaction
# tx 2 - payment transaction from sender to clawback-escrow to pay for the fee of the clawback
third_transaction_checks = And(
Gtxn[1].sender() == Gtxn[2].receiver(),
# verify the fee amount is good
Gtxn[2].amount() >= Gtxn[1].fee()
)
return And(
group_tx_checks,
common_fields,
first_transaction_checks,
second_transaction_checks,
third_transaction_checks
)
if __name__ == "__main__":
params = {
"ASSET_ID": 11,
"APP_ID": 22,
}
# Overwrite params if sys.argv[1] is passed
if(len(sys.argv) > 1):
params = parseArgs(sys.argv[1], params)
print(compileTeal(clawback_escrow(params["ASSET_ID"], params["APP_ID"]), Mode.Signature)) | 0.556882 | 0.373019 |
import json
import os
from abc import ABC, abstractmethod
from unittest.mock import ANY, patch
import pytest
from async_generator import async_generator, asynccontextmanager, yield_
from geopy import exc
from geopy.adapters import BaseAsyncAdapter
from geopy.location import Location
_env = {}
try:
with open(".test_keys") as fp:
_env.update(json.loads(fp.read()))
except IOError:
_env.update(os.environ)
class SkipIfMissingEnv(dict):
def __init__(self, env):
super().__init__(env)
self.is_internet_access_allowed = None
def __getitem__(self, key):
assert self.is_internet_access_allowed is not None
if key not in self:
if self.is_internet_access_allowed:
pytest.skip("Missing geocoder credential: %s" % (key,))
else:
# Generate some dummy token. We won't perform a networking
# request anyways.
return "dummy"
return super().__getitem__(key)
env = SkipIfMissingEnv(_env)
class BaseTestGeocoder(ABC):
"""
Base for geocoder-specific test cases.
"""
geocoder = None
delta = 0.5
@pytest.fixture(scope='class', autouse=True)
@async_generator
async def class_geocoder(_, request, patch_adapter, is_internet_access_allowed):
"""Prepare a class-level Geocoder instance."""
cls = request.cls
env.is_internet_access_allowed = is_internet_access_allowed
geocoder = cls.make_geocoder()
cls.geocoder = geocoder
run_async = isinstance(geocoder.adapter, BaseAsyncAdapter)
if run_async:
async with geocoder:
await yield_(geocoder)
else:
await yield_(geocoder)
@classmethod
@asynccontextmanager
@async_generator
async def inject_geocoder(cls, geocoder):
"""An async context manager allowing to inject a custom
geocoder instance in a single test method which will
be used by the `geocode_run`/`reverse_run` methods.
"""
with patch.object(cls, 'geocoder', geocoder):
run_async = isinstance(geocoder.adapter, BaseAsyncAdapter)
if run_async:
async with geocoder:
await yield_(geocoder)
else:
await yield_(geocoder)
@pytest.fixture(autouse=True)
def ensure_no_geocoder_assignment(self):
yield
assert self.geocoder is type(self).geocoder, (
"Detected `self.geocoder` assignment. "
"Please use `async with inject_geocoder(my_geocoder):` "
"instead, which supports async adapters."
)
@classmethod
@abstractmethod
def make_geocoder(cls, **kwargs): # pragma: no cover
pass
async def geocode_run(
self, payload, expected,
*,
skiptest_on_errors=True,
expect_failure=False
):
"""
Calls geocoder.geocode(**payload), then checks against `expected`.
"""
cls = type(self)
result = await self._make_request(
self.geocoder, 'geocode',
skiptest_on_errors=skiptest_on_errors,
**payload,
)
if expect_failure:
assert result is None
return
if result is None:
pytest.fail('%s: No result found' % cls.__name__)
if result == []:
pytest.fail('%s returned an empty list instead of None' % cls.__name__)
self._verify_request(result, exactly_one=payload.get('exactly_one', True),
**expected)
return result
async def reverse_run(
self, payload, expected,
*,
skiptest_on_errors=True,
expect_failure=False
):
"""
Calls geocoder.reverse(**payload), then checks against `expected`.
"""
cls = type(self)
result = await self._make_request(
self.geocoder, 'reverse',
skiptest_on_errors=skiptest_on_errors,
**payload,
)
if expect_failure:
assert result is None
return
if result is None:
pytest.fail('%s: No result found' % cls.__name__)
if result == []:
pytest.fail('%s returned an empty list instead of None' % cls.__name__)
self._verify_request(result, exactly_one=payload.get('exactly_one', True),
**expected)
return result
async def reverse_timezone_run(self, payload, expected, *, skiptest_on_errors=True):
timezone = await self._make_request(
self.geocoder, 'reverse_timezone',
skiptest_on_errors=skiptest_on_errors,
**payload,
)
if expected is None:
assert timezone is None
else:
assert timezone.pytz_timezone == expected
return timezone
async def _make_request(self, geocoder, method, *, skiptest_on_errors, **kwargs):
cls = type(self)
call = getattr(geocoder, method)
run_async = isinstance(geocoder.adapter, BaseAsyncAdapter)
try:
if run_async:
result = await call(**kwargs)
else:
result = call(**kwargs)
except exc.GeocoderRateLimited as e:
if not skiptest_on_errors:
raise
pytest.skip(
"%s: Rate-limited, retry-after %s" % (cls.__name__, e.retry_after)
)
except exc.GeocoderQuotaExceeded:
if not skiptest_on_errors:
raise
pytest.skip("%s: Quota exceeded" % cls.__name__)
except exc.GeocoderTimedOut:
if not skiptest_on_errors:
raise
pytest.skip("%s: Service timed out" % cls.__name__)
except exc.GeocoderUnavailable:
if not skiptest_on_errors:
raise
pytest.skip("%s: Service unavailable" % cls.__name__)
return result
def _verify_request(
self,
result,
latitude=ANY,
longitude=ANY,
address=ANY,
exactly_one=True,
delta=None,
):
if exactly_one:
assert isinstance(result, Location)
else:
assert isinstance(result, list)
item = result if exactly_one else result[0]
delta = delta or self.delta
expected = (
pytest.approx(latitude, abs=delta) if latitude is not ANY else ANY,
pytest.approx(longitude, abs=delta) if longitude is not ANY else ANY,
address,
)
received = (
item.latitude,
item.longitude,
item.address,
)
assert received == expected | test/geocoders/util.py | import json
import os
from abc import ABC, abstractmethod
from unittest.mock import ANY, patch
import pytest
from async_generator import async_generator, asynccontextmanager, yield_
from geopy import exc
from geopy.adapters import BaseAsyncAdapter
from geopy.location import Location
_env = {}
try:
with open(".test_keys") as fp:
_env.update(json.loads(fp.read()))
except IOError:
_env.update(os.environ)
class SkipIfMissingEnv(dict):
def __init__(self, env):
super().__init__(env)
self.is_internet_access_allowed = None
def __getitem__(self, key):
assert self.is_internet_access_allowed is not None
if key not in self:
if self.is_internet_access_allowed:
pytest.skip("Missing geocoder credential: %s" % (key,))
else:
# Generate some dummy token. We won't perform a networking
# request anyways.
return "dummy"
return super().__getitem__(key)
env = SkipIfMissingEnv(_env)
class BaseTestGeocoder(ABC):
"""
Base for geocoder-specific test cases.
"""
geocoder = None
delta = 0.5
@pytest.fixture(scope='class', autouse=True)
@async_generator
async def class_geocoder(_, request, patch_adapter, is_internet_access_allowed):
"""Prepare a class-level Geocoder instance."""
cls = request.cls
env.is_internet_access_allowed = is_internet_access_allowed
geocoder = cls.make_geocoder()
cls.geocoder = geocoder
run_async = isinstance(geocoder.adapter, BaseAsyncAdapter)
if run_async:
async with geocoder:
await yield_(geocoder)
else:
await yield_(geocoder)
@classmethod
@asynccontextmanager
@async_generator
async def inject_geocoder(cls, geocoder):
"""An async context manager allowing to inject a custom
geocoder instance in a single test method which will
be used by the `geocode_run`/`reverse_run` methods.
"""
with patch.object(cls, 'geocoder', geocoder):
run_async = isinstance(geocoder.adapter, BaseAsyncAdapter)
if run_async:
async with geocoder:
await yield_(geocoder)
else:
await yield_(geocoder)
@pytest.fixture(autouse=True)
def ensure_no_geocoder_assignment(self):
yield
assert self.geocoder is type(self).geocoder, (
"Detected `self.geocoder` assignment. "
"Please use `async with inject_geocoder(my_geocoder):` "
"instead, which supports async adapters."
)
@classmethod
@abstractmethod
def make_geocoder(cls, **kwargs): # pragma: no cover
pass
async def geocode_run(
self, payload, expected,
*,
skiptest_on_errors=True,
expect_failure=False
):
"""
Calls geocoder.geocode(**payload), then checks against `expected`.
"""
cls = type(self)
result = await self._make_request(
self.geocoder, 'geocode',
skiptest_on_errors=skiptest_on_errors,
**payload,
)
if expect_failure:
assert result is None
return
if result is None:
pytest.fail('%s: No result found' % cls.__name__)
if result == []:
pytest.fail('%s returned an empty list instead of None' % cls.__name__)
self._verify_request(result, exactly_one=payload.get('exactly_one', True),
**expected)
return result
async def reverse_run(
self, payload, expected,
*,
skiptest_on_errors=True,
expect_failure=False
):
"""
Calls geocoder.reverse(**payload), then checks against `expected`.
"""
cls = type(self)
result = await self._make_request(
self.geocoder, 'reverse',
skiptest_on_errors=skiptest_on_errors,
**payload,
)
if expect_failure:
assert result is None
return
if result is None:
pytest.fail('%s: No result found' % cls.__name__)
if result == []:
pytest.fail('%s returned an empty list instead of None' % cls.__name__)
self._verify_request(result, exactly_one=payload.get('exactly_one', True),
**expected)
return result
async def reverse_timezone_run(self, payload, expected, *, skiptest_on_errors=True):
timezone = await self._make_request(
self.geocoder, 'reverse_timezone',
skiptest_on_errors=skiptest_on_errors,
**payload,
)
if expected is None:
assert timezone is None
else:
assert timezone.pytz_timezone == expected
return timezone
async def _make_request(self, geocoder, method, *, skiptest_on_errors, **kwargs):
cls = type(self)
call = getattr(geocoder, method)
run_async = isinstance(geocoder.adapter, BaseAsyncAdapter)
try:
if run_async:
result = await call(**kwargs)
else:
result = call(**kwargs)
except exc.GeocoderRateLimited as e:
if not skiptest_on_errors:
raise
pytest.skip(
"%s: Rate-limited, retry-after %s" % (cls.__name__, e.retry_after)
)
except exc.GeocoderQuotaExceeded:
if not skiptest_on_errors:
raise
pytest.skip("%s: Quota exceeded" % cls.__name__)
except exc.GeocoderTimedOut:
if not skiptest_on_errors:
raise
pytest.skip("%s: Service timed out" % cls.__name__)
except exc.GeocoderUnavailable:
if not skiptest_on_errors:
raise
pytest.skip("%s: Service unavailable" % cls.__name__)
return result
def _verify_request(
self,
result,
latitude=ANY,
longitude=ANY,
address=ANY,
exactly_one=True,
delta=None,
):
if exactly_one:
assert isinstance(result, Location)
else:
assert isinstance(result, list)
item = result if exactly_one else result[0]
delta = delta or self.delta
expected = (
pytest.approx(latitude, abs=delta) if latitude is not ANY else ANY,
pytest.approx(longitude, abs=delta) if longitude is not ANY else ANY,
address,
)
received = (
item.latitude,
item.longitude,
item.address,
)
assert received == expected | 0.680454 | 0.416619 |
from django.test import TestCase
from rest_framework.authtoken.models import Token
from rest_framework import status
from rest_framework.test import APITestCase
from cride.circles.models import Circle, Invitation, Membership
from cride.users.models import Users, Profiles
class InvitationsManagerTestCase(TestCase):
"""Invitatiosn manager teste case"""
def setUp(self):
"""test case setup"""
self.user = Users.objects.create(
first_name='javier',
last_name='manobanda',
email='<EMAIL>',
username='javim',
password='<PASSWORD>'
)
self.circle = Circle.objects.create(
name='Facultad Mecatrónica',
slug_name='fciencias',
about='Grupo oficial de mecatrónica',
verified=True,
)
def test_code_generations(self):
"""random coces shoul be generatedt automatically"""
invitation = Invitation.objects.create(
issued_by=self.user,
circle=self.circle
)
self.assertIsNotNone(invitation.code)
def test_code_usage(self):
"""if the code is given, there´s no need to create a new one"""
code = 'holamundo'
invitation = Invitation.objects.create(
issued_by=self.user,
circle=self.circle,
code=code,
)
self.assertEqual(invitation.code, code)
def test_code_generation_if_duplicated(self):
"""if given code is not unique, a new one must be generated."""
code = Invitation.objects.create(
issued_by=self.user,
circle=self.circle,
).code
# * created a onother invitations white the past code
invitation = Invitation.objects.create(
issued_by=self.user,
circle=self.circle,
code=code,
)
self.assertNotEqual(code, invitation.code)
class MemberInvitationsAPITestCase(APITestCase):
def setUp(self):
"""test case setup"""
self.user = Users.objects.create(
first_name='javier',
last_name='manobanda',
email='<EMAIL>',
username='javim',
password='<PASSWORD>'
)
self.circle = Circle.objects.create(
name='Facultad Mecatrónica',
slug_name='fciencias',
about='Grupo oficial de mecatrónica',
verified=True,
)
self.profile = Profiles.objects.create(
users=self.user,
)
self.membership = Membership.objects.create(
user=self.user,
profile=self.profile,
circle=self.circle,
remaining_inv=10,
)
self.token = Token.objects.create(
user=self.user
).key
self.url = f'/circles/{self.circle.slug_name}/members/{self.user.username}/invitations/'
self.client.credentials(HTTP_AUTHORIZATION=f'token {self.token}')
def test_response_success(self):
"""verified request succeeded"""
request = self.client.get(self.url)
self.assertEqual(request.status_code, status.HTTP_200_OK)
def test_invitations_creations(self):
"""verifica que las invitaciones creadas no existan previamente"""
# * invitations in db must be 0
self.assertEqual(Invitation.objects.count(), 0)
request = self.client.get(self.url)
self.assertEqual(request.status_code, status.HTTP_200_OK)
# * verify new invitations were created
invitations = Invitation.objects.filter(issued_by=self.user)
self.assertEqual(Invitation.objects.count(), self.membership.remaining_inv)
for invitation in invitations:
self.assertIn(invitation.code, request.data['invitations']) | cride/tests/test_invitations.py |
from django.test import TestCase
from rest_framework.authtoken.models import Token
from rest_framework import status
from rest_framework.test import APITestCase
from cride.circles.models import Circle, Invitation, Membership
from cride.users.models import Users, Profiles
class InvitationsManagerTestCase(TestCase):
"""Invitatiosn manager teste case"""
def setUp(self):
"""test case setup"""
self.user = Users.objects.create(
first_name='javier',
last_name='manobanda',
email='<EMAIL>',
username='javim',
password='<PASSWORD>'
)
self.circle = Circle.objects.create(
name='Facultad Mecatrónica',
slug_name='fciencias',
about='Grupo oficial de mecatrónica',
verified=True,
)
def test_code_generations(self):
"""random coces shoul be generatedt automatically"""
invitation = Invitation.objects.create(
issued_by=self.user,
circle=self.circle
)
self.assertIsNotNone(invitation.code)
def test_code_usage(self):
"""if the code is given, there´s no need to create a new one"""
code = 'holamundo'
invitation = Invitation.objects.create(
issued_by=self.user,
circle=self.circle,
code=code,
)
self.assertEqual(invitation.code, code)
def test_code_generation_if_duplicated(self):
"""if given code is not unique, a new one must be generated."""
code = Invitation.objects.create(
issued_by=self.user,
circle=self.circle,
).code
# * created a onother invitations white the past code
invitation = Invitation.objects.create(
issued_by=self.user,
circle=self.circle,
code=code,
)
self.assertNotEqual(code, invitation.code)
class MemberInvitationsAPITestCase(APITestCase):
def setUp(self):
"""test case setup"""
self.user = Users.objects.create(
first_name='javier',
last_name='manobanda',
email='<EMAIL>',
username='javim',
password='<PASSWORD>'
)
self.circle = Circle.objects.create(
name='Facultad Mecatrónica',
slug_name='fciencias',
about='Grupo oficial de mecatrónica',
verified=True,
)
self.profile = Profiles.objects.create(
users=self.user,
)
self.membership = Membership.objects.create(
user=self.user,
profile=self.profile,
circle=self.circle,
remaining_inv=10,
)
self.token = Token.objects.create(
user=self.user
).key
self.url = f'/circles/{self.circle.slug_name}/members/{self.user.username}/invitations/'
self.client.credentials(HTTP_AUTHORIZATION=f'token {self.token}')
def test_response_success(self):
"""verified request succeeded"""
request = self.client.get(self.url)
self.assertEqual(request.status_code, status.HTTP_200_OK)
def test_invitations_creations(self):
"""verifica que las invitaciones creadas no existan previamente"""
# * invitations in db must be 0
self.assertEqual(Invitation.objects.count(), 0)
request = self.client.get(self.url)
self.assertEqual(request.status_code, status.HTTP_200_OK)
# * verify new invitations were created
invitations = Invitation.objects.filter(issued_by=self.user)
self.assertEqual(Invitation.objects.count(), self.membership.remaining_inv)
for invitation in invitations:
self.assertIn(invitation.code, request.data['invitations']) | 0.636918 | 0.354601 |
# Standard library imports
import sys
from urllib.parse import quote
# Third party imports
from qtpy.QtCore import Qt, QUrl, QUrlQuery, Signal
from qtpy.QtGui import QDesktopServices
from qtpy.QtWidgets import (QApplication, QCheckBox, QDialog, QFormLayout,
QHBoxLayout, QLabel, QLineEdit, QMessageBox,
QPlainTextEdit, QPushButton, QVBoxLayout)
# Local imports
from spyder import (__project_url__, __trouble_url__, dependencies,
get_versions)
from spyder.config.base import _, running_under_pytest
from spyder.config.gui import get_font
from spyder.plugins.console.widgets.console import ConsoleBaseWidget
from spyder.plugins.editor.widgets.codeeditor import CodeEditor
from spyder.utils import icon_manager as ima
from spyder.utils.qthelpers import restore_keyevent
from spyder.widgets.github.backend import GithubBackend
from spyder.widgets.mixins import BaseEditMixin, TracebackLinksMixin
# Minimum number of characters to introduce in the title and
# description fields before being able to send the report to
# Github.
TITLE_MIN_CHARS = 15
DESC_MIN_CHARS = 50
class DescriptionWidget(CodeEditor):
"""Widget to enter error description."""
def __init__(self, parent=None):
CodeEditor.__init__(self, parent)
# Editor options
self.setup_editor(
language='md',
color_scheme=None,
linenumbers=False,
scrollflagarea=False,
wrap=True,
edge_line=False,
highlight_current_line=False,
highlight_current_cell=False,
occurrence_highlighting=False,
auto_unindent=False)
# Set font
self.set_font(get_font())
# Header
self.header = (
"### What steps will reproduce the problem?\n\n"
"<!--- You can use Markdown here --->\n\n")
self.set_text(self.header)
self.move_cursor(len(self.header))
self.header_end_pos = self.get_position('eof')
def remove_text(self):
"""Remove text."""
self.truncate_selection(self.header_end_pos)
self.remove_selected_text()
def cut(self):
"""Cut text"""
self.truncate_selection(self.header_end_pos)
if self.has_selected_text():
CodeEditor.cut(self)
def keyPressEvent(self, event):
"""Reimplemented Qt Method to avoid removing the header."""
event, text, key, ctrl, shift = restore_keyevent(event)
cursor_position = self.get_position('cursor')
if cursor_position < self.header_end_pos:
self.restrict_cursor_position(self.header_end_pos, 'eof')
elif key == Qt.Key_Backspace:
if self.has_selected_text():
self.remove_text()
elif self.header_end_pos == cursor_position:
return
else:
self.stdkey_backspace()
elif key == Qt.Key_X and ctrl:
self.cut()
else:
CodeEditor.keyPressEvent(self, event)
def delete(self):
"""Reimplemented to avoid removing the header."""
cursor_position = self.get_position('cursor')
if cursor_position < self.header_end_pos:
self.restrict_cursor_position(self.header_end_pos, 'eof')
elif self.has_selected_text():
self.remove_text()
else:
self.stdkey_clear()
def contextMenuEvent(self, event):
"""Reimplemented Qt Method to not show the context menu."""
pass
class ShowErrorWidget(TracebackLinksMixin, ConsoleBaseWidget, BaseEditMixin):
"""Widget to show errors as they appear in the Internal console."""
QT_CLASS = QPlainTextEdit
go_to_error = Signal(str)
def __init__(self, parent=None):
ConsoleBaseWidget.__init__(self, parent)
BaseEditMixin.__init__(self)
TracebackLinksMixin.__init__(self)
self.setReadOnly(True)
class SpyderErrorDialog(QDialog):
"""Custom error dialog for error reporting."""
def __init__(self, parent=None, is_report=False):
QDialog.__init__(self, parent)
self.is_report = is_report
self.setWindowTitle(_("Issue reporter"))
self._github_org = 'spyder-ide'
self._github_repo = 'spyder'
# To save the traceback sent to the internal console
self.error_traceback = ""
# Dialog main label
if self.is_report:
title = _("Please fill the following information")
else:
title = _("Spyder has encountered an internal problem!")
self.main_label = QLabel(
_("<h3>{title}</h3>"
"Before reporting this problem, <i>please</i> consult our "
"comprehensive "
"<b><a href=\"{trouble_url}\">Troubleshooting Guide</a></b> "
"which should help solve most issues, and search for "
"<b><a href=\"{project_url}\">known bugs</a></b> "
"matching your error message or problem description for a "
"quicker solution."
).format(title=title, trouble_url=__trouble_url__,
project_url=__project_url__))
self.main_label.setOpenExternalLinks(True)
self.main_label.setWordWrap(True)
self.main_label.setAlignment(Qt.AlignJustify)
self.main_label.setStyleSheet('font-size: 12px;')
# Issue title
self.title = QLineEdit()
self.title.textChanged.connect(self._contents_changed)
self.title_chars_label = QLabel(_("{} more characters "
"to go...").format(TITLE_MIN_CHARS))
form_layout = QFormLayout()
form_layout.setFieldGrowthPolicy(QFormLayout.ExpandingFieldsGrow)
red_asterisk = '<font color="Red">*</font>'
title_label = QLabel(_("<b>Title</b>: {}").format(red_asterisk))
form_layout.setWidget(0, QFormLayout.LabelRole, title_label)
form_layout.setWidget(0, QFormLayout.FieldRole, self.title)
# Description
steps_header = QLabel(
_("<b>Steps to reproduce:</b> {}").format(red_asterisk))
self.steps_text = QLabel(
_("Please enter a detailed step-by-step "
"description (in English) of what led up to "
"the problem below. Issue reports without a "
"clear way to reproduce them will be closed.")
)
self.steps_text.setWordWrap(True)
self.steps_text.setAlignment(Qt.AlignJustify)
self.steps_text.setStyleSheet('font-size: 12px;')
# Field to input the description of the problem
self.input_description = DescriptionWidget(self)
# Only allow to submit to Github if we have a long enough description
self.input_description.textChanged.connect(self._contents_changed)
# Widget to show errors
self.details = ShowErrorWidget(self)
self.details.set_pythonshell_font(get_font())
self.details.hide()
self.description_minimum_length = DESC_MIN_CHARS
self.require_minimum_length = True
# Label to show missing chars
self.initial_chars = len(self.input_description.toPlainText())
self.desc_chars_label = QLabel(_("{} more characters "
"to go...").format(
self.description_minimum_length))
# Checkbox to dismiss future errors
self.dismiss_box = QCheckBox(_("Hide all future errors during this "
"session"))
if self.is_report:
self.dismiss_box.hide()
# Dialog buttons
gh_icon = ima.icon('github')
self.submit_btn = QPushButton(gh_icon, _('Submit to Github'))
self.submit_btn.setEnabled(False)
self.submit_btn.clicked.connect(self._submit_to_github)
self.details_btn = QPushButton(_('Show details'))
self.details_btn.clicked.connect(self._show_details)
if self.is_report:
self.details_btn.hide()
self.close_btn = QPushButton(_('Close'))
if self.is_report:
self.close_btn.clicked.connect(self.reject)
# Buttons layout
buttons_layout = QHBoxLayout()
buttons_layout.addWidget(self.submit_btn)
buttons_layout.addWidget(self.details_btn)
buttons_layout.addWidget(self.close_btn)
# Main layout
layout = QVBoxLayout()
layout.addWidget(self.main_label)
layout.addSpacing(20)
layout.addLayout(form_layout)
layout.addWidget(self.title_chars_label)
layout.addSpacing(12)
layout.addWidget(steps_header)
layout.addSpacing(-1)
layout.addWidget(self.steps_text)
layout.addSpacing(1)
layout.addWidget(self.input_description)
layout.addWidget(self.details)
layout.addWidget(self.desc_chars_label)
layout.addSpacing(15)
layout.addWidget(self.dismiss_box)
layout.addSpacing(15)
layout.addLayout(buttons_layout)
layout.setContentsMargins(25, 20, 25, 10)
self.setLayout(layout)
self.resize(570, 600)
self.title.setFocus()
# Set Tab key focus order
self.setTabOrder(self.title, self.input_description)
@staticmethod
def render_issue(description='', traceback=''):
"""
Render issue content.
Parameters
----------
description: str
Description to include in issue message.
traceback: str
Traceback text.
"""
# Get component versions
versions = get_versions()
# Get git revision for development version
revision = ''
if versions['revision']:
revision = versions['revision']
# Make a description header in case no description is supplied
if not description:
description = "### What steps reproduce the problem?"
# Make error section from traceback and add appropriate reminder header
if traceback:
error_section = ("### Traceback\n"
"```python-traceback\n"
"{}\n"
"```".format(traceback))
else:
error_section = ''
issue_template = """\
## Description
{description}
{error_section}
## Versions
* Spyder version: {spyder_version} {commit}
* Python version: {python_version}
* Qt version: {qt_version}
* {qt_api_name} version: {qt_api_version}
* Operating System: {os_name} {os_version}
### Dependencies
```
{dependencies}
```
""".format(description=description,
error_section=error_section,
spyder_version=versions['spyder'],
commit=revision,
python_version=versions['python'],
qt_version=versions['qt'],
qt_api_name=versions['qt_api'],
qt_api_version=versions['qt_api_ver'],
os_name=versions['system'],
os_version=versions['release'],
dependencies=dependencies.status())
return issue_template
@staticmethod
def open_web_report(body, title=None):
"""
Open a new issue on Github with prefilled information.
Parameters
----------
body: str
The body content of the report.
title: str or None, optional
The title of the report. Default is None.
"""
url = QUrl(__project_url__ + '/issues/new')
query = QUrlQuery()
query.addQueryItem("body", quote(body))
if title:
query.addQueryItem("title", quote(title))
url.setQuery(query)
QDesktopServices.openUrl(url)
def set_require_minimum_length(self, state):
"""Remove the requirement for minimum length."""
self.require_minimum_length = state
if state:
self._contents_changed()
else:
self.desc_chars_label.setText('')
def set_github_repo_org(self, repo_fullname):
"""Set the report Github organization and repository."""
org, repo = repo_fullname.split('/')
self._github_org = org
self._github_repo = repo
def _submit_to_github(self):
"""Action to take when pressing the submit button."""
# Getting description and traceback
title = self.title.text()
description = self.input_description.toPlainText()
traceback = self.error_traceback[:-1] # Remove last EOL
# Render issue
if traceback:
issue_text = self.render_issue(description=description,
traceback=traceback)
else:
issue_text = description
try:
if running_under_pytest():
org = 'ccordoba12'
else:
org = self._github_org
repo = self._github_repo
github_backend = GithubBackend(org, repo, parent_widget=self)
github_report = github_backend.send_report(title, issue_text)
if github_report:
self.close()
except Exception:
ret = QMessageBox.question(
self,
_('Error'),
_("An error occurred while trying to send the issue to "
"Github automatically. Would you like to open it "
"manually?<br><br>"
"If so, please make sure to paste your clipboard "
"into the issue report box that will appear in a new "
"browser tab before clicking <i>Submit</i> on that "
"page."),
)
if ret in [QMessageBox.Yes, QMessageBox.Ok]:
QApplication.clipboard().setText(issue_text)
issue_body = (
" \n<!--- *** BEFORE SUBMITTING: PASTE CLIPBOARD HERE "
"TO COMPLETE YOUR REPORT *** ---!>\n")
self.open_web_report(body=issue_body, title=title)
def append_traceback(self, text):
"""Append text to the traceback, to be displayed in details."""
self.error_traceback += text
def _show_details(self):
"""Show traceback on its own dialog"""
if self.details.isVisible():
self.details.hide()
self.details_btn.setText(_('Show details'))
else:
self.resize(570, 700)
self.details.document().setPlainText('')
self.details.append_text_to_shell(self.error_traceback,
error=True,
prompt=False)
self.details.show()
self.details_btn.setText(_('Hide details'))
def _contents_changed(self):
"""Activate submit_btn."""
if not self.require_minimum_length:
return
desc_chars = (len(self.input_description.toPlainText()) -
self.initial_chars)
if desc_chars < self.description_minimum_length:
self.desc_chars_label.setText(
u"{} {}".format(self.description_minimum_length - desc_chars,
_("more characters to go...")))
else:
self.desc_chars_label.setText(_("Description complete; thanks!"))
title_chars = len(self.title.text())
if title_chars < TITLE_MIN_CHARS:
self.title_chars_label.setText(
u"{} {}".format(TITLE_MIN_CHARS - title_chars,
_("more characters to go...")))
else:
self.title_chars_label.setText(_("Title complete; thanks!"))
submission_enabled = (desc_chars >= self.description_minimum_length and
title_chars >= TITLE_MIN_CHARS)
self.submit_btn.setEnabled(submission_enabled)
def set_title(self, title):
"""Set the title for the report."""
self.title.setText(title)
def set_description(self, description):
"""Set the description for the report."""
self.input_description.setPlainText(description)
def set_color_scheme(self, color_scheme):
"""Set the color scheme for the description input."""
self.input_description.set_color_scheme(color_scheme)
def test():
from spyder.utils.qthelpers import qapplication
app = qapplication()
dlg = SpyderErrorDialog()
dlg.show()
sys.exit(dlg.exec_())
if __name__ == "__main__":
test() | spyder/widgets/reporterror.py | {dependencies} | 0.426322 | 0.103115 |
from django import template
from project import additional_scripts as scripts
from services import models
import os
from project.settings.base import PROJECT_ROOT
import re
import random
register = template.Library()
@register.filter(name='translite')
def translite(value, lang):
return scripts.Translite(value).translite(lang).get_link()
@register.filter(name="get_object_by_name")
def get_object_by_name(model, name):
if model == "ServiceType":
return models.ServiceType.objects.get(type_name=name)
elif model == "Service":
return models.Service.objects.get(service_name=name)
elif model == "ServicedCar":
return models.ServicedCar.objects.get(car_type=name)
def get_attr(model, args):
args = args.split(",")
name = args[0]
attr = args[1]
if model == "ServiceType":
obj = models.ServiceType.objects.get(type_name=name)
elif model == "Service":
obj = models.Service.objects.get(service_name=name)
elif model == "ServicedCar":
obj = models.ServicedCar.objects.get(car_type=name)
return obj.__getattribute(attr)
@register.filter(name='path_without_page_number')
def get_path_without_page_number(path):
return re.sub(r"\d+\/$", "", path)
@register.filter(name='dir_by_position')
def get_dir_by_position(path, pos):
dirs = [dir_ for dir_ in path.split("/") if dir_!='']
if len(dirs) <= int(pos):
return 'DoesNotExist'
else:
return scripts.Translite(dirs[int(pos)]).translite("ru").normalize() if len(dirs[int(pos)]) > 3 else scripts.Translite(dirs[int(pos)]).translite("ru").normalize().upper()
@register.filter(name='inc')
def inc(count):
return count + 1
@register.filter(name='dec')
def inc(count):
return count - 1
@register.filter(name='truncatechars_right')
def truncatechars_right(string, count):
return string[:-int(count)]
@register.filter(name='get_string')
def get_string(objects, arg):
return arg + " "+ ", ".join([str(obj) for obj in objects])
@register.filter(name='contains')
def contains(objects, obj):
return True if obj in objects else False
@register.filter(name='relpath')
def get_relpath(path):
return os.path.relpath(path, PROJECT_ROOT)
@register.filter(name='selected')
def selected(path, app_name):
dirs = [dir_ for dir_ in path.split("/") if dir_!='']
if len(dirs) > 0:
return True if dirs[0] == app_name else False
else:
return True if app_name == "home" else False
@register.filter(name='random_slice')
def random_slice(iterator, count):
res = list(iterator)
random.shuffle(res)
return res[:int(count)] | project/mytemplatetags/templatetags/customtags.py | from django import template
from project import additional_scripts as scripts
from services import models
import os
from project.settings.base import PROJECT_ROOT
import re
import random
register = template.Library()
@register.filter(name='translite')
def translite(value, lang):
return scripts.Translite(value).translite(lang).get_link()
@register.filter(name="get_object_by_name")
def get_object_by_name(model, name):
if model == "ServiceType":
return models.ServiceType.objects.get(type_name=name)
elif model == "Service":
return models.Service.objects.get(service_name=name)
elif model == "ServicedCar":
return models.ServicedCar.objects.get(car_type=name)
def get_attr(model, args):
args = args.split(",")
name = args[0]
attr = args[1]
if model == "ServiceType":
obj = models.ServiceType.objects.get(type_name=name)
elif model == "Service":
obj = models.Service.objects.get(service_name=name)
elif model == "ServicedCar":
obj = models.ServicedCar.objects.get(car_type=name)
return obj.__getattribute(attr)
@register.filter(name='path_without_page_number')
def get_path_without_page_number(path):
return re.sub(r"\d+\/$", "", path)
@register.filter(name='dir_by_position')
def get_dir_by_position(path, pos):
dirs = [dir_ for dir_ in path.split("/") if dir_!='']
if len(dirs) <= int(pos):
return 'DoesNotExist'
else:
return scripts.Translite(dirs[int(pos)]).translite("ru").normalize() if len(dirs[int(pos)]) > 3 else scripts.Translite(dirs[int(pos)]).translite("ru").normalize().upper()
@register.filter(name='inc')
def inc(count):
return count + 1
@register.filter(name='dec')
def inc(count):
return count - 1
@register.filter(name='truncatechars_right')
def truncatechars_right(string, count):
return string[:-int(count)]
@register.filter(name='get_string')
def get_string(objects, arg):
return arg + " "+ ", ".join([str(obj) for obj in objects])
@register.filter(name='contains')
def contains(objects, obj):
return True if obj in objects else False
@register.filter(name='relpath')
def get_relpath(path):
return os.path.relpath(path, PROJECT_ROOT)
@register.filter(name='selected')
def selected(path, app_name):
dirs = [dir_ for dir_ in path.split("/") if dir_!='']
if len(dirs) > 0:
return True if dirs[0] == app_name else False
else:
return True if app_name == "home" else False
@register.filter(name='random_slice')
def random_slice(iterator, count):
res = list(iterator)
random.shuffle(res)
return res[:int(count)] | 0.25128 | 0.110231 |
"""The psort CLI tool."""
import argparse
import collections
import os
# The following import makes sure the filters are registered.
from plaso import filters # pylint: disable=unused-import
# The following import makes sure the output modules are registered.
from plaso import output # pylint: disable=unused-import
from plaso.cli import analysis_tool
from plaso.cli import logger
from plaso.cli import status_view
from plaso.cli import tool_options
from plaso.cli import views
from plaso.cli.helpers import manager as helpers_manager
from plaso.containers import reports
from plaso.engine import configurations
from plaso.engine import engine
from plaso.helpers import language_tags
from plaso.lib import errors
from plaso.lib import loggers
from plaso.multi_process import output_engine as multi_output_engine
from plaso.storage import factory as storage_factory
class PsortTool(
analysis_tool.AnalysisTool,
tool_options.OutputModuleOptions):
"""Psort CLI tool.
Attributes:
list_analysis_plugins (bool): True if information about the analysis
plugins should be shown.
list_language_identifiers (bool): True if information about the language
identifiers should be shown.
list_output_modules (bool): True if information about the output modules
should be shown.
list_profilers (bool): True if the profilers should be listed.
"""
NAME = 'psort'
DESCRIPTION = (
'Application to read, filter and process output from a plaso storage '
'file.')
_CONTAINER_TYPE_ANALYSIS_REPORT = reports.AnalysisReport.CONTAINER_TYPE
def __init__(self, input_reader=None, output_writer=None):
"""Initializes the CLI tool object.
Args:
input_reader (Optional[InputReader]): input reader, where None indicates
that the stdin input reader should be used.
output_writer (Optional[OutputWriter]): output writer, where None
indicates that the stdout output writer should be used.
"""
super(PsortTool, self).__init__(
input_reader=input_reader, output_writer=output_writer)
self._command_line_arguments = None
self._deduplicate_events = True
self._preferred_language = 'en-US'
self._process_memory_limit = None
self._status_view_mode = status_view.StatusView.MODE_WINDOW
self._status_view = status_view.StatusView(self._output_writer, self.NAME)
self._time_slice = None
self._use_time_slicer = False
self.list_language_identifiers = False
self.list_output_modules = False
self.list_profilers = False
def _CheckStorageFile(self, storage_file_path): # pylint: disable=arguments-differ
"""Checks if the storage file path is valid.
Args:
storage_file_path (str): path of the storage file.
Raises:
BadConfigOption: if the storage file path is invalid.
"""
if not storage_file_path:
raise errors.BadConfigOption('Missing storage file option.')
if not os.path.exists(storage_file_path):
raise errors.BadConfigOption(
'No such storage file: {0:s}.'.format(storage_file_path))
if not os.path.isfile(storage_file_path):
raise errors.BadConfigOption(
'Storage file: {0:s} already exists and is not a file.'.format(
storage_file_path))
storage_file_directory = os.path.dirname(storage_file_path) or '.'
if not os.access(storage_file_directory, os.W_OK):
raise errors.BadConfigOption(
'Unable to write to storage file: {0:s}'.format(storage_file_path))
if not storage_factory.StorageFactory.CheckStorageFileHasSupportedFormat(
storage_file_path, check_readable_only=False):
raise errors.BadConfigOption(
'Format of storage file: {0:s} not supported'.format(
storage_file_path))
def _GetAnalysisPlugins(self, analysis_plugins_string):
"""Retrieves analysis plugins.
Args:
analysis_plugins_string (str): comma separated names of analysis plugins
to enable.
Returns:
list[AnalysisPlugin]: analysis plugins.
"""
if not analysis_plugins_string:
return []
analysis_plugins_list = [
name.strip() for name in analysis_plugins_string.split(',')]
analysis_plugins = self._analysis_manager.GetPluginObjects(
analysis_plugins_list)
return analysis_plugins.values()
def _ParseAnalysisPluginOptions(self, options):
"""Parses the analysis plugin options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
# Get a list of all available plugins.
analysis_plugin_info = self._analysis_manager.GetAllPluginInformation()
# Use set-comprehension to create a set of the analysis plugin names.
analysis_plugin_names = {
name.lower() for name, _, _ in analysis_plugin_info}
analysis_plugins = self.ParseStringOption(options, 'analysis_plugins')
if not analysis_plugins:
return
# Use set-comprehension to create a set of the requested plugin names.
requested_plugin_names = {
name.strip().lower() for name in analysis_plugins.split(',')}
# Check to see if we are trying to load plugins that do not exist.
difference = requested_plugin_names.difference(analysis_plugin_names)
if difference:
raise errors.BadConfigOption(
'Non-existent analysis plugins specified: {0:s}'.format(
' '.join(difference)))
self._analysis_plugins = self._GetAnalysisPlugins(analysis_plugins)
for analysis_plugin in self._analysis_plugins:
helpers_manager.ArgumentHelperManager.ParseOptions(
options, analysis_plugin)
def _ParseInformationalOptions(self, options):
"""Parses the informational options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
super(PsortTool, self)._ParseInformationalOptions(options)
self._quiet_mode = getattr(options, 'quiet', False)
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=['status_view'])
def _ParseProcessingOptions(self, options):
"""Parses the processing options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
argument_helper_names = [
'process_resources', 'temporary_directory', 'zeromq']
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=argument_helper_names)
worker_memory_limit = getattr(options, 'worker_memory_limit', None)
if worker_memory_limit and worker_memory_limit < 0:
raise errors.BadConfigOption((
'Invalid worker memory limit: {0:d}, value must be 0 or '
'greater.').format(worker_memory_limit))
worker_timeout = getattr(options, 'worker_timeout', None)
if worker_timeout is not None and worker_timeout <= 0.0:
raise errors.BadConfigOption((
'Invalid worker timeout: {0:f}, value must be greater than '
'0.0 minutes.').format(worker_timeout))
self._worker_memory_limit = worker_memory_limit
self._worker_timeout = worker_timeout
def AddProcessingOptions(self, argument_group):
"""Adds processing options to the argument group
Args:
argument_group (argparse._ArgumentGroup): argparse argument group.
"""
argument_helper_names = ['temporary_directory', 'zeromq']
if self._CanEnforceProcessMemoryLimit():
argument_helper_names.append('process_resources')
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
argument_group, names=argument_helper_names)
argument_group.add_argument(
'--worker_memory_limit', '--worker-memory-limit',
dest='worker_memory_limit', action='store', type=int,
metavar='SIZE', help=(
'Maximum amount of memory (data segment and shared memory) '
'a worker process is allowed to consume in bytes, where 0 '
'represents no limit. The default limit is 2147483648 (2 GiB). '
'If a worker process exceeds this limit it is killed by the main '
'(foreman) process.'))
argument_group.add_argument(
'--worker_timeout', '--worker-timeout', dest='worker_timeout',
action='store', type=float, metavar='MINUTES', help=(
'Number of minutes before a worker process that is not providing '
'status updates is considered inactive. The default timeout is '
'15.0 minutes. If a worker process exceeds this timeout it is '
'killed by the main (foreman) process.'))
def ListLanguageIdentifiers(self):
"""Lists the language identifiers."""
table_view = views.ViewsFactory.GetTableView(
self._views_format_type, column_names=['Identifier', 'Language'],
title='Language identifiers')
for language_tag, description in (
language_tags.LanguageTagHelper.GetLanguages()):
table_view.AddRow([language_tag, description])
table_view.Write(self._output_writer)
def ParseArguments(self, arguments):
"""Parses the command line arguments.
Args:
arguments (list[str]): command line arguments.
Returns:
bool: True if the arguments were successfully parsed.
"""
loggers.ConfigureLogging()
argument_parser = argparse.ArgumentParser(
description=self.DESCRIPTION, add_help=False,
conflict_handler='resolve',
formatter_class=argparse.RawDescriptionHelpFormatter)
self.AddBasicOptions(argument_parser)
self.AddStorageOptions(argument_parser)
analysis_group = argument_parser.add_argument_group('Analysis Arguments')
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
analysis_group, names=['analysis_plugins'])
processing_group = argument_parser.add_argument_group('Processing')
self.AddProcessingOptions(processing_group)
info_group = argument_parser.add_argument_group('Informational Arguments')
self.AddLogFileOptions(info_group)
self.AddInformationalOptions(info_group)
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
info_group, names=['status_view'])
filter_group = argument_parser.add_argument_group('Filter Arguments')
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
filter_group, names=['event_filters'])
input_group = argument_parser.add_argument_group('Input Arguments')
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
input_group, names=['data_location'])
output_group = argument_parser.add_argument_group('Output Arguments')
output_group.add_argument(
'-a', '--include_all', '--include-all', action='store_false',
dest='dedup', default=True, help=(
'By default the psort removes duplicate entries from the '
'output. This parameter changes that behavior so all events '
'are included.'))
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
output_group, names=['language'])
self.AddOutputOptions(output_group)
output_format_group = argument_parser.add_argument_group(
'Output Format Arguments')
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
output_format_group, names=['output_modules'])
profiling_group = argument_parser.add_argument_group('profiling arguments')
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
profiling_group, names=['profiling'])
try:
# TODO: refactor how arguments is used in a more argparse way.
options = argument_parser.parse_args(arguments)
except UnicodeEncodeError:
# If we get here we are attempting to print help in a non-Unicode
# terminal.
self._output_writer.Write('\n')
self._output_writer.Write(argument_parser.format_help())
return False
# Properly prepare the attributes according to local encoding.
if self.preferred_encoding == 'ascii':
self._PrintUserWarning((
'the preferred encoding of your system is ASCII, which is not '
'optimal for the typically non-ASCII characters that need to be '
'parsed and processed. This will most likely result in an error.'))
try:
self.ParseOptions(options)
except errors.BadConfigOption as exception:
self._output_writer.Write('ERROR: {0!s}\n'.format(exception))
self._output_writer.Write('\n')
self._output_writer.Write(argument_parser.format_usage())
return False
self._WaitUserWarning()
loggers.ConfigureLogging(
debug_output=self._debug_mode, filename=self._log_file,
quiet_mode=self._quiet_mode)
return True
def ParseOptions(self, options):
"""Parses the options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
# The output modules options are dependent on the preferred_language
# and output_time_zone options.
self._ParseOutputOptions(options)
names = ['analysis_plugins', 'language', 'profiling']
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=names)
self.list_analysis_plugins = self._analysis_plugins == 'list'
self.list_language_identifiers = self._preferred_language == 'list'
self.list_profilers = self._profilers == 'list'
self.show_troubleshooting = getattr(options, 'show_troubleshooting', False)
if (self.list_analysis_plugins or self.list_language_identifiers or
self.list_profilers or self.list_time_zones or
self.show_troubleshooting):
return
# Check output modules after the other listable options, otherwise
# it could raise with "requires an output file".
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=['output_modules'])
self.list_output_modules = self._output_format == 'list'
if self.list_output_modules:
return
self._ParseInformationalOptions(options)
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=['data_location'])
output_mediator = self._CreateOutputMediator()
self._ReadMessageFormatters(output_mediator)
self._ParseLogFileOptions(options)
self._ParseProcessingOptions(options)
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=['event_filters'])
self._deduplicate_events = getattr(options, 'dedup', True)
if self._data_location:
# Update the data location with the calculated value.
options.data_location = self._data_location
else:
logger.warning('Unable to automatically determine data location.')
self._command_line_arguments = self.GetCommandLineArguments()
# TODO: move check into _CheckStorageFile.
self._storage_file_path = self.ParseStringOption(options, 'storage_file')
self._CheckStorageFile(self._storage_file_path)
self._EnforceProcessMemoryLimit(self._process_memory_limit)
self._analysis_plugins = self._CreateAnalysisPlugins(options)
self._output_module = self._CreateOutputModule(output_mediator, options)
def ProcessStorage(self):
"""Processes a plaso storage file.
Raises:
BadConfigOption: when a configuration parameter fails validation or the
storage file cannot be opened with read access.
RuntimeError: if a non-recoverable situation is encountered.
"""
self._status_view.SetMode(self._status_view_mode)
self._status_view.SetStorageFileInformation(self._storage_file_path)
status_update_callback = (
self._status_view.GetAnalysisStatusUpdateCallback())
session = engine.BaseEngine.CreateSession(
command_line_arguments=self._command_line_arguments,
preferred_encoding=self.preferred_encoding)
storage_reader = storage_factory.StorageFactory.CreateStorageReaderForFile(
self._storage_file_path)
if not storage_reader:
raise RuntimeError('Unable to create storage reader.')
try:
for session in storage_reader.GetSessions():
for source_configuration in session.source_configurations or []:
self._knowledge_base.ReadSystemConfigurationArtifact(
source_configuration.system_configuration,
session_identifier=session.identifier)
self._knowledge_base.SetTextPrepend(session.text_prepend)
self._number_of_analysis_reports = (
storage_reader.GetNumberOfAttributeContainers(
self._CONTAINER_TYPE_ANALYSIS_REPORT))
finally:
storage_reader.Close()
configuration = configurations.ProcessingConfiguration()
configuration.data_location = self._data_location
configuration.debug_output = self._debug_mode
configuration.log_filename = self._log_file
configuration.profiling.directory = self._profiling_directory
configuration.profiling.sample_rate = self._profiling_sample_rate
configuration.profiling.profilers = self._profilers
analysis_counter = None
if self._analysis_plugins:
self._AnalyzeEvents(
session, configuration, status_update_callback=status_update_callback)
analysis_counter = collections.Counter()
for item, value in session.analysis_reports_counter.items():
analysis_counter[item] = value
if self._output_format != 'null':
storage_reader = (
storage_factory.StorageFactory.CreateStorageReaderForFile(
self._storage_file_path))
self._output_module.SetStorageReader(storage_reader)
# TODO: add single process output and formatting engine support.
output_engine = (
multi_output_engine.OutputAndFormattingMultiProcessEngine())
output_engine.ExportEvents(
self._knowledge_base, storage_reader, self._output_module,
configuration, deduplicate_events=self._deduplicate_events,
event_filter=self._event_filter,
status_update_callback=status_update_callback,
time_slice=self._time_slice, use_time_slicer=self._use_time_slicer)
self._output_module.Close()
self._output_module = None
if self._quiet_mode:
return
self._output_writer.Write('Processing completed.\n')
if analysis_counter:
table_view = views.ViewsFactory.GetTableView(
self._views_format_type, title='Analysis reports generated')
for element, count in analysis_counter.most_common():
if element != 'total':
table_view.AddRow([element, count])
table_view.AddRow(['Total', analysis_counter['total']])
table_view.Write(self._output_writer)
storage_reader = storage_factory.StorageFactory.CreateStorageReaderForFile(
self._storage_file_path)
self._PrintAnalysisReportsDetails(storage_reader) | plaso/cli/psort_tool.py | """The psort CLI tool."""
import argparse
import collections
import os
# The following import makes sure the filters are registered.
from plaso import filters # pylint: disable=unused-import
# The following import makes sure the output modules are registered.
from plaso import output # pylint: disable=unused-import
from plaso.cli import analysis_tool
from plaso.cli import logger
from plaso.cli import status_view
from plaso.cli import tool_options
from plaso.cli import views
from plaso.cli.helpers import manager as helpers_manager
from plaso.containers import reports
from plaso.engine import configurations
from plaso.engine import engine
from plaso.helpers import language_tags
from plaso.lib import errors
from plaso.lib import loggers
from plaso.multi_process import output_engine as multi_output_engine
from plaso.storage import factory as storage_factory
class PsortTool(
analysis_tool.AnalysisTool,
tool_options.OutputModuleOptions):
"""Psort CLI tool.
Attributes:
list_analysis_plugins (bool): True if information about the analysis
plugins should be shown.
list_language_identifiers (bool): True if information about the language
identifiers should be shown.
list_output_modules (bool): True if information about the output modules
should be shown.
list_profilers (bool): True if the profilers should be listed.
"""
NAME = 'psort'
DESCRIPTION = (
'Application to read, filter and process output from a plaso storage '
'file.')
_CONTAINER_TYPE_ANALYSIS_REPORT = reports.AnalysisReport.CONTAINER_TYPE
def __init__(self, input_reader=None, output_writer=None):
"""Initializes the CLI tool object.
Args:
input_reader (Optional[InputReader]): input reader, where None indicates
that the stdin input reader should be used.
output_writer (Optional[OutputWriter]): output writer, where None
indicates that the stdout output writer should be used.
"""
super(PsortTool, self).__init__(
input_reader=input_reader, output_writer=output_writer)
self._command_line_arguments = None
self._deduplicate_events = True
self._preferred_language = 'en-US'
self._process_memory_limit = None
self._status_view_mode = status_view.StatusView.MODE_WINDOW
self._status_view = status_view.StatusView(self._output_writer, self.NAME)
self._time_slice = None
self._use_time_slicer = False
self.list_language_identifiers = False
self.list_output_modules = False
self.list_profilers = False
def _CheckStorageFile(self, storage_file_path): # pylint: disable=arguments-differ
"""Checks if the storage file path is valid.
Args:
storage_file_path (str): path of the storage file.
Raises:
BadConfigOption: if the storage file path is invalid.
"""
if not storage_file_path:
raise errors.BadConfigOption('Missing storage file option.')
if not os.path.exists(storage_file_path):
raise errors.BadConfigOption(
'No such storage file: {0:s}.'.format(storage_file_path))
if not os.path.isfile(storage_file_path):
raise errors.BadConfigOption(
'Storage file: {0:s} already exists and is not a file.'.format(
storage_file_path))
storage_file_directory = os.path.dirname(storage_file_path) or '.'
if not os.access(storage_file_directory, os.W_OK):
raise errors.BadConfigOption(
'Unable to write to storage file: {0:s}'.format(storage_file_path))
if not storage_factory.StorageFactory.CheckStorageFileHasSupportedFormat(
storage_file_path, check_readable_only=False):
raise errors.BadConfigOption(
'Format of storage file: {0:s} not supported'.format(
storage_file_path))
def _GetAnalysisPlugins(self, analysis_plugins_string):
"""Retrieves analysis plugins.
Args:
analysis_plugins_string (str): comma separated names of analysis plugins
to enable.
Returns:
list[AnalysisPlugin]: analysis plugins.
"""
if not analysis_plugins_string:
return []
analysis_plugins_list = [
name.strip() for name in analysis_plugins_string.split(',')]
analysis_plugins = self._analysis_manager.GetPluginObjects(
analysis_plugins_list)
return analysis_plugins.values()
def _ParseAnalysisPluginOptions(self, options):
"""Parses the analysis plugin options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
# Get a list of all available plugins.
analysis_plugin_info = self._analysis_manager.GetAllPluginInformation()
# Use set-comprehension to create a set of the analysis plugin names.
analysis_plugin_names = {
name.lower() for name, _, _ in analysis_plugin_info}
analysis_plugins = self.ParseStringOption(options, 'analysis_plugins')
if not analysis_plugins:
return
# Use set-comprehension to create a set of the requested plugin names.
requested_plugin_names = {
name.strip().lower() for name in analysis_plugins.split(',')}
# Check to see if we are trying to load plugins that do not exist.
difference = requested_plugin_names.difference(analysis_plugin_names)
if difference:
raise errors.BadConfigOption(
'Non-existent analysis plugins specified: {0:s}'.format(
' '.join(difference)))
self._analysis_plugins = self._GetAnalysisPlugins(analysis_plugins)
for analysis_plugin in self._analysis_plugins:
helpers_manager.ArgumentHelperManager.ParseOptions(
options, analysis_plugin)
def _ParseInformationalOptions(self, options):
"""Parses the informational options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
super(PsortTool, self)._ParseInformationalOptions(options)
self._quiet_mode = getattr(options, 'quiet', False)
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=['status_view'])
def _ParseProcessingOptions(self, options):
"""Parses the processing options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
argument_helper_names = [
'process_resources', 'temporary_directory', 'zeromq']
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=argument_helper_names)
worker_memory_limit = getattr(options, 'worker_memory_limit', None)
if worker_memory_limit and worker_memory_limit < 0:
raise errors.BadConfigOption((
'Invalid worker memory limit: {0:d}, value must be 0 or '
'greater.').format(worker_memory_limit))
worker_timeout = getattr(options, 'worker_timeout', None)
if worker_timeout is not None and worker_timeout <= 0.0:
raise errors.BadConfigOption((
'Invalid worker timeout: {0:f}, value must be greater than '
'0.0 minutes.').format(worker_timeout))
self._worker_memory_limit = worker_memory_limit
self._worker_timeout = worker_timeout
def AddProcessingOptions(self, argument_group):
"""Adds processing options to the argument group
Args:
argument_group (argparse._ArgumentGroup): argparse argument group.
"""
argument_helper_names = ['temporary_directory', 'zeromq']
if self._CanEnforceProcessMemoryLimit():
argument_helper_names.append('process_resources')
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
argument_group, names=argument_helper_names)
argument_group.add_argument(
'--worker_memory_limit', '--worker-memory-limit',
dest='worker_memory_limit', action='store', type=int,
metavar='SIZE', help=(
'Maximum amount of memory (data segment and shared memory) '
'a worker process is allowed to consume in bytes, where 0 '
'represents no limit. The default limit is 2147483648 (2 GiB). '
'If a worker process exceeds this limit it is killed by the main '
'(foreman) process.'))
argument_group.add_argument(
'--worker_timeout', '--worker-timeout', dest='worker_timeout',
action='store', type=float, metavar='MINUTES', help=(
'Number of minutes before a worker process that is not providing '
'status updates is considered inactive. The default timeout is '
'15.0 minutes. If a worker process exceeds this timeout it is '
'killed by the main (foreman) process.'))
def ListLanguageIdentifiers(self):
"""Lists the language identifiers."""
table_view = views.ViewsFactory.GetTableView(
self._views_format_type, column_names=['Identifier', 'Language'],
title='Language identifiers')
for language_tag, description in (
language_tags.LanguageTagHelper.GetLanguages()):
table_view.AddRow([language_tag, description])
table_view.Write(self._output_writer)
def ParseArguments(self, arguments):
"""Parses the command line arguments.
Args:
arguments (list[str]): command line arguments.
Returns:
bool: True if the arguments were successfully parsed.
"""
loggers.ConfigureLogging()
argument_parser = argparse.ArgumentParser(
description=self.DESCRIPTION, add_help=False,
conflict_handler='resolve',
formatter_class=argparse.RawDescriptionHelpFormatter)
self.AddBasicOptions(argument_parser)
self.AddStorageOptions(argument_parser)
analysis_group = argument_parser.add_argument_group('Analysis Arguments')
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
analysis_group, names=['analysis_plugins'])
processing_group = argument_parser.add_argument_group('Processing')
self.AddProcessingOptions(processing_group)
info_group = argument_parser.add_argument_group('Informational Arguments')
self.AddLogFileOptions(info_group)
self.AddInformationalOptions(info_group)
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
info_group, names=['status_view'])
filter_group = argument_parser.add_argument_group('Filter Arguments')
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
filter_group, names=['event_filters'])
input_group = argument_parser.add_argument_group('Input Arguments')
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
input_group, names=['data_location'])
output_group = argument_parser.add_argument_group('Output Arguments')
output_group.add_argument(
'-a', '--include_all', '--include-all', action='store_false',
dest='dedup', default=True, help=(
'By default the psort removes duplicate entries from the '
'output. This parameter changes that behavior so all events '
'are included.'))
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
output_group, names=['language'])
self.AddOutputOptions(output_group)
output_format_group = argument_parser.add_argument_group(
'Output Format Arguments')
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
output_format_group, names=['output_modules'])
profiling_group = argument_parser.add_argument_group('profiling arguments')
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
profiling_group, names=['profiling'])
try:
# TODO: refactor how arguments is used in a more argparse way.
options = argument_parser.parse_args(arguments)
except UnicodeEncodeError:
# If we get here we are attempting to print help in a non-Unicode
# terminal.
self._output_writer.Write('\n')
self._output_writer.Write(argument_parser.format_help())
return False
# Properly prepare the attributes according to local encoding.
if self.preferred_encoding == 'ascii':
self._PrintUserWarning((
'the preferred encoding of your system is ASCII, which is not '
'optimal for the typically non-ASCII characters that need to be '
'parsed and processed. This will most likely result in an error.'))
try:
self.ParseOptions(options)
except errors.BadConfigOption as exception:
self._output_writer.Write('ERROR: {0!s}\n'.format(exception))
self._output_writer.Write('\n')
self._output_writer.Write(argument_parser.format_usage())
return False
self._WaitUserWarning()
loggers.ConfigureLogging(
debug_output=self._debug_mode, filename=self._log_file,
quiet_mode=self._quiet_mode)
return True
def ParseOptions(self, options):
"""Parses the options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
# The output modules options are dependent on the preferred_language
# and output_time_zone options.
self._ParseOutputOptions(options)
names = ['analysis_plugins', 'language', 'profiling']
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=names)
self.list_analysis_plugins = self._analysis_plugins == 'list'
self.list_language_identifiers = self._preferred_language == 'list'
self.list_profilers = self._profilers == 'list'
self.show_troubleshooting = getattr(options, 'show_troubleshooting', False)
if (self.list_analysis_plugins or self.list_language_identifiers or
self.list_profilers or self.list_time_zones or
self.show_troubleshooting):
return
# Check output modules after the other listable options, otherwise
# it could raise with "requires an output file".
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=['output_modules'])
self.list_output_modules = self._output_format == 'list'
if self.list_output_modules:
return
self._ParseInformationalOptions(options)
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=['data_location'])
output_mediator = self._CreateOutputMediator()
self._ReadMessageFormatters(output_mediator)
self._ParseLogFileOptions(options)
self._ParseProcessingOptions(options)
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=['event_filters'])
self._deduplicate_events = getattr(options, 'dedup', True)
if self._data_location:
# Update the data location with the calculated value.
options.data_location = self._data_location
else:
logger.warning('Unable to automatically determine data location.')
self._command_line_arguments = self.GetCommandLineArguments()
# TODO: move check into _CheckStorageFile.
self._storage_file_path = self.ParseStringOption(options, 'storage_file')
self._CheckStorageFile(self._storage_file_path)
self._EnforceProcessMemoryLimit(self._process_memory_limit)
self._analysis_plugins = self._CreateAnalysisPlugins(options)
self._output_module = self._CreateOutputModule(output_mediator, options)
def ProcessStorage(self):
"""Processes a plaso storage file.
Raises:
BadConfigOption: when a configuration parameter fails validation or the
storage file cannot be opened with read access.
RuntimeError: if a non-recoverable situation is encountered.
"""
self._status_view.SetMode(self._status_view_mode)
self._status_view.SetStorageFileInformation(self._storage_file_path)
status_update_callback = (
self._status_view.GetAnalysisStatusUpdateCallback())
session = engine.BaseEngine.CreateSession(
command_line_arguments=self._command_line_arguments,
preferred_encoding=self.preferred_encoding)
storage_reader = storage_factory.StorageFactory.CreateStorageReaderForFile(
self._storage_file_path)
if not storage_reader:
raise RuntimeError('Unable to create storage reader.')
try:
for session in storage_reader.GetSessions():
for source_configuration in session.source_configurations or []:
self._knowledge_base.ReadSystemConfigurationArtifact(
source_configuration.system_configuration,
session_identifier=session.identifier)
self._knowledge_base.SetTextPrepend(session.text_prepend)
self._number_of_analysis_reports = (
storage_reader.GetNumberOfAttributeContainers(
self._CONTAINER_TYPE_ANALYSIS_REPORT))
finally:
storage_reader.Close()
configuration = configurations.ProcessingConfiguration()
configuration.data_location = self._data_location
configuration.debug_output = self._debug_mode
configuration.log_filename = self._log_file
configuration.profiling.directory = self._profiling_directory
configuration.profiling.sample_rate = self._profiling_sample_rate
configuration.profiling.profilers = self._profilers
analysis_counter = None
if self._analysis_plugins:
self._AnalyzeEvents(
session, configuration, status_update_callback=status_update_callback)
analysis_counter = collections.Counter()
for item, value in session.analysis_reports_counter.items():
analysis_counter[item] = value
if self._output_format != 'null':
storage_reader = (
storage_factory.StorageFactory.CreateStorageReaderForFile(
self._storage_file_path))
self._output_module.SetStorageReader(storage_reader)
# TODO: add single process output and formatting engine support.
output_engine = (
multi_output_engine.OutputAndFormattingMultiProcessEngine())
output_engine.ExportEvents(
self._knowledge_base, storage_reader, self._output_module,
configuration, deduplicate_events=self._deduplicate_events,
event_filter=self._event_filter,
status_update_callback=status_update_callback,
time_slice=self._time_slice, use_time_slicer=self._use_time_slicer)
self._output_module.Close()
self._output_module = None
if self._quiet_mode:
return
self._output_writer.Write('Processing completed.\n')
if analysis_counter:
table_view = views.ViewsFactory.GetTableView(
self._views_format_type, title='Analysis reports generated')
for element, count in analysis_counter.most_common():
if element != 'total':
table_view.AddRow([element, count])
table_view.AddRow(['Total', analysis_counter['total']])
table_view.Write(self._output_writer)
storage_reader = storage_factory.StorageFactory.CreateStorageReaderForFile(
self._storage_file_path)
self._PrintAnalysisReportsDetails(storage_reader) | 0.74382 | 0.179567 |
import copy
import logging
import socket
from keystoneauth1 import adapter
from keystoneauth1 import exceptions as ksa_exc
import OpenSSL
from oslo_utils import importutils
from oslo_utils import netutils
import requests
import six
try:
import json
except ImportError:
import simplejson as json
from oslo_utils import encodeutils
from glanceclient.common import utils
from glanceclient import exc
osprofiler_web = importutils.try_import("osprofiler.web")
LOG = logging.getLogger(__name__)
USER_AGENT = 'python-glanceclient'
CHUNKSIZE = 1024 * 64 # 64kB
REQ_ID_HEADER = 'X-OpenStack-Request-ID'
def encode_headers(headers):
"""Encodes headers.
Note: This should be used right before
sending anything out.
:param headers: Headers to encode
:returns: Dictionary with encoded headers'
names and values
"""
return dict((encodeutils.safe_encode(h), encodeutils.safe_encode(v))
for h, v in headers.items() if v is not None)
class _BaseHTTPClient(object):
@staticmethod
def _chunk_body(body):
chunk = body
while chunk:
chunk = body.read(CHUNKSIZE)
if not chunk:
break
yield chunk
def _set_common_request_kwargs(self, headers, kwargs):
"""Handle the common parameters used to send the request."""
# Default Content-Type is octet-stream
content_type = headers.get('Content-Type', 'application/octet-stream')
# NOTE(jamielennox): remove this later. Managers should pass json= if
# they want to send json data.
data = kwargs.pop("data", None)
if data is not None and not isinstance(data, six.string_types):
try:
data = json.dumps(data)
content_type = 'application/json'
except TypeError:
# Here we assume it's
# a file-like object
# and we'll chunk it
data = self._chunk_body(data)
headers['Content-Type'] = content_type
kwargs['stream'] = content_type == 'application/octet-stream'
return data
def _handle_response(self, resp):
if not resp.ok:
LOG.debug("Request returned failure status %s.", resp.status_code)
raise exc.from_response(resp, resp.content)
elif (resp.status_code == requests.codes.MULTIPLE_CHOICES and
resp.request.path_url != '/versions'):
# NOTE(flaper87): Eventually, we'll remove the check on `versions`
# which is a bug (1491350) on the server.
raise exc.from_response(resp)
content_type = resp.headers.get('Content-Type')
# Read body into string if it isn't obviously image data
if content_type == 'application/octet-stream':
# Do not read all response in memory when downloading an image.
body_iter = _close_after_stream(resp, CHUNKSIZE)
else:
content = resp.text
if content_type and content_type.startswith('application/json'):
# Let's use requests json method, it should take care of
# response encoding
body_iter = resp.json()
else:
body_iter = six.StringIO(content)
try:
body_iter = json.loads(''.join([c for c in body_iter]))
except ValueError:
body_iter = None
return resp, body_iter
class HTTPClient(_BaseHTTPClient):
def __init__(self, endpoint, **kwargs):
self.endpoint = endpoint
self.identity_headers = kwargs.get('identity_headers')
self.auth_token = kwargs.get('token')
self.language_header = kwargs.get('language_header')
self.global_request_id = kwargs.get('global_request_id')
if self.identity_headers:
self.auth_token = self.identity_headers.pop('X-Auth-Token',
self.auth_token)
self.session = requests.Session()
self.session.headers["User-Agent"] = USER_AGENT
if self.language_header:
self.session.headers["Accept-Language"] = self.language_header
self.timeout = float(kwargs.get('timeout', 600))
if self.endpoint.startswith("https"):
if kwargs.get('insecure', False) is True:
self.session.verify = False
else:
if kwargs.get('cacert', None) is not '':
self.session.verify = kwargs.get('cacert', True)
self.session.cert = (kwargs.get('cert_file'),
kwargs.get('key_file'))
@staticmethod
def parse_endpoint(endpoint):
return netutils.urlsplit(endpoint)
def log_curl_request(self, method, url, headers, data, kwargs):
curl = ['curl -g -i -X %s' % method]
headers = copy.deepcopy(headers)
headers.update(self.session.headers)
for (key, value) in headers.items():
header = '-H \'%s: %s\'' % utils.safe_header(key, value)
curl.append(header)
if not self.session.verify:
curl.append('-k')
else:
if isinstance(self.session.verify, six.string_types):
curl.append(' --cacert %s' % self.session.verify)
if self.session.cert:
curl.append(' --cert %s --key %s' % self.session.cert)
if data and isinstance(data, six.string_types):
curl.append('-d \'%s\'' % data)
curl.append(url)
msg = ' '.join([encodeutils.safe_decode(item, errors='ignore')
for item in curl])
LOG.debug(msg)
@staticmethod
def log_http_response(resp):
status = (resp.raw.version / 10.0, resp.status_code, resp.reason)
dump = ['\nHTTP/%.1f %s %s' % status]
headers = resp.headers.items()
dump.extend(['%s: %s' % utils.safe_header(k, v) for k, v in headers])
dump.append('')
content_type = resp.headers.get('Content-Type')
if content_type != 'application/octet-stream':
dump.extend([resp.text, ''])
LOG.debug('\n'.join([encodeutils.safe_decode(x, errors='ignore')
for x in dump]))
def _request(self, method, url, **kwargs):
"""Send an http request with the specified characteristics.
Wrapper around httplib.HTTP(S)Connection.request to handle tasks such
as setting headers and error handling.
"""
# Copy the kwargs so we can reuse the original in case of redirects
headers = copy.deepcopy(kwargs.pop('headers', {}))
if self.identity_headers:
for k, v in self.identity_headers.items():
headers.setdefault(k, v)
data = self._set_common_request_kwargs(headers, kwargs)
# add identity header to the request
if not headers.get('X-Auth-Token'):
headers['X-Auth-Token'] = self.auth_token
if self.global_request_id:
headers.setdefault(REQ_ID_HEADER, self.global_request_id)
if osprofiler_web:
headers.update(osprofiler_web.get_trace_id_headers())
# Note(flaper87): Before letting headers / url fly,
# they should be encoded otherwise httplib will
# complain.
headers = encode_headers(headers)
if self.endpoint.endswith("/") or url.startswith("/"):
conn_url = "%s%s" % (self.endpoint, url)
else:
conn_url = "%s/%s" % (self.endpoint, url)
self.log_curl_request(method, conn_url, headers, data, kwargs)
try:
resp = self.session.request(method,
conn_url,
data=data,
headers=headers,
**kwargs)
except requests.exceptions.Timeout as e:
message = ("Error communicating with %(url)s: %(e)s" %
dict(url=conn_url, e=e))
raise exc.InvalidEndpoint(message=message)
except requests.exceptions.ConnectionError as e:
message = ("Error finding address for %(url)s: %(e)s" %
dict(url=conn_url, e=e))
raise exc.CommunicationError(message=message)
except socket.gaierror as e:
message = "Error finding address for %s: %s" % (
self.endpoint_hostname, e)
raise exc.InvalidEndpoint(message=message)
except (socket.error, socket.timeout, IOError) as e:
endpoint = self.endpoint
message = ("Error communicating with %(endpoint)s %(e)s" %
{'endpoint': endpoint, 'e': e})
raise exc.CommunicationError(message=message)
except OpenSSL.SSL.Error as e:
message = ("SSL Error communicating with %(url)s: %(e)s" %
{'url': conn_url, 'e': e})
raise exc.CommunicationError(message=message)
# log request-id for each api call
request_id = resp.headers.get('x-openstack-request-id')
if request_id:
LOG.debug('%(method)s call to image for '
'%(url)s used request id '
'%(response_request_id)s',
{'method': resp.request.method,
'url': resp.url,
'response_request_id': request_id})
resp, body_iter = self._handle_response(resp)
self.log_http_response(resp)
return resp, body_iter
def head(self, url, **kwargs):
return self._request('HEAD', url, **kwargs)
def get(self, url, **kwargs):
return self._request('GET', url, **kwargs)
def post(self, url, **kwargs):
return self._request('POST', url, **kwargs)
def put(self, url, **kwargs):
return self._request('PUT', url, **kwargs)
def patch(self, url, **kwargs):
return self._request('PATCH', url, **kwargs)
def delete(self, url, **kwargs):
return self._request('DELETE', url, **kwargs)
def _close_after_stream(response, chunk_size):
"""Iterate over the content and ensure the response is closed after."""
# Yield each chunk in the response body
for chunk in response.iter_content(chunk_size=chunk_size):
yield chunk
# Once we're done streaming the body, ensure everything is closed.
# This will return the connection to the HTTPConnectionPool in urllib3
# and ideally reduce the number of HTTPConnectionPool full warnings.
response.close()
class SessionClient(adapter.Adapter, _BaseHTTPClient):
def __init__(self, session, **kwargs):
kwargs.setdefault('user_agent', USER_AGENT)
kwargs.setdefault('service_type', 'image')
self.global_request_id = kwargs.pop('global_request_id', None)
super(SessionClient, self).__init__(session, **kwargs)
def request(self, url, method, **kwargs):
headers = kwargs.pop('headers', {})
if self.global_request_id:
headers.setdefault(REQ_ID_HEADER, self.global_request_id)
kwargs['raise_exc'] = False
data = self._set_common_request_kwargs(headers, kwargs)
try:
# NOTE(pumaranikar): To avoid bug #1641239, no modification of
# headers should be allowed after encode_headers() is called.
resp = super(SessionClient,
self).request(url,
method,
headers=encode_headers(headers),
data=data,
**kwargs)
except ksa_exc.ConnectTimeout as e:
conn_url = self.get_endpoint(auth=kwargs.get('auth'))
conn_url = "%s/%s" % (conn_url.rstrip('/'), url.lstrip('/'))
message = ("Error communicating with %(url)s %(e)s" %
dict(url=conn_url, e=e))
raise exc.InvalidEndpoint(message=message)
except ksa_exc.ConnectFailure as e:
conn_url = self.get_endpoint(auth=kwargs.get('auth'))
conn_url = "%s/%s" % (conn_url.rstrip('/'), url.lstrip('/'))
message = ("Error finding address for %(url)s: %(e)s" %
dict(url=conn_url, e=e))
raise exc.CommunicationError(message=message)
return self._handle_response(resp)
def get_http_client(endpoint=None, session=None, **kwargs):
if session:
return SessionClient(session, **kwargs)
elif endpoint:
return HTTPClient(endpoint, **kwargs)
else:
raise AttributeError('Constructing a client must contain either an '
'endpoint or a session') | glanceclient/common/http.py |
import copy
import logging
import socket
from keystoneauth1 import adapter
from keystoneauth1 import exceptions as ksa_exc
import OpenSSL
from oslo_utils import importutils
from oslo_utils import netutils
import requests
import six
try:
import json
except ImportError:
import simplejson as json
from oslo_utils import encodeutils
from glanceclient.common import utils
from glanceclient import exc
osprofiler_web = importutils.try_import("osprofiler.web")
LOG = logging.getLogger(__name__)
USER_AGENT = 'python-glanceclient'
CHUNKSIZE = 1024 * 64 # 64kB
REQ_ID_HEADER = 'X-OpenStack-Request-ID'
def encode_headers(headers):
"""Encodes headers.
Note: This should be used right before
sending anything out.
:param headers: Headers to encode
:returns: Dictionary with encoded headers'
names and values
"""
return dict((encodeutils.safe_encode(h), encodeutils.safe_encode(v))
for h, v in headers.items() if v is not None)
class _BaseHTTPClient(object):
@staticmethod
def _chunk_body(body):
chunk = body
while chunk:
chunk = body.read(CHUNKSIZE)
if not chunk:
break
yield chunk
def _set_common_request_kwargs(self, headers, kwargs):
"""Handle the common parameters used to send the request."""
# Default Content-Type is octet-stream
content_type = headers.get('Content-Type', 'application/octet-stream')
# NOTE(jamielennox): remove this later. Managers should pass json= if
# they want to send json data.
data = kwargs.pop("data", None)
if data is not None and not isinstance(data, six.string_types):
try:
data = json.dumps(data)
content_type = 'application/json'
except TypeError:
# Here we assume it's
# a file-like object
# and we'll chunk it
data = self._chunk_body(data)
headers['Content-Type'] = content_type
kwargs['stream'] = content_type == 'application/octet-stream'
return data
def _handle_response(self, resp):
if not resp.ok:
LOG.debug("Request returned failure status %s.", resp.status_code)
raise exc.from_response(resp, resp.content)
elif (resp.status_code == requests.codes.MULTIPLE_CHOICES and
resp.request.path_url != '/versions'):
# NOTE(flaper87): Eventually, we'll remove the check on `versions`
# which is a bug (1491350) on the server.
raise exc.from_response(resp)
content_type = resp.headers.get('Content-Type')
# Read body into string if it isn't obviously image data
if content_type == 'application/octet-stream':
# Do not read all response in memory when downloading an image.
body_iter = _close_after_stream(resp, CHUNKSIZE)
else:
content = resp.text
if content_type and content_type.startswith('application/json'):
# Let's use requests json method, it should take care of
# response encoding
body_iter = resp.json()
else:
body_iter = six.StringIO(content)
try:
body_iter = json.loads(''.join([c for c in body_iter]))
except ValueError:
body_iter = None
return resp, body_iter
class HTTPClient(_BaseHTTPClient):
def __init__(self, endpoint, **kwargs):
self.endpoint = endpoint
self.identity_headers = kwargs.get('identity_headers')
self.auth_token = kwargs.get('token')
self.language_header = kwargs.get('language_header')
self.global_request_id = kwargs.get('global_request_id')
if self.identity_headers:
self.auth_token = self.identity_headers.pop('X-Auth-Token',
self.auth_token)
self.session = requests.Session()
self.session.headers["User-Agent"] = USER_AGENT
if self.language_header:
self.session.headers["Accept-Language"] = self.language_header
self.timeout = float(kwargs.get('timeout', 600))
if self.endpoint.startswith("https"):
if kwargs.get('insecure', False) is True:
self.session.verify = False
else:
if kwargs.get('cacert', None) is not '':
self.session.verify = kwargs.get('cacert', True)
self.session.cert = (kwargs.get('cert_file'),
kwargs.get('key_file'))
@staticmethod
def parse_endpoint(endpoint):
return netutils.urlsplit(endpoint)
def log_curl_request(self, method, url, headers, data, kwargs):
curl = ['curl -g -i -X %s' % method]
headers = copy.deepcopy(headers)
headers.update(self.session.headers)
for (key, value) in headers.items():
header = '-H \'%s: %s\'' % utils.safe_header(key, value)
curl.append(header)
if not self.session.verify:
curl.append('-k')
else:
if isinstance(self.session.verify, six.string_types):
curl.append(' --cacert %s' % self.session.verify)
if self.session.cert:
curl.append(' --cert %s --key %s' % self.session.cert)
if data and isinstance(data, six.string_types):
curl.append('-d \'%s\'' % data)
curl.append(url)
msg = ' '.join([encodeutils.safe_decode(item, errors='ignore')
for item in curl])
LOG.debug(msg)
@staticmethod
def log_http_response(resp):
status = (resp.raw.version / 10.0, resp.status_code, resp.reason)
dump = ['\nHTTP/%.1f %s %s' % status]
headers = resp.headers.items()
dump.extend(['%s: %s' % utils.safe_header(k, v) for k, v in headers])
dump.append('')
content_type = resp.headers.get('Content-Type')
if content_type != 'application/octet-stream':
dump.extend([resp.text, ''])
LOG.debug('\n'.join([encodeutils.safe_decode(x, errors='ignore')
for x in dump]))
def _request(self, method, url, **kwargs):
"""Send an http request with the specified characteristics.
Wrapper around httplib.HTTP(S)Connection.request to handle tasks such
as setting headers and error handling.
"""
# Copy the kwargs so we can reuse the original in case of redirects
headers = copy.deepcopy(kwargs.pop('headers', {}))
if self.identity_headers:
for k, v in self.identity_headers.items():
headers.setdefault(k, v)
data = self._set_common_request_kwargs(headers, kwargs)
# add identity header to the request
if not headers.get('X-Auth-Token'):
headers['X-Auth-Token'] = self.auth_token
if self.global_request_id:
headers.setdefault(REQ_ID_HEADER, self.global_request_id)
if osprofiler_web:
headers.update(osprofiler_web.get_trace_id_headers())
# Note(flaper87): Before letting headers / url fly,
# they should be encoded otherwise httplib will
# complain.
headers = encode_headers(headers)
if self.endpoint.endswith("/") or url.startswith("/"):
conn_url = "%s%s" % (self.endpoint, url)
else:
conn_url = "%s/%s" % (self.endpoint, url)
self.log_curl_request(method, conn_url, headers, data, kwargs)
try:
resp = self.session.request(method,
conn_url,
data=data,
headers=headers,
**kwargs)
except requests.exceptions.Timeout as e:
message = ("Error communicating with %(url)s: %(e)s" %
dict(url=conn_url, e=e))
raise exc.InvalidEndpoint(message=message)
except requests.exceptions.ConnectionError as e:
message = ("Error finding address for %(url)s: %(e)s" %
dict(url=conn_url, e=e))
raise exc.CommunicationError(message=message)
except socket.gaierror as e:
message = "Error finding address for %s: %s" % (
self.endpoint_hostname, e)
raise exc.InvalidEndpoint(message=message)
except (socket.error, socket.timeout, IOError) as e:
endpoint = self.endpoint
message = ("Error communicating with %(endpoint)s %(e)s" %
{'endpoint': endpoint, 'e': e})
raise exc.CommunicationError(message=message)
except OpenSSL.SSL.Error as e:
message = ("SSL Error communicating with %(url)s: %(e)s" %
{'url': conn_url, 'e': e})
raise exc.CommunicationError(message=message)
# log request-id for each api call
request_id = resp.headers.get('x-openstack-request-id')
if request_id:
LOG.debug('%(method)s call to image for '
'%(url)s used request id '
'%(response_request_id)s',
{'method': resp.request.method,
'url': resp.url,
'response_request_id': request_id})
resp, body_iter = self._handle_response(resp)
self.log_http_response(resp)
return resp, body_iter
def head(self, url, **kwargs):
return self._request('HEAD', url, **kwargs)
def get(self, url, **kwargs):
return self._request('GET', url, **kwargs)
def post(self, url, **kwargs):
return self._request('POST', url, **kwargs)
def put(self, url, **kwargs):
return self._request('PUT', url, **kwargs)
def patch(self, url, **kwargs):
return self._request('PATCH', url, **kwargs)
def delete(self, url, **kwargs):
return self._request('DELETE', url, **kwargs)
def _close_after_stream(response, chunk_size):
"""Iterate over the content and ensure the response is closed after."""
# Yield each chunk in the response body
for chunk in response.iter_content(chunk_size=chunk_size):
yield chunk
# Once we're done streaming the body, ensure everything is closed.
# This will return the connection to the HTTPConnectionPool in urllib3
# and ideally reduce the number of HTTPConnectionPool full warnings.
response.close()
class SessionClient(adapter.Adapter, _BaseHTTPClient):
def __init__(self, session, **kwargs):
kwargs.setdefault('user_agent', USER_AGENT)
kwargs.setdefault('service_type', 'image')
self.global_request_id = kwargs.pop('global_request_id', None)
super(SessionClient, self).__init__(session, **kwargs)
def request(self, url, method, **kwargs):
headers = kwargs.pop('headers', {})
if self.global_request_id:
headers.setdefault(REQ_ID_HEADER, self.global_request_id)
kwargs['raise_exc'] = False
data = self._set_common_request_kwargs(headers, kwargs)
try:
# NOTE(pumaranikar): To avoid bug #1641239, no modification of
# headers should be allowed after encode_headers() is called.
resp = super(SessionClient,
self).request(url,
method,
headers=encode_headers(headers),
data=data,
**kwargs)
except ksa_exc.ConnectTimeout as e:
conn_url = self.get_endpoint(auth=kwargs.get('auth'))
conn_url = "%s/%s" % (conn_url.rstrip('/'), url.lstrip('/'))
message = ("Error communicating with %(url)s %(e)s" %
dict(url=conn_url, e=e))
raise exc.InvalidEndpoint(message=message)
except ksa_exc.ConnectFailure as e:
conn_url = self.get_endpoint(auth=kwargs.get('auth'))
conn_url = "%s/%s" % (conn_url.rstrip('/'), url.lstrip('/'))
message = ("Error finding address for %(url)s: %(e)s" %
dict(url=conn_url, e=e))
raise exc.CommunicationError(message=message)
return self._handle_response(resp)
def get_http_client(endpoint=None, session=None, **kwargs):
if session:
return SessionClient(session, **kwargs)
elif endpoint:
return HTTPClient(endpoint, **kwargs)
else:
raise AttributeError('Constructing a client must contain either an '
'endpoint or a session') | 0.566738 | 0.074164 |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""
FILE: sample_synonym_map_operations.py
DESCRIPTION:
This sample demonstrates how to get, create, update, or delete a Synonym Map.
USAGE:
python sample_synonym_map_operations.py
Set the environment variables with your own values before running the sample:
1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service
2) AZURE_SEARCH_API_KEY - your search API key
"""
import os
service_endpoint = os.getenv("AZURE_SEARCH_SERVICE_ENDPOINT")
key = os.getenv("AZURE_SEARCH_API_KEY")
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchServiceClient
client = SearchServiceClient(service_endpoint, AzureKeyCredential(key)).get_synonym_maps_client()
def create_synonym_map():
# [START create_synonym_map]
result = client.create_synonym_map("test-syn-map", [
"USA, United States, United States of America",
"Washington, Wash. => WA",
])
print("Create new Synonym Map 'test-syn-map succeeded")
# [END create_synonym_map]
def get_synonym_maps():
# [START get_synonym_maps]
result = client.get_synonym_maps()
names = [x["name"] for x in result]
print("Found {} Synonym Maps in the service: {}".format(len(result), ", ".join(names)))
# [END get_synonym_maps]
def get_synonym_map():
# [START get_synonym_map]
result = client.get_synonym_map("test-syn-map")
print("Retrived Synonym Map 'test-syn-map' with synonyms")
for syn in result["synonyms"]:
print(" {}".format(syn))
# [END get_synonym_map]
def delete_synonym_map():
# [START delete_synonym_map]
client.delete_synonym_map("test-syn-map")
print("Synonym Map 'test-syn-map' deleted")
# [END delete_synonym_map]
if __name__ == '__main__':
create_synonym_map()
get_synonym_maps()
get_synonym_map()
delete_synonym_map() | sdk/search/azure-search-documents/samples/sample_synonym_map_operations.py |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""
FILE: sample_synonym_map_operations.py
DESCRIPTION:
This sample demonstrates how to get, create, update, or delete a Synonym Map.
USAGE:
python sample_synonym_map_operations.py
Set the environment variables with your own values before running the sample:
1) AZURE_SEARCH_SERVICE_ENDPOINT - the endpoint of your Azure Cognitive Search service
2) AZURE_SEARCH_API_KEY - your search API key
"""
import os
service_endpoint = os.getenv("AZURE_SEARCH_SERVICE_ENDPOINT")
key = os.getenv("AZURE_SEARCH_API_KEY")
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchServiceClient
client = SearchServiceClient(service_endpoint, AzureKeyCredential(key)).get_synonym_maps_client()
def create_synonym_map():
# [START create_synonym_map]
result = client.create_synonym_map("test-syn-map", [
"USA, United States, United States of America",
"Washington, Wash. => WA",
])
print("Create new Synonym Map 'test-syn-map succeeded")
# [END create_synonym_map]
def get_synonym_maps():
# [START get_synonym_maps]
result = client.get_synonym_maps()
names = [x["name"] for x in result]
print("Found {} Synonym Maps in the service: {}".format(len(result), ", ".join(names)))
# [END get_synonym_maps]
def get_synonym_map():
# [START get_synonym_map]
result = client.get_synonym_map("test-syn-map")
print("Retrived Synonym Map 'test-syn-map' with synonyms")
for syn in result["synonyms"]:
print(" {}".format(syn))
# [END get_synonym_map]
def delete_synonym_map():
# [START delete_synonym_map]
client.delete_synonym_map("test-syn-map")
print("Synonym Map 'test-syn-map' deleted")
# [END delete_synonym_map]
if __name__ == '__main__':
create_synonym_map()
get_synonym_maps()
get_synonym_map()
delete_synonym_map() | 0.733356 | 0.318008 |
import math
from functools import reduce
from itertools import product
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import torch
from torch import Tensor
Array = np.ndarray
Ints = Union[int, List[int], Tuple[int, ...]]
from pytorch_toolbelt.utils import pytorch_toolbelt_deprecated
__all__ = [
"ImageSlicer",
"TileMerger",
"CudaTileMerger",
"compute_pyramid_patch_weight_loss",
"compute_pyramid_patch_weight_loss_2d",
]
def compute_pyramid_patch_weight_loss(*dims: int) -> Tuple[Array, Array, Array]:
"""
Compute a weight matrix that assigns bigger weight on pixels in center and
less weight to pixels on image boundary.
This weight matrix then used for merging individual tile predictions and helps dealing
with prediction artifacts on tile boundaries.
:param dims: tile dimensions (any number)
:return: tuple of arrays with given dimensionality
weight,
d_circle,
d_ladder
"""
dims = np.array(dims)
dims_center = dims * 0.5
dims_start = np.zeros_like(dims)
dims_end = dims.copy()
d_circle = [np.square(np.arange(d) - c + 0.5) for d, c in zip(dims, dims_center)]
d_circle = np.sqrt(reduce(lambda x, y: x[..., np.newaxis] + y, d_circle))
d_ladder_start = [np.square(np.arange(dim) - start + 0.5) + np.square(0.5) for dim, start in zip(dims, dims_start)]
d_ladder_end = [np.square(np.arange(dim) - end + 0.5) + np.square(0.5) for dim, end in zip(dims, dims_end)]
d_ladder = [np.sqrt(np.minimum(s, e)) for s, e in zip(d_ladder_start, d_ladder_end)]
d_ladder = reduce(lambda x, y: np.minimum(x[..., np.newaxis], y), d_ladder)
alpha = np.prod(dims) / np.sum(np.divide(d_ladder, np.add(d_circle, d_ladder)))
weight = alpha * np.divide(d_ladder, np.add(d_circle, d_ladder))
return weight, d_circle, d_ladder
def compute_pyramid_patch_weight_loss_2d(width: int, height: int) -> Tuple[Array, Array, Array]:
"""
Original for `compute_pyramid_patch_weight_loss` in a specific 2D case
Compute a weight matrix that assigns bigger weight on pixels in center and
less weight to pixels on image boundary.
This weight matrix then used for merging individual tile predictions and helps dealing
with prediction artifacts on tile boundaries.
:param width: Tile width
:param height: Tile height
:return: Since-channel image [Width x Height]
"""
xc = width * 0.5
yc = height * 0.5
xl = 0
xr = width
yb = 0
yt = height
Dc = np.zeros((width, height))
De = np.zeros((width, height))
Dcx = np.square(np.arange(width) - xc + 0.5)
Dcy = np.square(np.arange(height) - yc + 0.5)
Dc = np.sqrt(Dcx[np.newaxis].transpose() + Dcy)
De_l = np.square(np.arange(width) - xl + 0.5) + np.square(0.5)
De_r = np.square(np.arange(width) - xr + 0.5) + np.square(0.5)
De_b = np.square(0.5) + np.square(np.arange(height) - yb + 0.5)
De_t = np.square(0.5) + np.square(np.arange(height) - yt + 0.5)
De_x = np.sqrt(np.minimum(De_l, De_r))
De_y = np.sqrt(np.minimum(De_b, De_t))
De = np.minimum(De_x[np.newaxis].transpose(), De_y)
alpha = (width * height) / np.sum(np.divide(De, np.add(Dc, De)))
W = alpha * np.divide(De, np.add(Dc, De))
return W, Dc, De
def make_tuple(numbers: Ints, n_dims: Optional[int] = None) -> Tuple[int, ...]:
"""
Guarantees tuple of ints from tuple or scalar
"""
if isinstance(numbers, (tuple, list)):
numbers = tuple(map(int, numbers))
else:
assert n_dims is not None
numbers = (int(numbers),) * n_dims
return numbers
def assert_shape(shape_0: Tuple[int, ...], shape_1: Tuple[int, ...]) -> None:
"""
Assert shape equality for each dim
"""
for i, (s0, s1) in enumerate(zip(shape_0, shape_1)):
assert s0 == s1, f"shape_0 does not match shape_1 in dim {i} {s0} != {s1}"
class ImageSlicer:
"""
Helper class to slice image into tiles and merge them back
"""
def __init__(
self,
image_shape: Ints,
tile_size: Ints,
tile_step: Ints = 0,
image_margin: int = 0,
weight: str = "mean",
ignore_weight_dim: Optional[int] = None,
is_channels: bool = True,
crop_border: Ints = 0,
weight_dtype: type = np.float64,
):
"""
:param image_shape: Shape of the source image (scalar or tuple)
:param tile_size: Tile size (scalar or tuple)
:param tile_step: Step in pixels between tiles (scalar or tuple)
:param image_margin:
:param weight: Fusion algorithm. 'mean' - simple averaging, 'pyramid' - weighted by position
:param ignore_weight_dim: dimension to ignore when building weights (e.g. no overlap there)
:param is_channels: if image has channels (last dim by default)
"""
self.image_shape = image_shape
self.ignore_weight_dim = ignore_weight_dim
# Convert tile_size and tile_step to tuples of ints
n_dims = len(image_shape)
self.channels = None
if is_channels:
n_dims -= 1
self.channels = self.image_shape[-1]
self.tile_size = make_tuple(tile_size, n_dims=n_dims)
self.tile_step = make_tuple(tile_step, n_dims=n_dims)
self.crop_border = make_tuple(crop_border, n_dims=n_dims)
# Calculate weight for tile fusion (or assign provided)
self.weight_dtype = weight_dtype
weights = {"mean": self._mean, "pyramid": self._pyramid}
self.weight = weight if isinstance(weight, np.ndarray) else weights[weight]()
if sum(self.crop_border) != 0:
# make borders zero
mask = np.zeros_like(self.weight)
center = tuple(slice(cb, ts - cb) for cb, ts in zip(self.crop_border, self.tile_size))
mask[center] = 1
self.weight *= mask
# Check tile step and size correctness
for step, size in zip(self.tile_step, self.tile_size):
if step < 1 or step > size:
raise ValueError()
# Calculate overlap between tiles
overlap = [size - step for step, size in zip(self.tile_step, self.tile_size)]
for i, (cb, over) in enumerate(zip(self.crop_border, overlap)):
if over < cb:
raise ValueError(f"Overlap ({over}) < crop border ({cb}) in dim {i}")
# Calculate margins (arrays of `self.tile_size` shape)
if image_margin == 0:
# In case margin is not set, we compute it manually
nd = [
max(1, math.ceil((dim - over + cb * 2) / step))
for dim, over, step, cb in zip(self.image_shape, overlap, self.tile_step, self.crop_border)
]
extra = np.array(
[
step * n - (dim - over)
for n, dim, over, step, cb in zip(nd, self.image_shape, overlap, self.tile_step, self.crop_border)
]
)
self.margin_start = np.floor_divide(extra, 2)
self.margin_end = extra - self.margin_start
else:
# If margin is precalculated
for dim, over, step in zip(self.image_shape, overlap, self.tile_step):
if (dim - over + 2 * image_margin) % step != 0:
raise ValueError()
self.margin_start = np.zeros_like(self.tile_size).fill(image_margin)
self.margin_end = np.zeros_like(self.tile_size).fill(image_margin)
# Calculate crop coordinates
crops_product = []
for shape, margin_start, margin_end, size, step in zip(
self.image_shape, self.margin_start, self.margin_end, self.tile_size, self.tile_step
):
# For each dimension add top corner coordinate to the list
# No need to store tile size, since it is the same for every patch
crops_product_x = np.arange(0, shape + margin_start + margin_end - size + 1, step)
# Append a list of corner coordinates to other lists
crops_product.append(crops_product_x)
# Combine coordinates with a Cartesian product; each inner list consists of `n_dims` elements
self.crops = np.array(list(product(*crops_product)))
def split(self, image: Array, mode: str = "constant", **kwargs: Any):
"""
Split image into tiles
"""
assert_shape(image.shape, self.image_shape)
tiles = []
for i, crop in enumerate(self.crops):
tile, crop = self.crop_tile(image, i, random_crop=False, mode=mode, **kwargs)
assert_shape(tile.shape, self.tile_size)
tiles.append(tile)
return tiles
def project_crop_to_tile(
self,
crop: List[int],
) -> Tuple[Tuple[List[int], List[int]], Tuple[List[int], List[int]], List[int]]:
"""
Project crop coordinates in padded image `self.crops` to both the original image and the tile
:param crop: list of ints, corner coordinates of a crop
:return:
coordinates in original image ([ix0, iy0, ...], [ix1, iy1, ...])
coordinates in tile ([tx0, ty0, ...], [tx1, ty1, ...])
"""
# Get original coordinates with padding
c0 = [c - start for c, start in zip(crop, self.margin_start)] # may be negative
c1 = [c + ts for c, ts in zip(c0, self.tile_size)] # may overflow image size
# Restrict coordinated by image size (image coordinate = ic)
ic0 = [max(c, 0) for c in c0]
ic1 = [min(c, shape) for c, shape in zip(c1, self.image_shape)]
# Set shifts for the tile (tile coordinate = tc)
tc0 = [ic - c for ic, c in zip(ic0, c0)] # >= 0
tc1 = [ts + ic - c for ts, ic, c in zip(self.tile_size, ic1, c1)]
return (ic0, ic1), (tc0, tc1), crop
def crop_tile(
self,
image: Array,
crop_index: Optional[int] = None,
crop: Optional[List[int]] = None,
random_crop: bool = False,
mode: str = "constant",
**kwargs: Any,
) -> Tuple[Array, List[int]]:
"""
Memory efficient version of ImageSlicer.cut_patch with zero padding
:param image: image to cut a tile from
:param crop: list of ints, corner coordinates of a crop
:param crop_index: alternatively, crop index in self.crops
:param random_crop: if sample crop coordinates randomly
:param mode: padding mode for np.pad
{constant, edge, linear_ramp, maximum, mean, median, minimum, reflect, symmetric, wrap, empty}
:param kwargs: kwargs for np.pad
:returns:
tile, cropped array
crop, list of crop corner coordinates
"""
assert_shape(image.shape[:-1], self.image_shape[:-1])
if crop is None:
if random_crop:
crop = [
np.random.randint(0, max(1, shape - ts - 1)) for shape, ts in zip(self.image_shape, self.tile_size)
]
else:
crop = self.crops[crop_index]
# Get image slice (image coordinate = ic, tile coordinate = tc)
(ic0, ic1), (tc0, tc1), crop = self.project_crop_to_tile(crop)
image_slice = tuple(slice(c0, c1) for c0, c1 in zip(ic0, ic1))
# Assume channel last in padding
# [(before_0, after_0), (before_1, after_1), ...]
pad_width = [(c0, ts - c1) for ts, c0, c1 in zip(self.tile_size, tc0, tc1)] + [(0, 0)]
# Create tile by padding image slice to the tile size
tile = np.pad(image[image_slice], pad_width=pad_width, mode=mode, **kwargs)
assert_shape(tile.shape, self.tile_size)
return tile, crop
@property
def target_shape(self) -> Tuple[int, ...]:
"""
Target shape without the last (channel) dimension
"""
target_shape = tuple(
image_shape + margin_start + margin_end
for image_shape, margin_start, margin_end in zip(self.image_shape, self.margin_start, self.margin_end)
)
return target_shape
def merge(self, tiles: List[Array], dtype=np.float32) -> Array:
"""
Merge tiles to the original shape
"""
if len(tiles) != len(self.crops):
raise ValueError
# TODO add channel first option
channels = 1 if len(tiles[0].shape) == len(self.tile_size) else tiles[0].shape[-1]
target_shape = self.target_shape + (channels,) # self.target shape is without channel dim
image = np.zeros(target_shape, dtype=np.float64)
norm_mask = np.zeros(target_shape, dtype=self.weight_dtype)
w = np.stack([self.weight] * channels, axis=-1)
tile_slice = tuple(slice(cb, ts - cb) for ts, cb in zip(self.tile_size, self.crop_border))
for tile, crop in zip(tiles, self.crops):
image_slice = tuple(
slice(x + cb, x + ts - cb) for x, ts, cb in zip(crop, self.tile_size, self.crop_border)
)
image[image_slice] += tile[tile_slice] * w[tile_slice]
norm_mask[image_slice] += w[tile_slice]
# TODO is clip necessary with uint?
norm_mask = np.clip(norm_mask, a_min=0, a_max=None)
normalized = np.divide(image, norm_mask, where=(norm_mask != 0))
if dtype == np.uint8:
normalized = np.round(normalized)
normalized = normalized.astype(dtype)
crop = self.crop_to_original_size(normalized)
return crop
def crop_to_original_size(self, image: Array) -> Array:
"""
Crops an image from target shape to original shape
"""
assert_shape(image.shape, self.target_shape)
image_slice = tuple(
slice(start, -end if end != 0 else None) for start, end in zip(self.margin_start, self.margin_end)
)
crop = image[image_slice]
assert_shape(crop.shape[:-1], self.image_shape[:-1])
return crop
def _mean(self, tile_size: Optional[Ints] = None) -> Array:
"""
Compute patch weight loss with respect to tile size
"""
if tile_size is None:
tile_size = self.tile_size
return np.ones(tile_size, dtype=self.weight_dtype)
def _pyramid(self, tile_size: Optional[Ints] = None) -> Array:
"""
Compute pyramid patch weight loss with respect to tile size
"""
if tile_size is None:
tile_size = self.tile_size
if self.ignore_weight_dim is not None:
tile_size = tuple(x for i, x in enumerate(tile_size) if i != self.ignore_weight_dim)
w, _, _ = compute_pyramid_patch_weight_loss(*tile_size)
if self.ignore_weight_dim is not None:
w = np.stack([w] * self.image_shape[self.ignore_weight_dim], axis=self.ignore_weight_dim)
# quantize weight for memory efficiency
if self.weight_dtype == np.uint8:
n_steps = 126
# n_steps = min(
# 127 - 1, max(tile_size) // 2
# ) # TODO calculate not to exceed 255 in uint8 anyhow (even with step 1)
w = (w - np.min(w)) / np.max(w) * n_steps + 1
return w.astype(self.weight_dtype)
def __len__(self):
return len(self.crops)
class TileMerger:
"""
Helper class to merge final image on GPU. This generally faster than moving individual tiles to CPU.
"""
def __init__(
self,
image_shape: Tuple[int, ...],
channels: int,
weight: Array,
device="cpu",
default_value: float = 0,
crop_border: int = 0,
dtype: torch.dtype = torch.float32,
keys: Optional[List[str]] = None,
requires_grad: bool = False,
):
"""
:param image_shape: Shape of the source image
:param channels: Number of channels
:param weight: Weighting matrix
:param device: Device for memory allocation
:param default_value: Negative value to fill image by default
in case we predict only some tiles ond need zeros
for other areas in final prediction
:param crop_border: how many pixels to crop from the border before merging
(might help with severe edge effects)
:param dtype: data type of the output image
:param keys: list of keys to use for merging multiple images
"""
self.image_shape = image_shape
self.image_height = image_shape[0]
self.image_width = image_shape[1]
self.channels = channels
self.default_value = default_value
# TODO assert crop_border < margin
self.crop_border = crop_border
self.dtype = dtype
self.device = device
# Set up keys
self.keys = keys
self.default_key = "image"
if self.keys is None:
self.keys = [self.default_key]
# Make weight and norm_mask uint8 for memory efficiency
self.weight = torch.from_numpy(np.expand_dims(weight, axis=0)).to(device)
if isinstance(requires_grad, bool):
requires_grad = {k: requires_grad for k in self.keys}
self.image = {
k: torch.zeros((channels,) + self.image_shape, device=device, dtype=dtype, requires_grad=requires_grad[k]) + default_value
for k in self.keys
}
self.norm_mask = torch.zeros((1,) + self.image_shape, device=device, dtype=self.weight.dtype)
# Save accumulated coordinates for weighting
self.accumulated_coords = set()
def accumulate_single(self, tile: Tensor, coords: Array, key: str = None) -> None:
"""
Accumulates single element
:param tile: Predicted image of shape [C,H,W]
:param coords: Corresponding tile crops (top corner coordinates) w.r.t to original image
:param key: key to access merging image
"""
if key is None:
key = self.default_key
# Calculate slices
image_slice = (slice(None),) + tuple(
slice(x + self.crop_border, x + ts - self.crop_border) for x, ts in zip(coords, tile.shape[1:])
)
tile_slice = (slice(None),) + tuple(slice(self.crop_border, ts - self.crop_border) for ts in tile.shape[1:])
tile = tile.to(device=self.device)
# Replace default (large negative) value with zero to add predictions
if self.default_value < 0:
self.image[key][image_slice] = torch.where(
self.image[key][image_slice] == self.default_value,
torch.tensor(0.0, dtype=self.dtype).to(self.device),
self.image[key][image_slice],
)
self.image[key][image_slice] += tile[tile_slice] * self.weight[tile_slice]
coords = tuple(np.array(coords))
if coords not in self.accumulated_coords:
# todo check if this can cause any trouble in accumulation
self.norm_mask[image_slice] += self.weight[tile_slice]
self.accumulated_coords.add(coords)
def integrate_batch_dict(self, batch: Dict[str, Tensor], crop_coords: Array) -> None:
"""
Accumulates dict batch of tile predictions
:param batch: Predicted tiles of shape [B,C,H,W]
:param crop_coords: Corresponding tile crops w.r.t to original image
"""
if set(batch.keys()) != set(self.keys):
raise ValueError(f"Keys in batch {batch.keys()} must match keys in the merger {self.keys}")
for k, b in batch.items():
self.integrate_batch(b, crop_coords, k)
def integrate_batch(self, batch: Tensor, crop_coords: Array, key: str = None) -> None:
"""
Accumulates batch of tile predictions
:param batch: Predicted tiles of shape [B,C,H,W]
:param crop_coords: Corresponding tile crops w.r.t to original image
:param key: key to access merging image
"""
if len(batch) != len(crop_coords):
raise ValueError("Number of images in batch does not correspond to number of coordinates")
batch = batch.to(device=self.device)
for tile, coords in zip(batch, crop_coords):
self.accumulate_single(tile, coords, key)
def merge(self) -> Dict[str, Tensor]:
self.norm_mask = torch.where(
self.norm_mask == 0, torch.tensor(1.0).type(self.weight.dtype).to(self.device), self.norm_mask
)
# self.norm_mask[self.norm_mask == 0] = 1
return {k: v / self.norm_mask for k, v in self.image.items()}
def merge_(self) -> None:
"""
Inplace version of TileMerger.merge() using div_()
Substitute self.image with (self.image / self.norm_mask)
:return: None
"""
self.norm_mask = torch.where(
self.norm_mask == 0, torch.tensor(1.0).type(self.weight.dtype).to(self.device), self.norm_mask
)
# self.norm_mask[self.norm_mask == 0] = 1
for k in self.keys:
if self.image[k].requires_grad:
self.image[k] = self.image[k].div(self.norm_mask)
else:
self.image[k].div_(self.norm_mask)
def threshold_(self, threshold: float = 0.5) -> None:
"""
Inplace thresholding of TileMerger.image:
image = sigmoid(image) > threshold
:return: None
"""
for k in self.keys:
if self.image[k].requires_grad:
self.image[k] = self.image[k].sigmoid()
self.image[k] = self.image[k].gt(threshold)
else:
self.image[k].sigmoid_()
self.image[k].gt_(threshold)
self.image[k].type(torch.int8)
@pytorch_toolbelt_deprecated("This class is deprecated and will be removed in 0.5.0. Please use TileMerger instead.")
class CudaTileMerger(TileMerger):
def __init__(
self,
image_shape,
channels,
weight,
device="cuda",
default_value=-99,
crop_border=0,
dtype=torch.float32,
keys=None,
):
super().__init__(
image_shape,
channels,
weight,
device,
default_value=default_value,
crop_border=crop_border,
dtype=dtype,
keys=keys,
) | pytorch_toolbelt/inference/tiles.py | import math
from functools import reduce
from itertools import product
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import torch
from torch import Tensor
Array = np.ndarray
Ints = Union[int, List[int], Tuple[int, ...]]
from pytorch_toolbelt.utils import pytorch_toolbelt_deprecated
__all__ = [
"ImageSlicer",
"TileMerger",
"CudaTileMerger",
"compute_pyramid_patch_weight_loss",
"compute_pyramid_patch_weight_loss_2d",
]
def compute_pyramid_patch_weight_loss(*dims: int) -> Tuple[Array, Array, Array]:
"""
Compute a weight matrix that assigns bigger weight on pixels in center and
less weight to pixels on image boundary.
This weight matrix then used for merging individual tile predictions and helps dealing
with prediction artifacts on tile boundaries.
:param dims: tile dimensions (any number)
:return: tuple of arrays with given dimensionality
weight,
d_circle,
d_ladder
"""
dims = np.array(dims)
dims_center = dims * 0.5
dims_start = np.zeros_like(dims)
dims_end = dims.copy()
d_circle = [np.square(np.arange(d) - c + 0.5) for d, c in zip(dims, dims_center)]
d_circle = np.sqrt(reduce(lambda x, y: x[..., np.newaxis] + y, d_circle))
d_ladder_start = [np.square(np.arange(dim) - start + 0.5) + np.square(0.5) for dim, start in zip(dims, dims_start)]
d_ladder_end = [np.square(np.arange(dim) - end + 0.5) + np.square(0.5) for dim, end in zip(dims, dims_end)]
d_ladder = [np.sqrt(np.minimum(s, e)) for s, e in zip(d_ladder_start, d_ladder_end)]
d_ladder = reduce(lambda x, y: np.minimum(x[..., np.newaxis], y), d_ladder)
alpha = np.prod(dims) / np.sum(np.divide(d_ladder, np.add(d_circle, d_ladder)))
weight = alpha * np.divide(d_ladder, np.add(d_circle, d_ladder))
return weight, d_circle, d_ladder
def compute_pyramid_patch_weight_loss_2d(width: int, height: int) -> Tuple[Array, Array, Array]:
"""
Original for `compute_pyramid_patch_weight_loss` in a specific 2D case
Compute a weight matrix that assigns bigger weight on pixels in center and
less weight to pixels on image boundary.
This weight matrix then used for merging individual tile predictions and helps dealing
with prediction artifacts on tile boundaries.
:param width: Tile width
:param height: Tile height
:return: Since-channel image [Width x Height]
"""
xc = width * 0.5
yc = height * 0.5
xl = 0
xr = width
yb = 0
yt = height
Dc = np.zeros((width, height))
De = np.zeros((width, height))
Dcx = np.square(np.arange(width) - xc + 0.5)
Dcy = np.square(np.arange(height) - yc + 0.5)
Dc = np.sqrt(Dcx[np.newaxis].transpose() + Dcy)
De_l = np.square(np.arange(width) - xl + 0.5) + np.square(0.5)
De_r = np.square(np.arange(width) - xr + 0.5) + np.square(0.5)
De_b = np.square(0.5) + np.square(np.arange(height) - yb + 0.5)
De_t = np.square(0.5) + np.square(np.arange(height) - yt + 0.5)
De_x = np.sqrt(np.minimum(De_l, De_r))
De_y = np.sqrt(np.minimum(De_b, De_t))
De = np.minimum(De_x[np.newaxis].transpose(), De_y)
alpha = (width * height) / np.sum(np.divide(De, np.add(Dc, De)))
W = alpha * np.divide(De, np.add(Dc, De))
return W, Dc, De
def make_tuple(numbers: Ints, n_dims: Optional[int] = None) -> Tuple[int, ...]:
"""
Guarantees tuple of ints from tuple or scalar
"""
if isinstance(numbers, (tuple, list)):
numbers = tuple(map(int, numbers))
else:
assert n_dims is not None
numbers = (int(numbers),) * n_dims
return numbers
def assert_shape(shape_0: Tuple[int, ...], shape_1: Tuple[int, ...]) -> None:
"""
Assert shape equality for each dim
"""
for i, (s0, s1) in enumerate(zip(shape_0, shape_1)):
assert s0 == s1, f"shape_0 does not match shape_1 in dim {i} {s0} != {s1}"
class ImageSlicer:
"""
Helper class to slice image into tiles and merge them back
"""
def __init__(
self,
image_shape: Ints,
tile_size: Ints,
tile_step: Ints = 0,
image_margin: int = 0,
weight: str = "mean",
ignore_weight_dim: Optional[int] = None,
is_channels: bool = True,
crop_border: Ints = 0,
weight_dtype: type = np.float64,
):
"""
:param image_shape: Shape of the source image (scalar or tuple)
:param tile_size: Tile size (scalar or tuple)
:param tile_step: Step in pixels between tiles (scalar or tuple)
:param image_margin:
:param weight: Fusion algorithm. 'mean' - simple averaging, 'pyramid' - weighted by position
:param ignore_weight_dim: dimension to ignore when building weights (e.g. no overlap there)
:param is_channels: if image has channels (last dim by default)
"""
self.image_shape = image_shape
self.ignore_weight_dim = ignore_weight_dim
# Convert tile_size and tile_step to tuples of ints
n_dims = len(image_shape)
self.channels = None
if is_channels:
n_dims -= 1
self.channels = self.image_shape[-1]
self.tile_size = make_tuple(tile_size, n_dims=n_dims)
self.tile_step = make_tuple(tile_step, n_dims=n_dims)
self.crop_border = make_tuple(crop_border, n_dims=n_dims)
# Calculate weight for tile fusion (or assign provided)
self.weight_dtype = weight_dtype
weights = {"mean": self._mean, "pyramid": self._pyramid}
self.weight = weight if isinstance(weight, np.ndarray) else weights[weight]()
if sum(self.crop_border) != 0:
# make borders zero
mask = np.zeros_like(self.weight)
center = tuple(slice(cb, ts - cb) for cb, ts in zip(self.crop_border, self.tile_size))
mask[center] = 1
self.weight *= mask
# Check tile step and size correctness
for step, size in zip(self.tile_step, self.tile_size):
if step < 1 or step > size:
raise ValueError()
# Calculate overlap between tiles
overlap = [size - step for step, size in zip(self.tile_step, self.tile_size)]
for i, (cb, over) in enumerate(zip(self.crop_border, overlap)):
if over < cb:
raise ValueError(f"Overlap ({over}) < crop border ({cb}) in dim {i}")
# Calculate margins (arrays of `self.tile_size` shape)
if image_margin == 0:
# In case margin is not set, we compute it manually
nd = [
max(1, math.ceil((dim - over + cb * 2) / step))
for dim, over, step, cb in zip(self.image_shape, overlap, self.tile_step, self.crop_border)
]
extra = np.array(
[
step * n - (dim - over)
for n, dim, over, step, cb in zip(nd, self.image_shape, overlap, self.tile_step, self.crop_border)
]
)
self.margin_start = np.floor_divide(extra, 2)
self.margin_end = extra - self.margin_start
else:
# If margin is precalculated
for dim, over, step in zip(self.image_shape, overlap, self.tile_step):
if (dim - over + 2 * image_margin) % step != 0:
raise ValueError()
self.margin_start = np.zeros_like(self.tile_size).fill(image_margin)
self.margin_end = np.zeros_like(self.tile_size).fill(image_margin)
# Calculate crop coordinates
crops_product = []
for shape, margin_start, margin_end, size, step in zip(
self.image_shape, self.margin_start, self.margin_end, self.tile_size, self.tile_step
):
# For each dimension add top corner coordinate to the list
# No need to store tile size, since it is the same for every patch
crops_product_x = np.arange(0, shape + margin_start + margin_end - size + 1, step)
# Append a list of corner coordinates to other lists
crops_product.append(crops_product_x)
# Combine coordinates with a Cartesian product; each inner list consists of `n_dims` elements
self.crops = np.array(list(product(*crops_product)))
def split(self, image: Array, mode: str = "constant", **kwargs: Any):
"""
Split image into tiles
"""
assert_shape(image.shape, self.image_shape)
tiles = []
for i, crop in enumerate(self.crops):
tile, crop = self.crop_tile(image, i, random_crop=False, mode=mode, **kwargs)
assert_shape(tile.shape, self.tile_size)
tiles.append(tile)
return tiles
def project_crop_to_tile(
self,
crop: List[int],
) -> Tuple[Tuple[List[int], List[int]], Tuple[List[int], List[int]], List[int]]:
"""
Project crop coordinates in padded image `self.crops` to both the original image and the tile
:param crop: list of ints, corner coordinates of a crop
:return:
coordinates in original image ([ix0, iy0, ...], [ix1, iy1, ...])
coordinates in tile ([tx0, ty0, ...], [tx1, ty1, ...])
"""
# Get original coordinates with padding
c0 = [c - start for c, start in zip(crop, self.margin_start)] # may be negative
c1 = [c + ts for c, ts in zip(c0, self.tile_size)] # may overflow image size
# Restrict coordinated by image size (image coordinate = ic)
ic0 = [max(c, 0) for c in c0]
ic1 = [min(c, shape) for c, shape in zip(c1, self.image_shape)]
# Set shifts for the tile (tile coordinate = tc)
tc0 = [ic - c for ic, c in zip(ic0, c0)] # >= 0
tc1 = [ts + ic - c for ts, ic, c in zip(self.tile_size, ic1, c1)]
return (ic0, ic1), (tc0, tc1), crop
def crop_tile(
self,
image: Array,
crop_index: Optional[int] = None,
crop: Optional[List[int]] = None,
random_crop: bool = False,
mode: str = "constant",
**kwargs: Any,
) -> Tuple[Array, List[int]]:
"""
Memory efficient version of ImageSlicer.cut_patch with zero padding
:param image: image to cut a tile from
:param crop: list of ints, corner coordinates of a crop
:param crop_index: alternatively, crop index in self.crops
:param random_crop: if sample crop coordinates randomly
:param mode: padding mode for np.pad
{constant, edge, linear_ramp, maximum, mean, median, minimum, reflect, symmetric, wrap, empty}
:param kwargs: kwargs for np.pad
:returns:
tile, cropped array
crop, list of crop corner coordinates
"""
assert_shape(image.shape[:-1], self.image_shape[:-1])
if crop is None:
if random_crop:
crop = [
np.random.randint(0, max(1, shape - ts - 1)) for shape, ts in zip(self.image_shape, self.tile_size)
]
else:
crop = self.crops[crop_index]
# Get image slice (image coordinate = ic, tile coordinate = tc)
(ic0, ic1), (tc0, tc1), crop = self.project_crop_to_tile(crop)
image_slice = tuple(slice(c0, c1) for c0, c1 in zip(ic0, ic1))
# Assume channel last in padding
# [(before_0, after_0), (before_1, after_1), ...]
pad_width = [(c0, ts - c1) for ts, c0, c1 in zip(self.tile_size, tc0, tc1)] + [(0, 0)]
# Create tile by padding image slice to the tile size
tile = np.pad(image[image_slice], pad_width=pad_width, mode=mode, **kwargs)
assert_shape(tile.shape, self.tile_size)
return tile, crop
@property
def target_shape(self) -> Tuple[int, ...]:
"""
Target shape without the last (channel) dimension
"""
target_shape = tuple(
image_shape + margin_start + margin_end
for image_shape, margin_start, margin_end in zip(self.image_shape, self.margin_start, self.margin_end)
)
return target_shape
def merge(self, tiles: List[Array], dtype=np.float32) -> Array:
"""
Merge tiles to the original shape
"""
if len(tiles) != len(self.crops):
raise ValueError
# TODO add channel first option
channels = 1 if len(tiles[0].shape) == len(self.tile_size) else tiles[0].shape[-1]
target_shape = self.target_shape + (channels,) # self.target shape is without channel dim
image = np.zeros(target_shape, dtype=np.float64)
norm_mask = np.zeros(target_shape, dtype=self.weight_dtype)
w = np.stack([self.weight] * channels, axis=-1)
tile_slice = tuple(slice(cb, ts - cb) for ts, cb in zip(self.tile_size, self.crop_border))
for tile, crop in zip(tiles, self.crops):
image_slice = tuple(
slice(x + cb, x + ts - cb) for x, ts, cb in zip(crop, self.tile_size, self.crop_border)
)
image[image_slice] += tile[tile_slice] * w[tile_slice]
norm_mask[image_slice] += w[tile_slice]
# TODO is clip necessary with uint?
norm_mask = np.clip(norm_mask, a_min=0, a_max=None)
normalized = np.divide(image, norm_mask, where=(norm_mask != 0))
if dtype == np.uint8:
normalized = np.round(normalized)
normalized = normalized.astype(dtype)
crop = self.crop_to_original_size(normalized)
return crop
def crop_to_original_size(self, image: Array) -> Array:
"""
Crops an image from target shape to original shape
"""
assert_shape(image.shape, self.target_shape)
image_slice = tuple(
slice(start, -end if end != 0 else None) for start, end in zip(self.margin_start, self.margin_end)
)
crop = image[image_slice]
assert_shape(crop.shape[:-1], self.image_shape[:-1])
return crop
def _mean(self, tile_size: Optional[Ints] = None) -> Array:
"""
Compute patch weight loss with respect to tile size
"""
if tile_size is None:
tile_size = self.tile_size
return np.ones(tile_size, dtype=self.weight_dtype)
def _pyramid(self, tile_size: Optional[Ints] = None) -> Array:
"""
Compute pyramid patch weight loss with respect to tile size
"""
if tile_size is None:
tile_size = self.tile_size
if self.ignore_weight_dim is not None:
tile_size = tuple(x for i, x in enumerate(tile_size) if i != self.ignore_weight_dim)
w, _, _ = compute_pyramid_patch_weight_loss(*tile_size)
if self.ignore_weight_dim is not None:
w = np.stack([w] * self.image_shape[self.ignore_weight_dim], axis=self.ignore_weight_dim)
# quantize weight for memory efficiency
if self.weight_dtype == np.uint8:
n_steps = 126
# n_steps = min(
# 127 - 1, max(tile_size) // 2
# ) # TODO calculate not to exceed 255 in uint8 anyhow (even with step 1)
w = (w - np.min(w)) / np.max(w) * n_steps + 1
return w.astype(self.weight_dtype)
def __len__(self):
return len(self.crops)
class TileMerger:
"""
Helper class to merge final image on GPU. This generally faster than moving individual tiles to CPU.
"""
def __init__(
self,
image_shape: Tuple[int, ...],
channels: int,
weight: Array,
device="cpu",
default_value: float = 0,
crop_border: int = 0,
dtype: torch.dtype = torch.float32,
keys: Optional[List[str]] = None,
requires_grad: bool = False,
):
"""
:param image_shape: Shape of the source image
:param channels: Number of channels
:param weight: Weighting matrix
:param device: Device for memory allocation
:param default_value: Negative value to fill image by default
in case we predict only some tiles ond need zeros
for other areas in final prediction
:param crop_border: how many pixels to crop from the border before merging
(might help with severe edge effects)
:param dtype: data type of the output image
:param keys: list of keys to use for merging multiple images
"""
self.image_shape = image_shape
self.image_height = image_shape[0]
self.image_width = image_shape[1]
self.channels = channels
self.default_value = default_value
# TODO assert crop_border < margin
self.crop_border = crop_border
self.dtype = dtype
self.device = device
# Set up keys
self.keys = keys
self.default_key = "image"
if self.keys is None:
self.keys = [self.default_key]
# Make weight and norm_mask uint8 for memory efficiency
self.weight = torch.from_numpy(np.expand_dims(weight, axis=0)).to(device)
if isinstance(requires_grad, bool):
requires_grad = {k: requires_grad for k in self.keys}
self.image = {
k: torch.zeros((channels,) + self.image_shape, device=device, dtype=dtype, requires_grad=requires_grad[k]) + default_value
for k in self.keys
}
self.norm_mask = torch.zeros((1,) + self.image_shape, device=device, dtype=self.weight.dtype)
# Save accumulated coordinates for weighting
self.accumulated_coords = set()
def accumulate_single(self, tile: Tensor, coords: Array, key: str = None) -> None:
"""
Accumulates single element
:param tile: Predicted image of shape [C,H,W]
:param coords: Corresponding tile crops (top corner coordinates) w.r.t to original image
:param key: key to access merging image
"""
if key is None:
key = self.default_key
# Calculate slices
image_slice = (slice(None),) + tuple(
slice(x + self.crop_border, x + ts - self.crop_border) for x, ts in zip(coords, tile.shape[1:])
)
tile_slice = (slice(None),) + tuple(slice(self.crop_border, ts - self.crop_border) for ts in tile.shape[1:])
tile = tile.to(device=self.device)
# Replace default (large negative) value with zero to add predictions
if self.default_value < 0:
self.image[key][image_slice] = torch.where(
self.image[key][image_slice] == self.default_value,
torch.tensor(0.0, dtype=self.dtype).to(self.device),
self.image[key][image_slice],
)
self.image[key][image_slice] += tile[tile_slice] * self.weight[tile_slice]
coords = tuple(np.array(coords))
if coords not in self.accumulated_coords:
# todo check if this can cause any trouble in accumulation
self.norm_mask[image_slice] += self.weight[tile_slice]
self.accumulated_coords.add(coords)
def integrate_batch_dict(self, batch: Dict[str, Tensor], crop_coords: Array) -> None:
"""
Accumulates dict batch of tile predictions
:param batch: Predicted tiles of shape [B,C,H,W]
:param crop_coords: Corresponding tile crops w.r.t to original image
"""
if set(batch.keys()) != set(self.keys):
raise ValueError(f"Keys in batch {batch.keys()} must match keys in the merger {self.keys}")
for k, b in batch.items():
self.integrate_batch(b, crop_coords, k)
def integrate_batch(self, batch: Tensor, crop_coords: Array, key: str = None) -> None:
"""
Accumulates batch of tile predictions
:param batch: Predicted tiles of shape [B,C,H,W]
:param crop_coords: Corresponding tile crops w.r.t to original image
:param key: key to access merging image
"""
if len(batch) != len(crop_coords):
raise ValueError("Number of images in batch does not correspond to number of coordinates")
batch = batch.to(device=self.device)
for tile, coords in zip(batch, crop_coords):
self.accumulate_single(tile, coords, key)
def merge(self) -> Dict[str, Tensor]:
self.norm_mask = torch.where(
self.norm_mask == 0, torch.tensor(1.0).type(self.weight.dtype).to(self.device), self.norm_mask
)
# self.norm_mask[self.norm_mask == 0] = 1
return {k: v / self.norm_mask for k, v in self.image.items()}
def merge_(self) -> None:
"""
Inplace version of TileMerger.merge() using div_()
Substitute self.image with (self.image / self.norm_mask)
:return: None
"""
self.norm_mask = torch.where(
self.norm_mask == 0, torch.tensor(1.0).type(self.weight.dtype).to(self.device), self.norm_mask
)
# self.norm_mask[self.norm_mask == 0] = 1
for k in self.keys:
if self.image[k].requires_grad:
self.image[k] = self.image[k].div(self.norm_mask)
else:
self.image[k].div_(self.norm_mask)
def threshold_(self, threshold: float = 0.5) -> None:
"""
Inplace thresholding of TileMerger.image:
image = sigmoid(image) > threshold
:return: None
"""
for k in self.keys:
if self.image[k].requires_grad:
self.image[k] = self.image[k].sigmoid()
self.image[k] = self.image[k].gt(threshold)
else:
self.image[k].sigmoid_()
self.image[k].gt_(threshold)
self.image[k].type(torch.int8)
@pytorch_toolbelt_deprecated("This class is deprecated and will be removed in 0.5.0. Please use TileMerger instead.")
class CudaTileMerger(TileMerger):
def __init__(
self,
image_shape,
channels,
weight,
device="cuda",
default_value=-99,
crop_border=0,
dtype=torch.float32,
keys=None,
):
super().__init__(
image_shape,
channels,
weight,
device,
default_value=default_value,
crop_border=crop_border,
dtype=dtype,
keys=keys,
) | 0.930789 | 0.693428 |
from torchvision import datasets, transforms
from PIL import Image
import numpy as np
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
from torch.utils.data.dataloader import default_collate
import torchvision
import matplotlib.pyplot as plt
from torchvision import transforms as T
from imgaug import augmenters as iaa
import pandas as pd
import pathlib
from data import *
class_names = [
"Nucleoplasm",
"Nuclear membrane",
"Nucleoli",
"Nucleoli fibrillar center" ,
"Nuclear speckles",
"Nuclear bodies",
"Endoplasmic reticulum",
"Golgi apparatus",
"Peroxisomes",
"Endosomes",
"Lysosomes",
"Intermediate filaments",
"Actin filaments",
"Focal adhesion sites",
"Microtubules",
"Microtubule ends",
"Cytokinetic bridge",
"Mitotic spindle",
"Microtubule organizing center",
"Centrosome",
"Lipid droplets",
"Plasma membrane",
"Cell junctions",
"Mitochondria",
"Aggresome",
"Cytosol",
"Cytoplasmic bodies",
"Rods & rings"
]
class BaseDataLoader(DataLoader):
"""
Base class for all data loaders
"""
def __init__(self, dataset, batch_size, shuffle, validation_split, num_workers, collate_fn=default_collate):
self.validation_split = validation_split
self.shuffle = shuffle
self.batch_idx = 0
self.n_samples = len(dataset)
self.sampler, self.valid_sampler = self._split_sampler(self.validation_split)
self.init_kwargs = {
'dataset': dataset,
'batch_size': batch_size,
'shuffle': self.shuffle,
'collate_fn': collate_fn,
'num_workers': num_workers
}
super(BaseDataLoader, self).__init__(sampler=self.sampler, **self.init_kwargs)
def _split_sampler(self, split):
if split == 0.0:
return None, None
idx_full = np.arange(self.n_samples)
np.random.seed(0)
np.random.shuffle(idx_full)
len_valid = int(self.n_samples * split)
valid_idx = idx_full[0:len_valid]
train_idx = np.delete(idx_full, np.arange(0, len_valid))
train_sampler = SubsetRandomSampler(train_idx)
valid_sampler = SubsetRandomSampler(valid_idx)
# turn off shuffle option which is mutually exclusive with sampler
self.shuffle = False
self.n_samples = len(train_idx)
return train_sampler, valid_sampler
def split_validation(self):
if self.valid_sampler is None:
return None
else:
return DataLoader(sampler=self.valid_sampler, **self.init_kwargs)
class ProteinDataLoader(BaseDataLoader):
def __init__(self, data_dir, csv_path, batch_size, shuffle, validation_split, num_workers, num_classes, img_size, training=True):
self.images_df = pd.read_csv(csv_path)
self.num_classes = num_classes
self.dataset = ProteinDataset(self.images_df, data_dir, num_classes, img_size, not training, training)
self.n_samples = len(self.dataset)
super(ProteinDataLoader, self).__init__(self.dataset, batch_size, shuffle, validation_split, num_workers)
def _split_sampler(self, split):
if split == 0.0:
return None, None
validation_split = []
for idx, (value, count) in enumerate(self.images_df['Target'].value_counts().to_dict().items()):
for _ in range(max(round(split * count), 1)):
validation_split.append(value)
validation_split_idx = []
for idx, value in enumerate(self.images_df['Target']):
try:
validation_split.remove(value)
validation_split_idx.append(idx)
except:
pass
idx_full = np.arange(self.n_samples)
valid_idx = np.array(validation_split_idx)
train_idx = np.delete(idx_full, valid_idx)
train_sampler = SubsetRandomSampler(train_idx)
valid_sampler = SubsetRandomSampler(valid_idx)
# turn off shuffle option which is mutually exclusive with sampler
self.shuffle = False
self.n_samples = len(train_idx)
return train_sampler, valid_sampler
class ProteinDataset(Dataset):
def __init__(self, images_df, base_path, num_classes, img_size, augument=True, training=True):
base_path = pathlib.Path(base_path)
self.img_size = img_size
self.num_classes = num_classes
self.images_df = images_df.copy()
self.augument = augument
self.images_df.Id = self.images_df.Id.apply(lambda x: base_path / x)
self.training = training
def __len__(self):
return len(self.images_df)
def __getitem__(self, index):
X = self.read_images(index)
if self.training:
labels = self.read_labels(index)
y = np.eye(self.num_classes, dtype=np.float)[labels].sum(axis=0)
else:
y = str(self.images_df.iloc[index].Id.absolute())
if self.augument:
X = self.augumentor(X)
X = T.Compose([T.ToPILImage(), T.Resize(299,299),T.ToTensor()])(X)
return X.float(), y
def read_labels(self, index):
return np.array(list(map(int, self.images_df.iloc[index].Target.split(' '))))
def read_images(self, index):
row = self.images_df.iloc[index]
filename = str(row.Id.absolute())
images = np.zeros(shape=(self.img_size, self.img_size, 4))
r = np.array(data_transforms(Image.open(filename + "_red.png")))
g = np.array(data_transforms(Image.open(filename + "_green.png")))
b = np.array(data_transforms(Image.open(filename + "_blue.png")))
y = np.array(data_transforms(Image.open(filename + "_yellow.png")))
images[:, :, 0] = r.astype(np.uint8)
images[:, :, 1] = g.astype(np.uint8)
images[:, :, 2] = b.astype(np.uint8)
images[:, :, 3] = y.astype(np.uint8)
images = images.astype(np.uint8)
return images
def augumentor(self, image):
augment_img = iaa.Sequential([
iaa.OneOf([
iaa.Affine(rotate=90),
iaa.Affine(rotate=180),
iaa.Affine(rotate=270),
iaa.Affine(shear=(-16, 16)),
iaa.Fliplr(0.5),
iaa.Flipud(0.5),
])], random_order=True)
image_aug = augment_img.augment_image(image)
return image_aug
if __name__ == '__main__':
dictio = {'data_dir': "./human-protein-atlas-image-classification/train",
'csv_path': "./human-protein-atlas-image-classification/train.csv",
'img_size': 299,
'batch_size': 1,
'shuffle': True,
'validation_split': 0.15,
'num_workers': 0,
'num_classes': 28}
data_loader = ProteinDataLoader(**dictio)
from data import *
#data_loader = data_transforms(data_loader)
def display_image(image, ax):
[a.axis('off') for a in ax]
r, g, b, y = image
ax[0].imshow(r,cmap='Reds')
ax[0].set_title('Microtubules')
ax[1].imshow(g,cmap='Greens')
ax[1].set_title('Protein of Interest')
ax[2].imshow(b,cmap='Blues')
ax[2].set_title('Nucleus')
ax[3].imshow(y,cmap='Oranges')
ax[3].set_title('Endoplasmic Reticulum')
return ax
from PIL import Image
# Get a batch of training data
# inputs contains 4 images because batch_size=4 for the dataloaders
inputs, classes = next(iter(data_loader))
print(inputs.shape)
# Make a grid from batch
out = torchvision.utils.make_grid(inputs)
fig, ax = plt.subplots(figsize=(15,5),nrows=1, ncols=4)
display_image(out, ax);
plt.show() | dataloader2.py | from torchvision import datasets, transforms
from PIL import Image
import numpy as np
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
from torch.utils.data.dataloader import default_collate
import torchvision
import matplotlib.pyplot as plt
from torchvision import transforms as T
from imgaug import augmenters as iaa
import pandas as pd
import pathlib
from data import *
class_names = [
"Nucleoplasm",
"Nuclear membrane",
"Nucleoli",
"Nucleoli fibrillar center" ,
"Nuclear speckles",
"Nuclear bodies",
"Endoplasmic reticulum",
"Golgi apparatus",
"Peroxisomes",
"Endosomes",
"Lysosomes",
"Intermediate filaments",
"Actin filaments",
"Focal adhesion sites",
"Microtubules",
"Microtubule ends",
"Cytokinetic bridge",
"Mitotic spindle",
"Microtubule organizing center",
"Centrosome",
"Lipid droplets",
"Plasma membrane",
"Cell junctions",
"Mitochondria",
"Aggresome",
"Cytosol",
"Cytoplasmic bodies",
"Rods & rings"
]
class BaseDataLoader(DataLoader):
"""
Base class for all data loaders
"""
def __init__(self, dataset, batch_size, shuffle, validation_split, num_workers, collate_fn=default_collate):
self.validation_split = validation_split
self.shuffle = shuffle
self.batch_idx = 0
self.n_samples = len(dataset)
self.sampler, self.valid_sampler = self._split_sampler(self.validation_split)
self.init_kwargs = {
'dataset': dataset,
'batch_size': batch_size,
'shuffle': self.shuffle,
'collate_fn': collate_fn,
'num_workers': num_workers
}
super(BaseDataLoader, self).__init__(sampler=self.sampler, **self.init_kwargs)
def _split_sampler(self, split):
if split == 0.0:
return None, None
idx_full = np.arange(self.n_samples)
np.random.seed(0)
np.random.shuffle(idx_full)
len_valid = int(self.n_samples * split)
valid_idx = idx_full[0:len_valid]
train_idx = np.delete(idx_full, np.arange(0, len_valid))
train_sampler = SubsetRandomSampler(train_idx)
valid_sampler = SubsetRandomSampler(valid_idx)
# turn off shuffle option which is mutually exclusive with sampler
self.shuffle = False
self.n_samples = len(train_idx)
return train_sampler, valid_sampler
def split_validation(self):
if self.valid_sampler is None:
return None
else:
return DataLoader(sampler=self.valid_sampler, **self.init_kwargs)
class ProteinDataLoader(BaseDataLoader):
def __init__(self, data_dir, csv_path, batch_size, shuffle, validation_split, num_workers, num_classes, img_size, training=True):
self.images_df = pd.read_csv(csv_path)
self.num_classes = num_classes
self.dataset = ProteinDataset(self.images_df, data_dir, num_classes, img_size, not training, training)
self.n_samples = len(self.dataset)
super(ProteinDataLoader, self).__init__(self.dataset, batch_size, shuffle, validation_split, num_workers)
def _split_sampler(self, split):
if split == 0.0:
return None, None
validation_split = []
for idx, (value, count) in enumerate(self.images_df['Target'].value_counts().to_dict().items()):
for _ in range(max(round(split * count), 1)):
validation_split.append(value)
validation_split_idx = []
for idx, value in enumerate(self.images_df['Target']):
try:
validation_split.remove(value)
validation_split_idx.append(idx)
except:
pass
idx_full = np.arange(self.n_samples)
valid_idx = np.array(validation_split_idx)
train_idx = np.delete(idx_full, valid_idx)
train_sampler = SubsetRandomSampler(train_idx)
valid_sampler = SubsetRandomSampler(valid_idx)
# turn off shuffle option which is mutually exclusive with sampler
self.shuffle = False
self.n_samples = len(train_idx)
return train_sampler, valid_sampler
class ProteinDataset(Dataset):
def __init__(self, images_df, base_path, num_classes, img_size, augument=True, training=True):
base_path = pathlib.Path(base_path)
self.img_size = img_size
self.num_classes = num_classes
self.images_df = images_df.copy()
self.augument = augument
self.images_df.Id = self.images_df.Id.apply(lambda x: base_path / x)
self.training = training
def __len__(self):
return len(self.images_df)
def __getitem__(self, index):
X = self.read_images(index)
if self.training:
labels = self.read_labels(index)
y = np.eye(self.num_classes, dtype=np.float)[labels].sum(axis=0)
else:
y = str(self.images_df.iloc[index].Id.absolute())
if self.augument:
X = self.augumentor(X)
X = T.Compose([T.ToPILImage(), T.Resize(299,299),T.ToTensor()])(X)
return X.float(), y
def read_labels(self, index):
return np.array(list(map(int, self.images_df.iloc[index].Target.split(' '))))
def read_images(self, index):
row = self.images_df.iloc[index]
filename = str(row.Id.absolute())
images = np.zeros(shape=(self.img_size, self.img_size, 4))
r = np.array(data_transforms(Image.open(filename + "_red.png")))
g = np.array(data_transforms(Image.open(filename + "_green.png")))
b = np.array(data_transforms(Image.open(filename + "_blue.png")))
y = np.array(data_transforms(Image.open(filename + "_yellow.png")))
images[:, :, 0] = r.astype(np.uint8)
images[:, :, 1] = g.astype(np.uint8)
images[:, :, 2] = b.astype(np.uint8)
images[:, :, 3] = y.astype(np.uint8)
images = images.astype(np.uint8)
return images
def augumentor(self, image):
augment_img = iaa.Sequential([
iaa.OneOf([
iaa.Affine(rotate=90),
iaa.Affine(rotate=180),
iaa.Affine(rotate=270),
iaa.Affine(shear=(-16, 16)),
iaa.Fliplr(0.5),
iaa.Flipud(0.5),
])], random_order=True)
image_aug = augment_img.augment_image(image)
return image_aug
if __name__ == '__main__':
dictio = {'data_dir': "./human-protein-atlas-image-classification/train",
'csv_path': "./human-protein-atlas-image-classification/train.csv",
'img_size': 299,
'batch_size': 1,
'shuffle': True,
'validation_split': 0.15,
'num_workers': 0,
'num_classes': 28}
data_loader = ProteinDataLoader(**dictio)
from data import *
#data_loader = data_transforms(data_loader)
def display_image(image, ax):
[a.axis('off') for a in ax]
r, g, b, y = image
ax[0].imshow(r,cmap='Reds')
ax[0].set_title('Microtubules')
ax[1].imshow(g,cmap='Greens')
ax[1].set_title('Protein of Interest')
ax[2].imshow(b,cmap='Blues')
ax[2].set_title('Nucleus')
ax[3].imshow(y,cmap='Oranges')
ax[3].set_title('Endoplasmic Reticulum')
return ax
from PIL import Image
# Get a batch of training data
# inputs contains 4 images because batch_size=4 for the dataloaders
inputs, classes = next(iter(data_loader))
print(inputs.shape)
# Make a grid from batch
out = torchvision.utils.make_grid(inputs)
fig, ax = plt.subplots(figsize=(15,5),nrows=1, ncols=4)
display_image(out, ax);
plt.show() | 0.760917 | 0.585931 |
import sys
import math
# CONSTANTS
g = 3.711 # Gravity
max_angle = math.degrees(math.acos(g / 4)) - 1 # Maximum angle for constant vertical velocity at thrust 4
# PARAMETERS
min_h_speed = 10 # Minimum acceptable horizontal speed
min_v_distance = 750
# FIRST INPUTS
# The number of points used to draw the surface of Mars.
surface_n = int(input())
surface = []
for i in range(surface_n):
# land_x: X coordinate of a surface point. (0 to 6999)
# land_y: Y coordinate of a surface point. By linking all the points together in a sequential fashion, you form the surface of Mars.
surface += [[int(j) for j in input().split()]]
# HELPER FUNCTIONS
def find_flat(surface):
for index in range(len(surface) - 1):
if surface[index][1] == surface[index + 1][1]:
return [surface[index][0], surface[index + 1][0], surface[index][1]]
def dist_to_flat(x, flat):
start, end = flat[0], flat[1]
if x < start:
return start - x
elif x > end:
return end - x
else:
return 0
# Find the flat surface
flat = find_flat(surface)
# Game Loop
while True:
# h_speed: the horizontal speed (in m/s), can be negative.
# v_speed: the vertical speed (in m/s), can be negative.
# fuel: the quantity of remaining fuel in liters.
# rotate: the rotation angle in degrees (-90 to 90).
# power: the thrust power (0 to 4).
x, y, h_speed, v_speed, fuel, rotate, power = [int(i) for i in input().split()]
dist = dist_to_flat(x, flat)
direction = -1 if dist < 0 else 1
# CONTOL SYSTEM
new_rotate = 0
new_power = 4
allowed_angle = 45 # Allowed Angle to Turn
# DATA ANALASYS
# VDC -> VERTICAL DISTANCE CONTROL
# If we're only slightly above the landing area, make sure we don't get below it
if y < flat[2] + min_v_distance and v_speed < 1:
allowed_angle = max_angle
# HDC -> HORIZONTAL DISTANCE CONTROL
# Horizontal Speed Info
delta_h_speed = abs(min_h_speed - abs(h_speed)) # Delta v we need to get to min_h_speed
h_acc = math.sin(math.radians(allowed_angle)) * 4 # Horizontal Acceleration
time_to_h_decelerate = 1.3 * delta_h_speed / h_acc # Time to decelerate given by Delta v over a
delta_h_pos = time_to_h_decelerate * (h_speed + min_h_speed) / 2 # Delta h position if we start breaking now
final_h_pos = x + delta_h_pos
# Get to landing area ASAP
if dist != 0:
new_rotate = -allowed_angle * direction
new_power = 4
# HSC -> HORIZONTAL SPEED CONTROL
# Activate HSC if we are already going to stop in the right area if we start breaking now, Position = x + vt, where v is average speed of the interval!
if (flat[0] < final_h_pos < flat[1]):
if abs(h_speed) > min_h_speed:
new_rotate = allowed_angle * (1 if h_speed > 0 else -1)
elif (flat[0] < final_h_pos and dist >= 0) or (flat[1] > final_h_pos and dist <= 0):
new_rotate = allowed_angle * (1 if h_speed > 0 else -1)
# VSC -> VERTCAL SPEED CONTROL
# Make sure we keep a constant vertical speed
if abs(new_rotate) > max_angle:
if abs(v_speed) > 35:
new_rotate = -max_angle * direction
# LP -> LANDING PROTOCOL
# Start landing protocols
if dist == 0:
# Local HSC (Horizontal Speed Control)
if flat[0] + 100 > final_h_pos:
new_rotate = -allowed_angle
new_power = 4
elif flat[1] - 100 < final_h_pos:
new_rotate = allowed_angle
new_power = 4
if abs(h_speed) > min_h_speed:
new_rotate = allowed_angle * (1 if h_speed > 0 else -1)
new_power = 4
# Local VSC (Vertical Speed Control)
print(v_speed, file=sys.stderr)
if v_speed < -35:
new_power = 4
new_rotate = 0
elif v_speed > -15:
new_power = 3
if y < flat[2] + 50:
new_rotate = 0
# print(rotate power)
print(f'{int(new_rotate)} {new_power}') | Puzzles/Medium/003-Mars-Lander-Ep2.py | import sys
import math
# CONSTANTS
g = 3.711 # Gravity
max_angle = math.degrees(math.acos(g / 4)) - 1 # Maximum angle for constant vertical velocity at thrust 4
# PARAMETERS
min_h_speed = 10 # Minimum acceptable horizontal speed
min_v_distance = 750
# FIRST INPUTS
# The number of points used to draw the surface of Mars.
surface_n = int(input())
surface = []
for i in range(surface_n):
# land_x: X coordinate of a surface point. (0 to 6999)
# land_y: Y coordinate of a surface point. By linking all the points together in a sequential fashion, you form the surface of Mars.
surface += [[int(j) for j in input().split()]]
# HELPER FUNCTIONS
def find_flat(surface):
for index in range(len(surface) - 1):
if surface[index][1] == surface[index + 1][1]:
return [surface[index][0], surface[index + 1][0], surface[index][1]]
def dist_to_flat(x, flat):
start, end = flat[0], flat[1]
if x < start:
return start - x
elif x > end:
return end - x
else:
return 0
# Find the flat surface
flat = find_flat(surface)
# Game Loop
while True:
# h_speed: the horizontal speed (in m/s), can be negative.
# v_speed: the vertical speed (in m/s), can be negative.
# fuel: the quantity of remaining fuel in liters.
# rotate: the rotation angle in degrees (-90 to 90).
# power: the thrust power (0 to 4).
x, y, h_speed, v_speed, fuel, rotate, power = [int(i) for i in input().split()]
dist = dist_to_flat(x, flat)
direction = -1 if dist < 0 else 1
# CONTOL SYSTEM
new_rotate = 0
new_power = 4
allowed_angle = 45 # Allowed Angle to Turn
# DATA ANALASYS
# VDC -> VERTICAL DISTANCE CONTROL
# If we're only slightly above the landing area, make sure we don't get below it
if y < flat[2] + min_v_distance and v_speed < 1:
allowed_angle = max_angle
# HDC -> HORIZONTAL DISTANCE CONTROL
# Horizontal Speed Info
delta_h_speed = abs(min_h_speed - abs(h_speed)) # Delta v we need to get to min_h_speed
h_acc = math.sin(math.radians(allowed_angle)) * 4 # Horizontal Acceleration
time_to_h_decelerate = 1.3 * delta_h_speed / h_acc # Time to decelerate given by Delta v over a
delta_h_pos = time_to_h_decelerate * (h_speed + min_h_speed) / 2 # Delta h position if we start breaking now
final_h_pos = x + delta_h_pos
# Get to landing area ASAP
if dist != 0:
new_rotate = -allowed_angle * direction
new_power = 4
# HSC -> HORIZONTAL SPEED CONTROL
# Activate HSC if we are already going to stop in the right area if we start breaking now, Position = x + vt, where v is average speed of the interval!
if (flat[0] < final_h_pos < flat[1]):
if abs(h_speed) > min_h_speed:
new_rotate = allowed_angle * (1 if h_speed > 0 else -1)
elif (flat[0] < final_h_pos and dist >= 0) or (flat[1] > final_h_pos and dist <= 0):
new_rotate = allowed_angle * (1 if h_speed > 0 else -1)
# VSC -> VERTCAL SPEED CONTROL
# Make sure we keep a constant vertical speed
if abs(new_rotate) > max_angle:
if abs(v_speed) > 35:
new_rotate = -max_angle * direction
# LP -> LANDING PROTOCOL
# Start landing protocols
if dist == 0:
# Local HSC (Horizontal Speed Control)
if flat[0] + 100 > final_h_pos:
new_rotate = -allowed_angle
new_power = 4
elif flat[1] - 100 < final_h_pos:
new_rotate = allowed_angle
new_power = 4
if abs(h_speed) > min_h_speed:
new_rotate = allowed_angle * (1 if h_speed > 0 else -1)
new_power = 4
# Local VSC (Vertical Speed Control)
print(v_speed, file=sys.stderr)
if v_speed < -35:
new_power = 4
new_rotate = 0
elif v_speed > -15:
new_power = 3
if y < flat[2] + 50:
new_rotate = 0
# print(rotate power)
print(f'{int(new_rotate)} {new_power}') | 0.415017 | 0.61286 |
from pathlib import Path
from flake8_bandit import BanditTester
import pytest
def _get_errors(filename):
filename = Path(__file__).absolute().parent / filename
bt = BanditTester(tree=None, filename=str(filename), lines=None)
return list(bt.run())
@pytest.mark.parametrize(
"filename,line,message",
[
pytest.param(
"assert.py",
1,
"S101 Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.",
),
pytest.param("binding.py", 4, "S104 Possible binding to all interfaces."),
pytest.param(
"cipher-modes.py",
6,
"S305 Use of insecure cipher mode cryptography.hazmat.primitives.ciphers.modes.ECB.",
),
pytest.param(
"ciphers.py",
1,
"S413 The pyCrypto library and its module ARC2 are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"ciphers.py",
2,
"S413 The pyCrypto library and its module ARC4 are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"ciphers.py",
3,
"S413 The pyCrypto library and its module Blowfish are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"ciphers.py",
4,
"S413 The pyCrypto library and its module DES are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"ciphers.py",
5,
"S413 The pyCrypto library and its module XOR are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"ciphers.py",
11,
"S413 The pyCrypto library and its module SHA are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"ciphers.py",
12,
"S413 The pyCrypto library and its module Random are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"ciphers.py",
13,
"S413 The pyCrypto library and its module Counter are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"ciphers.py",
22,
"S304 Use of insecure cipher Crypto.Cipher.ARC2.new. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
24,
"S304 Use of insecure cipher Cryptodome.Cipher.ARC2.new. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
29,
"S303 Use of insecure MD2, MD4, MD5, or SHA1 hash function.",
),
pytest.param(
"ciphers.py",
30,
"S304 Use of insecure cipher Crypto.Cipher.ARC4.new. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
32,
"S304 Use of insecure cipher Cryptodome.Cipher.ARC4.new. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
42,
"S304 Use of insecure cipher Crypto.Cipher.Blowfish.new. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
45,
"S304 Use of insecure cipher Cryptodome.Cipher.Blowfish.new. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
52,
"S304 Use of insecure cipher Crypto.Cipher.DES.new. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
56,
"S304 Use of insecure cipher Cryptodome.Cipher.DES.new. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
61,
"S304 Use of insecure cipher Crypto.Cipher.XOR.new. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
63,
"S304 Use of insecure cipher Cryptodome.Cipher.XOR.new. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
66,
"S304 Use of insecure cipher cryptography.hazmat.primitives.ciphers.algorithms.ARC4. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
70,
"S304 Use of insecure cipher cryptography.hazmat.primitives.ciphers.algorithms.Blowfish. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
74,
"S304 Use of insecure cipher cryptography.hazmat.primitives.ciphers.algorithms.IDEA. Replace with a known secure cipher such as AES.",
),
pytest.param(
"dill.py",
1,
"S403 Consider possible security implications associated with dill module.",
),
pytest.param(
"dill.py",
6,
"S301 Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.",
),
pytest.param(
"dill.py",
11,
"S301 Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.",
),
pytest.param(
"django_sql_injection_extra.py",
12,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_extra.py",
13,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_extra.py",
15,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_extra.py",
16,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_extra.py",
17,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_extra.py",
20,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_extra.py",
22,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_extra.py",
23,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_extra.py",
24,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_extra.py",
27,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_extra.py",
29,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_raw.py",
5,
"S611 Use of RawSQL potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_raw.py",
6,
"S611 Use of RawSQL potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_raw.py",
8,
"S611 Use of RawSQL potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_raw.py",
11,
"S611 Use of RawSQL potential SQL attack vector.",
),
pytest.param(
"eval.py",
3,
"S307 Use of possibly insecure function - consider using safer ast.literal_eval.",
),
pytest.param(
"eval.py",
4,
"S307 Use of possibly insecure function - consider using safer ast.literal_eval.",
),
pytest.param(
"eval.py",
5,
"S307 Use of possibly insecure function - consider using safer ast.literal_eval.",
),
pytest.param("exec-py3.py", 1, "S102 Use of exec detected."),
pytest.param(
"flask_debug.py",
10,
"S201 A Flask app appears to be run with debug=True, which exposes the Werkzeug debugger and allows the execution of arbitrary code.",
),
pytest.param(
"ftplib.py",
1,
"S402 A FTP-related module is being imported. FTP is considered insecure. Use SSH/SFTP/SCP or some other encrypted protocol.",
),
pytest.param(
"ftplib.py",
3,
"S321 FTP-related functions are being called. FTP is considered insecure. Use SSH/SFTP/SCP or some other encrypted protocol.",
),
pytest.param(
"hardcoded-passwords.py", 1, "S107 Possible hardcoded password: '<PASSWORD>'"
),
pytest.param(
"hardcoded-passwords.py", 5, "S105 Possible hardcoded password: 'root'"
),
pytest.param(
"hardcoded-passwords.py", 9, "S105 Possible hardcoded password: ''"
),
pytest.param(
"hardcoded-passwords.py",
13,
"S105 Possible hardcoded password: '<PASSWORD>'",
),
pytest.param(
"hardcoded-passwords.py", 16, "S107 Possible hardcoded password: '<PASSWORD>'"
),
pytest.param(
"hardcoded-passwords.py", 22, "S106 Possible hardcoded password: '<PASSWORD>'"
),
pytest.param(
"hardcoded-passwords.py", 23, "S105 Possible hardcoded password: '<PASSWORD>'"
),
pytest.param(
"hardcoded-passwords.py", 24, "S105 Possible hardcoded password: '<PASSWORD>'"
),
pytest.param(
"hardcoded-passwords.py", 26, "S105 Possible hardcoded password: '<PASSWORD>'"
),
pytest.param(
"hardcoded-passwords.py",
27,
"S105 Possible hardcoded password: '<PASSWORD>'",
),
pytest.param(
"hardcoded-passwords.py",
28,
"S105 Possible hardcoded password: '<PASSWORD>'",
),
pytest.param(
"hardcoded-passwords.py", 29, "S105 Possible hardcoded password: '<PASSWORD>'"
),
pytest.param(
"hardcoded-tmp.py",
1,
"S108 Probable insecure usage of temp file/directory.",
),
pytest.param(
"hardcoded-tmp.py",
8,
"S108 Probable insecure usage of temp file/directory.",
),
pytest.param(
"hardcoded-tmp.py",
11,
"S108 Probable insecure usage of temp file/directory.",
),
pytest.param(
"hashlib_new_insecure_functions.py",
3,
"S324 Use of insecure MD4 or MD5 hash function.",
),
pytest.param(
"hashlib_new_insecure_functions.py",
5,
"S324 Use of insecure MD4 or MD5 hash function.",
),
pytest.param(
"hashlib_new_insecure_functions.py",
7,
"S324 Use of insecure MD4 or MD5 hash function.",
),
pytest.param(
"hashlib_new_insecure_functions.py",
9,
"S324 Use of insecure MD4 or MD5 hash function.",
),
pytest.param(
"hashlib_new_insecure_functions.py",
11,
"S324 Use of insecure MD4 or MD5 hash function.",
),
pytest.param(
"httplib_https.py",
2,
"S309 Use of HTTPSConnection on older versions of Python prior to 2.7.9 and 3.4.3 do not provide security, see https://wiki.openstack.org/wiki/OSSN/OSSN-0033",
),
pytest.param(
"httplib_https.py",
5,
"S309 Use of HTTPSConnection on older versions of Python prior to 2.7.9 and 3.4.3 do not provide security, see https://wiki.openstack.org/wiki/OSSN/OSSN-0033",
),
pytest.param(
"httplib_https.py",
8,
"S309 Use of HTTPSConnection on older versions of Python prior to 2.7.9 and 3.4.3 do not provide security, see https://wiki.openstack.org/wiki/OSSN/OSSN-0033",
),
pytest.param(
"httpoxy_cgihandler.py",
10,
"S412 Consider possible security implications associated with wsgiref.handlers.CGIHandler module.",
),
pytest.param(
"httpoxy_twisted_directory.py",
5,
"S412 Consider possible security implications associated with twisted.web.twcgi.CGIDirectory module.",
),
pytest.param(
"httpoxy_twisted_script.py",
5,
"S412 Consider possible security implications associated with twisted.web.twcgi.CGIScript module.",
),
pytest.param(
"imports-aliases.py",
1,
"S404 Consider possible security implications associated with Popen module.",
),
pytest.param(
"imports-aliases.py",
6,
"S403 Consider possible security implications associated with loads module.",
),
pytest.param(
"imports-aliases.py",
7,
"S403 Consider possible security implications associated with pickle module.",
),
pytest.param(
"imports-aliases.py",
9,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"imports-aliases.py",
11,
"S303 Use of insecure MD2, MD4, MD5, or SHA1 hash function.",
),
pytest.param(
"imports-aliases.py",
12,
"S303 Use of insecure MD2, MD4, MD5, or SHA1 hash function.",
),
pytest.param(
"imports-aliases.py",
13,
"S303 Use of insecure MD2, MD4, MD5, or SHA1 hash function.",
),
pytest.param(
"imports-aliases.py",
14,
"S303 Use of insecure MD2, MD4, MD5, or SHA1 hash function.",
),
pytest.param(
"imports-aliases.py",
15,
"S301 Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.",
),
pytest.param(
"imports-from.py",
1,
"S404 Consider possible security implications associated with Popen module.",
),
pytest.param(
"imports-from.py",
6,
"S404 Consider possible security implications associated with subprocess module.",
),
pytest.param(
"imports-from.py",
7,
"S404 Consider possible security implications associated with Popen module.",
),
pytest.param(
"imports-function.py",
2,
"S403 Consider possible security implications associated with pickle module.",
),
pytest.param(
"imports-function.py",
4,
"S404 Consider possible security implications associated with subprocess module.",
),
pytest.param(
"imports.py",
2,
"S403 Consider possible security implications associated with pickle module.",
),
pytest.param(
"imports.py",
4,
"S404 Consider possible security implications associated with subprocess module.",
),
pytest.param(
"imports-with-importlib.py",
3,
"S403 Consider possible security implications associated with pickle module.",
),
pytest.param(
"imports-with-importlib.py",
5,
"S404 Consider possible security implications associated with subprocess module.",
),
pytest.param(
"input.py",
1,
"S322 The input method in Python 2 will read from standard input, evaluate and run the resulting string as python source code. This is similar, though in many ways worse, then using eval. On Python 2, use raw_input instead, input is safe in Python 3.",
),
pytest.param(
"jinja2_templating.py",
9,
"S701 Using jinja2 templates with autoescape=False is dangerous and can lead to XSS. Ensure autoescape=True or use the select_autoescape function to mitigate XSS vulnerabilities.",
),
pytest.param(
"jinja2_templating.py",
10,
"S701 Using jinja2 templates with autoescape=False is dangerous and can lead to XSS. Use autoescape=True or use the select_autoescape function to mitigate XSS vulnerabilities.",
),
pytest.param(
"jinja2_templating.py",
11,
"S701 Using jinja2 templates with autoescape=False is dangerous and can lead to XSS. Use autoescape=True or use the select_autoescape function to mitigate XSS vulnerabilities.",
),
pytest.param(
"jinja2_templating.py",
15,
"S701 By default, jinja2 sets autoescape to False. Consider using autoescape=True or use the select_autoescape function to mitigate XSS vulnerabilities.",
),
pytest.param(
"jinja2_templating.py",
26,
"S701 Using jinja2 templates with autoescape=False is dangerous and can lead to XSS. Ensure autoescape=True or use the select_autoescape function to mitigate XSS vulnerabilities.",
),
pytest.param(
"mako_templating.py",
6,
"S702 Mako templates allow HTML/JS rendering by default and are inherently open to XSS attacks. Ensure variables in all templates are properly sanitized via the 'n', 'h' or 'x' flags (depending on context). For example, to HTML escape the variable 'data' do ${ data |h }.",
),
pytest.param(
"mako_templating.py",
10,
"S702 Mako templates allow HTML/JS rendering by default and are inherently open to XSS attacks. Ensure variables in all templates are properly sanitized via the 'n', 'h' or 'x' flags (depending on context). For example, to HTML escape the variable 'data' do ${ data |h }.",
),
pytest.param(
"mako_templating.py",
11,
"S702 Mako templates allow HTML/JS rendering by default and are inherently open to XSS attacks. Ensure variables in all templates are properly sanitized via the 'n', 'h' or 'x' flags (depending on context). For example, to HTML escape the variable 'data' do ${ data |h }.",
),
pytest.param(
"mark_safe_insecure.py", 10, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
10,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 11, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py", 12, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py", 13, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py", 14, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py", 22, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
22,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 30, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
30,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py",
35,
"S311 Standard pseudo-random generators are not suitable for security/cryptographic purposes.",
),
pytest.param(
"mark_safe_insecure.py", 41, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
41,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py",
46,
"S311 Standard pseudo-random generators are not suitable for security/cryptographic purposes.",
),
pytest.param(
"mark_safe_insecure.py", 54, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
54,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 59, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
59,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 64, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
64,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 69, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
69,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 74, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
74,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 79, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
79,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 84, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
84,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 89, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
89,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 94, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
94,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 99, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
99,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 104, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
104,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 109, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
109,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 114, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
114,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 119, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
119,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py",
124,
"S311 Standard pseudo-random generators are not suitable for security/cryptographic purposes.",
),
pytest.param(
"mark_safe_insecure.py", 126, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
126,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 133, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
133,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 143, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
143,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 149, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
149,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 153, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
153,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 159, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
159,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe.py",
4,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
4,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
11,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
14,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
17,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
29,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
33,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
35,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
36,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
37,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py", 38, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_secure.py",
38,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py", 39, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_secure.py",
39,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
41,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
45,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
47,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
48,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py", 49, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_secure.py",
49,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
54,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
62,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
65,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
75,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"marshal_deserialize.py",
6,
"S302 Deserialization with the marshal module is possibly dangerous.",
),
pytest.param(
"marshal_deserialize.py",
11,
"S302 Deserialization with the marshal module is possibly dangerous.",
),
pytest.param(
"mktemp.py", 7, "S306 Use of insecure and deprecated function (mktemp)."
),
pytest.param(
"mktemp.py", 8, "S306 Use of insecure and deprecated function (mktemp)."
),
pytest.param(
"mktemp.py", 9, "S306 Use of insecure and deprecated function (mktemp)."
),
pytest.param(
"mktemp.py", 10, "S306 Use of insecure and deprecated function (mktemp)."
),
pytest.param(
"multiline_statement.py",
1,
"S404 Consider possible security implications associated with subprocess module.",
),
pytest.param(
"multiline_statement.py",
5,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"new_candidates-all.py",
7,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"new_candidates-all.py",
9,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"new_candidates-all.py",
15,
"S506 Use of unsafe yaml load. Allows instantiation of arbitrary objects. Consider yaml.safe_load().",
),
pytest.param(
"new_candidates-all.py",
17,
"S506 Use of unsafe yaml load. Allows instantiation of arbitrary objects. Consider yaml.safe_load().",
),
pytest.param(
"new_candidates-all.py",
22,
"S317 Using xml.sax.make_parser to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.make_parser with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"new_candidates-all.py",
24,
"S317 Using xml.sax.make_parser to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.make_parser with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"new_candidates-nosec.py",
7,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"new_candidates-nosec.py",
13,
"S506 Use of unsafe yaml load. Allows instantiation of arbitrary objects. Consider yaml.safe_load().",
),
pytest.param(
"new_candidates-nosec.py",
18,
"S317 Using xml.sax.make_parser to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.make_parser with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"new_candidates-some.py",
7,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"new_candidates-some.py",
9,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"new_candidates-some.py",
15,
"S506 Use of unsafe yaml load. Allows instantiation of arbitrary objects. Consider yaml.safe_load().",
),
pytest.param(
"new_candidates-some.py",
20,
"S317 Using xml.sax.make_parser to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.make_parser with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"no_host_key_verification.py",
4,
"S507 Paramiko call with policy set to automatically trust the unknown host key.",
),
pytest.param(
"no_host_key_verification.py",
5,
"S507 Paramiko call with policy set to automatically trust the unknown host key.",
),
pytest.param(
"os-chmod-py3.py",
6,
"S103 Chmod setting a permissive mask 0o227 on file (/etc/passwd).",
),
pytest.param(
"os-chmod-py3.py",
7,
"S103 Chmod setting a permissive mask 0o7 on file (/etc/passwd).",
),
pytest.param(
"os-chmod-py3.py",
9,
"S103 Chmod setting a permissive mask 0o777 on file (/etc/passwd).",
),
pytest.param(
"os-chmod-py3.py",
10,
"S103 Chmod setting a permissive mask 0o770 on file (/etc/passwd).",
),
pytest.param(
"os-chmod-py3.py",
11,
"S103 Chmod setting a permissive mask 0o776 on file (/etc/passwd).",
),
pytest.param(
"os-chmod-py3.py",
13,
"S103 Chmod setting a permissive mask 0o777 on file (~/.bashrc).",
),
pytest.param(
"os-chmod-py3.py",
14,
"S103 Chmod setting a permissive mask 0o777 on file (/etc/hosts).",
),
pytest.param(
"os-chmod-py3.py",
15,
"S103 Chmod setting a permissive mask 0o777 on file (/tmp/oh_hai).",
),
pytest.param(
"os-chmod-py3.py",
15,
"S108 Probable insecure usage of temp file/directory.",
),
pytest.param(
"os-chmod-py3.py",
17,
"S103 Chmod setting a permissive mask 0o777 on file (key_file).",
),
pytest.param("os-exec.py", 3, "S606 Starting a process without a shell."),
pytest.param("os-exec.py", 4, "S606 Starting a process without a shell."),
pytest.param("os-exec.py", 5, "S606 Starting a process without a shell."),
pytest.param("os-exec.py", 6, "S606 Starting a process without a shell."),
pytest.param("os-exec.py", 7, "S606 Starting a process without a shell."),
pytest.param("os-exec.py", 8, "S606 Starting a process without a shell."),
pytest.param("os-exec.py", 9, "S606 Starting a process without a shell."),
pytest.param("os-exec.py", 10, "S606 Starting a process without a shell."),
pytest.param(
"os-popen.py",
6,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"os-popen.py",
7,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"os-popen.py",
8,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"os-popen.py",
9,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"os-popen.py",
10,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"os-popen.py",
11,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"os-popen.py",
12,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"os-popen.py",
14,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"os-popen.py",
15,
"S605 Starting a process with a shell, possible injection detected, security issue.",
),
pytest.param("os-spawn.py", 3, "S606 Starting a process without a shell."),
pytest.param("os-spawn.py", 4, "S606 Starting a process without a shell."),
pytest.param("os-spawn.py", 5, "S606 Starting a process without a shell."),
pytest.param("os-spawn.py", 6, "S606 Starting a process without a shell."),
pytest.param("os-spawn.py", 7, "S606 Starting a process without a shell."),
pytest.param("os-spawn.py", 8, "S606 Starting a process without a shell."),
pytest.param("os-spawn.py", 9, "S606 Starting a process without a shell."),
pytest.param("os-spawn.py", 10, "S606 Starting a process without a shell."),
pytest.param("os-startfile.py", 3, "S606 Starting a process without a shell."),
pytest.param("os-startfile.py", 4, "S606 Starting a process without a shell."),
pytest.param("os-startfile.py", 5, "S606 Starting a process without a shell."),
pytest.param(
"os_system.py",
3,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"paramiko_injection.py",
7,
"S601 Possible shell injection via Paramiko call, check inputs are properly sanitized.",
),
pytest.param(
"pickle_deserialize.py",
1,
"S403 Consider possible security implications associated with cPickle module.",
),
pytest.param(
"pickle_deserialize.py",
2,
"S403 Consider possible security implications associated with pickle module.",
),
pytest.param(
"pickle_deserialize.py",
8,
"S301 Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.",
),
pytest.param(
"pickle_deserialize.py",
13,
"S301 Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.",
),
pytest.param(
"pickle_deserialize.py",
16,
"S301 Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.",
),
pytest.param(
"pickle_deserialize.py",
20,
"S301 Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.",
),
pytest.param(
"pickle_deserialize.py",
25,
"S301 Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.",
),
pytest.param(
"pickle_deserialize.py",
28,
"S301 Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.",
),
pytest.param(
"popen_wrappers.py",
5,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"popen_wrappers.py",
6,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"popen_wrappers.py",
11,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"popen_wrappers.py",
12,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"popen_wrappers.py",
13,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"popen_wrappers.py",
14,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"popen_wrappers.py",
15,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"pycrypto.py",
1,
"S413 The pyCrypto library and its module AES are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"pycrypto.py",
2,
"S413 The pyCrypto library and its module Random are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"random_module.py",
5,
"S311 Standard pseudo-random generators are not suitable for security/cryptographic purposes.",
),
pytest.param(
"random_module.py",
6,
"S311 Standard pseudo-random generators are not suitable for security/cryptographic purposes.",
),
pytest.param(
"random_module.py",
7,
"S311 Standard pseudo-random generators are not suitable for security/cryptographic purposes.",
),
pytest.param(
"random_module.py",
8,
"S311 Standard pseudo-random generators are not suitable for security/cryptographic purposes.",
),
pytest.param(
"random_module.py",
9,
"S311 Standard pseudo-random generators are not suitable for security/cryptographic purposes.",
),
pytest.param(
"random_module.py",
10,
"S311 Standard pseudo-random generators are not suitable for security/cryptographic purposes.",
),
pytest.param(
"requests-ssl-verify-disabled.py",
4,
"S501 Requests call with verify=False disabling SSL certificate checks, security issue.",
),
pytest.param(
"requests-ssl-verify-disabled.py",
6,
"S501 Requests call with verify=False disabling SSL certificate checks, security issue.",
),
pytest.param(
"requests-ssl-verify-disabled.py",
8,
"S501 Requests call with verify=False disabling SSL certificate checks, security issue.",
),
pytest.param(
"requests-ssl-verify-disabled.py",
10,
"S501 Requests call with verify=False disabling SSL certificate checks, security issue.",
),
pytest.param(
"requests-ssl-verify-disabled.py",
12,
"S501 Requests call with verify=False disabling SSL certificate checks, security issue.",
),
pytest.param(
"requests-ssl-verify-disabled.py",
14,
"S501 Requests call with verify=False disabling SSL certificate checks, security issue.",
),
pytest.param(
"requests-ssl-verify-disabled.py",
16,
"S501 Requests call with verify=False disabling SSL certificate checks, security issue.",
),
pytest.param(
"skip.py",
1,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"skip.py",
2,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"skip.py",
3,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"skip.py",
4,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"skip.py",
5,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"skip.py",
6,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"skip.py",
7,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"sql_statements.py",
4,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
5,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
6,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
7,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
9,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
11,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
12,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
15,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
16,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
17,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
18,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
20,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
21,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
35,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"ssl-insecure-version.py",
4,
"S502 ssl.wrap_socket call with insecure SSL/TLS protocol version identified, security issue.",
),
pytest.param(
"ssl-insecure-version.py",
5,
"S502 SSL.Context call with insecure SSL/TLS protocol version identified, security issue.",
),
pytest.param(
"ssl-insecure-version.py",
6,
"S502 SSL.Context call with insecure SSL/TLS protocol version identified, security issue.",
),
pytest.param(
"ssl-insecure-version.py",
8,
"S502 Function call with insecure SSL/TLS protocol identified, possible security issue.",
),
pytest.param(
"ssl-insecure-version.py",
9,
"S502 Function call with insecure SSL/TLS protocol identified, possible security issue.",
),
pytest.param(
"ssl-insecure-version.py",
10,
"S502 Function call with insecure SSL/TLS protocol identified, possible security issue.",
),
pytest.param(
"ssl-insecure-version.py",
13,
"S502 ssl.wrap_socket call with insecure SSL/TLS protocol version identified, security issue.",
),
pytest.param(
"ssl-insecure-version.py",
14,
"S502 ssl.wrap_socket call with insecure SSL/TLS protocol version identified, security issue.",
),
pytest.param(
"ssl-insecure-version.py",
15,
"S502 SSL.Context call with insecure SSL/TLS protocol version identified, security issue.",
),
pytest.param(
"ssl-insecure-version.py",
16,
"S502 SSL.Context call with insecure SSL/TLS protocol version identified, security issue.",
),
pytest.param(
"ssl-insecure-version.py",
18,
"S502 Function call with insecure SSL/TLS protocol identified, possible security issue.",
),
pytest.param(
"ssl-insecure-version.py",
19,
"S502 Function call with insecure SSL/TLS protocol identified, possible security issue.",
),
pytest.param(
"ssl-insecure-version.py",
20,
"S502 Function call with insecure SSL/TLS protocol identified, possible security issue.",
),
pytest.param(
"ssl-insecure-version.py",
21,
"S502 Function call with insecure SSL/TLS protocol identified, possible security issue.",
),
pytest.param(
"ssl-insecure-version.py",
23,
"S504 ssl.wrap_socket call with no SSL/TLS protocol version specified, the default SSLv23 could be insecure, possible security issue.",
),
pytest.param(
"ssl-insecure-version.py",
25,
"S503 Function definition identified with insecure SSL/TLS protocol version by default, possible security issue.",
),
pytest.param(
"ssl-insecure-version.py",
28,
"S503 Function definition identified with insecure SSL/TLS protocol version by default, possible security issue.",
),
pytest.param(
"ssl-insecure-version.py",
31,
"S503 Function definition identified with insecure SSL/TLS protocol version by default, possible security issue.",
),
pytest.param(
"subprocess_shell.py",
1,
"S404 Consider possible security implications associated with subprocess module.",
),
pytest.param(
"subprocess_shell.py",
2,
"S404 Consider possible security implications associated with Popen module.",
),
pytest.param(
"subprocess_shell.py",
11,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"subprocess_shell.py",
12,
"S604 Function call with shell=True parameter identified, possible security issue.",
),
pytest.param(
"subprocess_shell.py",
14,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"subprocess_shell.py",
15,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"subprocess_shell.py",
16,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"subprocess_shell.py",
18,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"subprocess_shell.py",
21,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"subprocess_shell.py",
23,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"subprocess_shell.py",
24,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"subprocess_shell.py",
26,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"subprocess_shell.py",
27,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"subprocess_shell.py",
29,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"subprocess_shell.py",
30,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"subprocess_shell.py",
32,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"subprocess_shell.py",
33,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
34,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
37,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
39,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"subprocess_shell.py",
42,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
43,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
44,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
45,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
47,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
48,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
49,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
50,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
52,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"subprocess_shell.py",
53,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"subprocess_shell.py",
54,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"subprocess_shell.py",
55,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"subprocess_shell.py",
56,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"telnetlib.py",
1,
"S401 A telnet-related module is being imported. Telnet is considered insecure. Use SSH or some other encrypted protocol.",
),
pytest.param(
"telnetlib.py",
8,
"S312 Telnet-related functions are being called. Telnet is considered insecure. Use SSH or some other encrypted protocol.",
),
pytest.param(
"tempnam.py",
5,
"S325 Use of os.tempnam() and os.tmpnam() is vulnerable to symlink attacks. Consider using tmpfile() instead.",
),
pytest.param(
"tempnam.py",
7,
"S325 Use of os.tempnam() and os.tmpnam() is vulnerable to symlink attacks. Consider using tmpfile() instead.",
),
pytest.param(
"tempnam.py",
9,
"S325 Use of os.tempnam() and os.tmpnam() is vulnerable to symlink attacks. Consider using tmpfile() instead.",
),
pytest.param(
"tempnam.py",
10,
"S325 Use of os.tempnam() and os.tmpnam() is vulnerable to symlink attacks. Consider using tmpfile() instead.",
),
pytest.param(
"tempnam.py",
12,
"S325 Use of os.tempnam() and os.tmpnam() is vulnerable to symlink attacks. Consider using tmpfile() instead.",
),
pytest.param(
"tempnam.py",
13,
"S325 Use of os.tempnam() and os.tmpnam() is vulnerable to symlink attacks. Consider using tmpfile() instead.",
),
pytest.param(
"try_except_continue.py", 5, "S112 Try, Except, Continue detected."
),
pytest.param(
"try_except_continue.py", 13, "S112 Try, Except, Continue detected."
),
pytest.param("try_except_pass.py", 4, "S110 Try, Except, Pass detected."),
pytest.param("try_except_pass.py", 11, "S110 Try, Except, Pass detected."),
pytest.param(
"unverified_context.py",
7,
"S323 By default, Python will create a secure, verified ssl context for use in such classes as HTTPSConnection. However, it still allows using an insecure context via the _create_unverified_context that reverts to the previous behavior that does not validate certificates or perform hostname checks.",
),
pytest.param(
"urlopen.py",
22,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
23,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
24,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
27,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
38,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
39,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
42,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
43,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
44,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
47,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
52,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
53,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
54,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
57,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
5,
"S413 The pyCrypto library and its module DSA are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
6,
"S413 The pyCrypto library and its module RSA are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
38,
"S505 DSA key sizes below 2048 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
40,
"S505 EC key sizes below 224 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
42,
"S505 RSA key sizes below 2048 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
45,
"S505 DSA key sizes below 2048 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
46,
"S505 RSA key sizes below 2048 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
47,
"S505 DSA key sizes below 2048 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
48,
"S505 RSA key sizes below 2048 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
51,
"S505 DSA key sizes below 1024 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
53,
"S505 EC key sizes below 224 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
55,
"S505 RSA key sizes below 1024 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
58,
"S505 DSA key sizes below 1024 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
59,
"S505 RSA key sizes below 1024 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
60,
"S505 DSA key sizes below 1024 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
61,
"S505 RSA key sizes below 1024 bits are considered breakable. ",
),
pytest.param(
"wildcard-injection.py",
2,
"S404 Consider possible security implications associated with subprocess module.",
),
pytest.param(
"wildcard-injection.py",
5,
"S609 Possible wildcard injection in call: os.system",
),
pytest.param(
"wildcard-injection.py",
5,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"wildcard-injection.py",
6,
"S609 Possible wildcard injection in call: os.system",
),
pytest.param(
"wildcard-injection.py",
6,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"wildcard-injection.py",
7,
"S609 Possible wildcard injection in call: os.popen2",
),
pytest.param(
"wildcard-injection.py",
7,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"wildcard-injection.py",
8,
"S609 Possible wildcard injection in call: subprocess.Popen",
),
pytest.param(
"wildcard-injection.py",
8,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"wildcard-injection.py",
11,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"wildcard-injection.py",
12,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"wildcard-injection.py",
13,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"wildcard-injection.py",
14,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"wildcard-injection.py", 16, "S606 Starting a process without a shell."
),
pytest.param(
"xml_etree_celementtree.py",
1,
"S405 Using xml.etree.cElementTree to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.cElementTree with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.",
),
pytest.param(
"xml_etree_celementtree.py",
7,
"S313 Using xml.etree.cElementTree.fromstring to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.cElementTree.fromstring with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_etree_celementtree.py",
9,
"S313 Using xml.etree.cElementTree.parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.cElementTree.parse with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_etree_celementtree.py",
10,
"S313 Using xml.etree.cElementTree.iterparse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.cElementTree.iterparse with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_etree_celementtree.py",
11,
"S313 Using xml.etree.cElementTree.XMLParser to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.cElementTree.XMLParser with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_etree_elementtree.py",
1,
"S405 Using xml.etree.ElementTree to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.ElementTree with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.",
),
pytest.param(
"xml_etree_elementtree.py",
7,
"S314 Using xml.etree.ElementTree.fromstring to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.ElementTree.fromstring with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_etree_elementtree.py",
9,
"S314 Using xml.etree.ElementTree.parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.ElementTree.parse with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_etree_elementtree.py",
10,
"S314 Using xml.etree.ElementTree.iterparse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.ElementTree.iterparse with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_etree_elementtree.py",
11,
"S314 Using xml.etree.ElementTree.XMLParser to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.ElementTree.XMLParser with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_expatbuilder.py",
1,
"S407 Using xml.dom.expatbuilder to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.dom.expatbuilder with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.",
),
pytest.param(
"xml_expatbuilder.py",
4,
"S316 Using xml.dom.expatbuilder.parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.dom.expatbuilder.parse with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_expatbuilder.py",
9,
"S316 Using xml.dom.expatbuilder.parseString to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.dom.expatbuilder.parseString with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_expatreader.py",
1,
"S406 Using xml.sax.expatreader to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.expatreader with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.",
),
pytest.param(
"xml_expatreader.py",
4,
"S315 Using xml.sax.expatreader.create_parser to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.expatreader.create_parser with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_lxml.py",
1,
"S410 Using lxml.etree to parse untrusted XML data is known to be vulnerable to XML attacks. Replace lxml.etree with the equivalent defusedxml package.",
),
pytest.param(
"xml_lxml.py",
2,
"S410 Using lxml to parse untrusted XML data is known to be vulnerable to XML attacks. Replace lxml with the equivalent defusedxml package.",
),
pytest.param(
"xml_lxml.py",
3,
"S410 Using etree to parse untrusted XML data is known to be vulnerable to XML attacks. Replace etree with the equivalent defusedxml package.",
),
pytest.param(
"xml_lxml.py",
8,
"S320 Using lxml.etree.fromstring to parse untrusted XML data is known to be vulnerable to XML attacks. Replace lxml.etree.fromstring with its defusedxml equivalent function.",
),
pytest.param(
"xml_minidom.py",
1,
"S408 Using parseString to parse untrusted XML data is known to be vulnerable to XML attacks. Replace parseString with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.",
),
pytest.param(
"xml_minidom.py",
3,
"S318 Using xml.dom.minidom.parseString to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.dom.minidom.parseString with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_minidom.py",
9,
"S408 Using parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace parse with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.",
),
pytest.param(
"xml_minidom.py",
11,
"S318 Using xml.dom.minidom.parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.dom.minidom.parse with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_pulldom.py",
1,
"S409 Using parseString to parse untrusted XML data is known to be vulnerable to XML attacks. Replace parseString with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.",
),
pytest.param(
"xml_pulldom.py",
3,
"S319 Using xml.dom.pulldom.parseString to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.dom.pulldom.parseString with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_pulldom.py",
9,
"S409 Using parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace parse with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.",
),
pytest.param(
"xml_pulldom.py",
11,
"S319 Using xml.dom.pulldom.parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.dom.pulldom.parse with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_sax.py",
1,
"S406 Using xml.sax to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.",
),
pytest.param(
"xml_sax.py",
2,
"S406 Using sax to parse untrusted XML data is known to be vulnerable to XML attacks. Replace sax with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.",
),
pytest.param(
"xml_sax.py",
21,
"S317 Using xml.sax.parseString to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.parseString with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_sax.py",
22,
"S317 Using xml.sax.parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.parse with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_sax.py",
23,
"S317 Using xml.sax.parseString to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.parseString with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_sax.py",
24,
"S317 Using xml.sax.parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.parse with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_sax.py",
30,
"S317 Using xml.sax.make_parser to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.make_parser with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_sax.py",
31,
"S317 Using xml.sax.make_parser to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.make_parser with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_xmlrpc.py",
1,
"S411 Using xmlrpclib to parse untrusted XML data is known to be vulnerable to XML attacks. Use defused.xmlrpc.monkey_patch() function to monkey-patch xmlrpclib and mitigate XML vulnerabilities.",
),
pytest.param(
"yaml_load.py",
7,
"S506 Use of unsafe yaml load. Allows instantiation of arbitrary objects. Consider yaml.safe_load().",
),
],
)
def test_outputs(filename, line, message):
errors = _get_errors(filename)
idxes = []
for idx, error in enumerate(errors):
# Some lines have multiple errors and
# we need to check both
if error[0] == line:
idxes.append(idx)
# Assume failing tests for multiple lines
_pass = False
for idx in idxes:
if errors[idx][2] != message:
continue
# We found a matching message in the
# index list
_pass = True
assert errors[idx][0] == line
assert errors[idx][1] == 0
assert errors[idx][2] == message
if not _pass:
print(errors[idx])
print(idxes)
assert _pass | tests/test_bandit.py | from pathlib import Path
from flake8_bandit import BanditTester
import pytest
def _get_errors(filename):
filename = Path(__file__).absolute().parent / filename
bt = BanditTester(tree=None, filename=str(filename), lines=None)
return list(bt.run())
@pytest.mark.parametrize(
"filename,line,message",
[
pytest.param(
"assert.py",
1,
"S101 Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.",
),
pytest.param("binding.py", 4, "S104 Possible binding to all interfaces."),
pytest.param(
"cipher-modes.py",
6,
"S305 Use of insecure cipher mode cryptography.hazmat.primitives.ciphers.modes.ECB.",
),
pytest.param(
"ciphers.py",
1,
"S413 The pyCrypto library and its module ARC2 are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"ciphers.py",
2,
"S413 The pyCrypto library and its module ARC4 are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"ciphers.py",
3,
"S413 The pyCrypto library and its module Blowfish are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"ciphers.py",
4,
"S413 The pyCrypto library and its module DES are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"ciphers.py",
5,
"S413 The pyCrypto library and its module XOR are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"ciphers.py",
11,
"S413 The pyCrypto library and its module SHA are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"ciphers.py",
12,
"S413 The pyCrypto library and its module Random are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"ciphers.py",
13,
"S413 The pyCrypto library and its module Counter are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"ciphers.py",
22,
"S304 Use of insecure cipher Crypto.Cipher.ARC2.new. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
24,
"S304 Use of insecure cipher Cryptodome.Cipher.ARC2.new. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
29,
"S303 Use of insecure MD2, MD4, MD5, or SHA1 hash function.",
),
pytest.param(
"ciphers.py",
30,
"S304 Use of insecure cipher Crypto.Cipher.ARC4.new. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
32,
"S304 Use of insecure cipher Cryptodome.Cipher.ARC4.new. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
42,
"S304 Use of insecure cipher Crypto.Cipher.Blowfish.new. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
45,
"S304 Use of insecure cipher Cryptodome.Cipher.Blowfish.new. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
52,
"S304 Use of insecure cipher Crypto.Cipher.DES.new. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
56,
"S304 Use of insecure cipher Cryptodome.Cipher.DES.new. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
61,
"S304 Use of insecure cipher Crypto.Cipher.XOR.new. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
63,
"S304 Use of insecure cipher Cryptodome.Cipher.XOR.new. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
66,
"S304 Use of insecure cipher cryptography.hazmat.primitives.ciphers.algorithms.ARC4. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
70,
"S304 Use of insecure cipher cryptography.hazmat.primitives.ciphers.algorithms.Blowfish. Replace with a known secure cipher such as AES.",
),
pytest.param(
"ciphers.py",
74,
"S304 Use of insecure cipher cryptography.hazmat.primitives.ciphers.algorithms.IDEA. Replace with a known secure cipher such as AES.",
),
pytest.param(
"dill.py",
1,
"S403 Consider possible security implications associated with dill module.",
),
pytest.param(
"dill.py",
6,
"S301 Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.",
),
pytest.param(
"dill.py",
11,
"S301 Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.",
),
pytest.param(
"django_sql_injection_extra.py",
12,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_extra.py",
13,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_extra.py",
15,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_extra.py",
16,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_extra.py",
17,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_extra.py",
20,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_extra.py",
22,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_extra.py",
23,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_extra.py",
24,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_extra.py",
27,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_extra.py",
29,
"S610 Use of extra potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_raw.py",
5,
"S611 Use of RawSQL potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_raw.py",
6,
"S611 Use of RawSQL potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_raw.py",
8,
"S611 Use of RawSQL potential SQL attack vector.",
),
pytest.param(
"django_sql_injection_raw.py",
11,
"S611 Use of RawSQL potential SQL attack vector.",
),
pytest.param(
"eval.py",
3,
"S307 Use of possibly insecure function - consider using safer ast.literal_eval.",
),
pytest.param(
"eval.py",
4,
"S307 Use of possibly insecure function - consider using safer ast.literal_eval.",
),
pytest.param(
"eval.py",
5,
"S307 Use of possibly insecure function - consider using safer ast.literal_eval.",
),
pytest.param("exec-py3.py", 1, "S102 Use of exec detected."),
pytest.param(
"flask_debug.py",
10,
"S201 A Flask app appears to be run with debug=True, which exposes the Werkzeug debugger and allows the execution of arbitrary code.",
),
pytest.param(
"ftplib.py",
1,
"S402 A FTP-related module is being imported. FTP is considered insecure. Use SSH/SFTP/SCP or some other encrypted protocol.",
),
pytest.param(
"ftplib.py",
3,
"S321 FTP-related functions are being called. FTP is considered insecure. Use SSH/SFTP/SCP or some other encrypted protocol.",
),
pytest.param(
"hardcoded-passwords.py", 1, "S107 Possible hardcoded password: '<PASSWORD>'"
),
pytest.param(
"hardcoded-passwords.py", 5, "S105 Possible hardcoded password: 'root'"
),
pytest.param(
"hardcoded-passwords.py", 9, "S105 Possible hardcoded password: ''"
),
pytest.param(
"hardcoded-passwords.py",
13,
"S105 Possible hardcoded password: '<PASSWORD>'",
),
pytest.param(
"hardcoded-passwords.py", 16, "S107 Possible hardcoded password: '<PASSWORD>'"
),
pytest.param(
"hardcoded-passwords.py", 22, "S106 Possible hardcoded password: '<PASSWORD>'"
),
pytest.param(
"hardcoded-passwords.py", 23, "S105 Possible hardcoded password: '<PASSWORD>'"
),
pytest.param(
"hardcoded-passwords.py", 24, "S105 Possible hardcoded password: '<PASSWORD>'"
),
pytest.param(
"hardcoded-passwords.py", 26, "S105 Possible hardcoded password: '<PASSWORD>'"
),
pytest.param(
"hardcoded-passwords.py",
27,
"S105 Possible hardcoded password: '<PASSWORD>'",
),
pytest.param(
"hardcoded-passwords.py",
28,
"S105 Possible hardcoded password: '<PASSWORD>'",
),
pytest.param(
"hardcoded-passwords.py", 29, "S105 Possible hardcoded password: '<PASSWORD>'"
),
pytest.param(
"hardcoded-tmp.py",
1,
"S108 Probable insecure usage of temp file/directory.",
),
pytest.param(
"hardcoded-tmp.py",
8,
"S108 Probable insecure usage of temp file/directory.",
),
pytest.param(
"hardcoded-tmp.py",
11,
"S108 Probable insecure usage of temp file/directory.",
),
pytest.param(
"hashlib_new_insecure_functions.py",
3,
"S324 Use of insecure MD4 or MD5 hash function.",
),
pytest.param(
"hashlib_new_insecure_functions.py",
5,
"S324 Use of insecure MD4 or MD5 hash function.",
),
pytest.param(
"hashlib_new_insecure_functions.py",
7,
"S324 Use of insecure MD4 or MD5 hash function.",
),
pytest.param(
"hashlib_new_insecure_functions.py",
9,
"S324 Use of insecure MD4 or MD5 hash function.",
),
pytest.param(
"hashlib_new_insecure_functions.py",
11,
"S324 Use of insecure MD4 or MD5 hash function.",
),
pytest.param(
"httplib_https.py",
2,
"S309 Use of HTTPSConnection on older versions of Python prior to 2.7.9 and 3.4.3 do not provide security, see https://wiki.openstack.org/wiki/OSSN/OSSN-0033",
),
pytest.param(
"httplib_https.py",
5,
"S309 Use of HTTPSConnection on older versions of Python prior to 2.7.9 and 3.4.3 do not provide security, see https://wiki.openstack.org/wiki/OSSN/OSSN-0033",
),
pytest.param(
"httplib_https.py",
8,
"S309 Use of HTTPSConnection on older versions of Python prior to 2.7.9 and 3.4.3 do not provide security, see https://wiki.openstack.org/wiki/OSSN/OSSN-0033",
),
pytest.param(
"httpoxy_cgihandler.py",
10,
"S412 Consider possible security implications associated with wsgiref.handlers.CGIHandler module.",
),
pytest.param(
"httpoxy_twisted_directory.py",
5,
"S412 Consider possible security implications associated with twisted.web.twcgi.CGIDirectory module.",
),
pytest.param(
"httpoxy_twisted_script.py",
5,
"S412 Consider possible security implications associated with twisted.web.twcgi.CGIScript module.",
),
pytest.param(
"imports-aliases.py",
1,
"S404 Consider possible security implications associated with Popen module.",
),
pytest.param(
"imports-aliases.py",
6,
"S403 Consider possible security implications associated with loads module.",
),
pytest.param(
"imports-aliases.py",
7,
"S403 Consider possible security implications associated with pickle module.",
),
pytest.param(
"imports-aliases.py",
9,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"imports-aliases.py",
11,
"S303 Use of insecure MD2, MD4, MD5, or SHA1 hash function.",
),
pytest.param(
"imports-aliases.py",
12,
"S303 Use of insecure MD2, MD4, MD5, or SHA1 hash function.",
),
pytest.param(
"imports-aliases.py",
13,
"S303 Use of insecure MD2, MD4, MD5, or SHA1 hash function.",
),
pytest.param(
"imports-aliases.py",
14,
"S303 Use of insecure MD2, MD4, MD5, or SHA1 hash function.",
),
pytest.param(
"imports-aliases.py",
15,
"S301 Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.",
),
pytest.param(
"imports-from.py",
1,
"S404 Consider possible security implications associated with Popen module.",
),
pytest.param(
"imports-from.py",
6,
"S404 Consider possible security implications associated with subprocess module.",
),
pytest.param(
"imports-from.py",
7,
"S404 Consider possible security implications associated with Popen module.",
),
pytest.param(
"imports-function.py",
2,
"S403 Consider possible security implications associated with pickle module.",
),
pytest.param(
"imports-function.py",
4,
"S404 Consider possible security implications associated with subprocess module.",
),
pytest.param(
"imports.py",
2,
"S403 Consider possible security implications associated with pickle module.",
),
pytest.param(
"imports.py",
4,
"S404 Consider possible security implications associated with subprocess module.",
),
pytest.param(
"imports-with-importlib.py",
3,
"S403 Consider possible security implications associated with pickle module.",
),
pytest.param(
"imports-with-importlib.py",
5,
"S404 Consider possible security implications associated with subprocess module.",
),
pytest.param(
"input.py",
1,
"S322 The input method in Python 2 will read from standard input, evaluate and run the resulting string as python source code. This is similar, though in many ways worse, then using eval. On Python 2, use raw_input instead, input is safe in Python 3.",
),
pytest.param(
"jinja2_templating.py",
9,
"S701 Using jinja2 templates with autoescape=False is dangerous and can lead to XSS. Ensure autoescape=True or use the select_autoescape function to mitigate XSS vulnerabilities.",
),
pytest.param(
"jinja2_templating.py",
10,
"S701 Using jinja2 templates with autoescape=False is dangerous and can lead to XSS. Use autoescape=True or use the select_autoescape function to mitigate XSS vulnerabilities.",
),
pytest.param(
"jinja2_templating.py",
11,
"S701 Using jinja2 templates with autoescape=False is dangerous and can lead to XSS. Use autoescape=True or use the select_autoescape function to mitigate XSS vulnerabilities.",
),
pytest.param(
"jinja2_templating.py",
15,
"S701 By default, jinja2 sets autoescape to False. Consider using autoescape=True or use the select_autoescape function to mitigate XSS vulnerabilities.",
),
pytest.param(
"jinja2_templating.py",
26,
"S701 Using jinja2 templates with autoescape=False is dangerous and can lead to XSS. Ensure autoescape=True or use the select_autoescape function to mitigate XSS vulnerabilities.",
),
pytest.param(
"mako_templating.py",
6,
"S702 Mako templates allow HTML/JS rendering by default and are inherently open to XSS attacks. Ensure variables in all templates are properly sanitized via the 'n', 'h' or 'x' flags (depending on context). For example, to HTML escape the variable 'data' do ${ data |h }.",
),
pytest.param(
"mako_templating.py",
10,
"S702 Mako templates allow HTML/JS rendering by default and are inherently open to XSS attacks. Ensure variables in all templates are properly sanitized via the 'n', 'h' or 'x' flags (depending on context). For example, to HTML escape the variable 'data' do ${ data |h }.",
),
pytest.param(
"mako_templating.py",
11,
"S702 Mako templates allow HTML/JS rendering by default and are inherently open to XSS attacks. Ensure variables in all templates are properly sanitized via the 'n', 'h' or 'x' flags (depending on context). For example, to HTML escape the variable 'data' do ${ data |h }.",
),
pytest.param(
"mark_safe_insecure.py", 10, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
10,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 11, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py", 12, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py", 13, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py", 14, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py", 22, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
22,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 30, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
30,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py",
35,
"S311 Standard pseudo-random generators are not suitable for security/cryptographic purposes.",
),
pytest.param(
"mark_safe_insecure.py", 41, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
41,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py",
46,
"S311 Standard pseudo-random generators are not suitable for security/cryptographic purposes.",
),
pytest.param(
"mark_safe_insecure.py", 54, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
54,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 59, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
59,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 64, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
64,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 69, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
69,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 74, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
74,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 79, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
79,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 84, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
84,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 89, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
89,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 94, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
94,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 99, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
99,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 104, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
104,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 109, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
109,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 114, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
114,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 119, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
119,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py",
124,
"S311 Standard pseudo-random generators are not suitable for security/cryptographic purposes.",
),
pytest.param(
"mark_safe_insecure.py", 126, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
126,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 133, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
133,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 143, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
143,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 149, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
149,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 153, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
153,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_insecure.py", 159, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_insecure.py",
159,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe.py",
4,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
4,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
11,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
14,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
17,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
29,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
33,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
35,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
36,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
37,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py", 38, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_secure.py",
38,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py", 39, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_secure.py",
39,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
41,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
45,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
47,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
48,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py", 49, "S703 Potential XSS on mark_safe function."
),
pytest.param(
"mark_safe_secure.py",
49,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
54,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
62,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
65,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"mark_safe_secure.py",
75,
"S308 Use of mark_safe() may expose cross-site scripting vulnerabilities and should be reviewed.",
),
pytest.param(
"marshal_deserialize.py",
6,
"S302 Deserialization with the marshal module is possibly dangerous.",
),
pytest.param(
"marshal_deserialize.py",
11,
"S302 Deserialization with the marshal module is possibly dangerous.",
),
pytest.param(
"mktemp.py", 7, "S306 Use of insecure and deprecated function (mktemp)."
),
pytest.param(
"mktemp.py", 8, "S306 Use of insecure and deprecated function (mktemp)."
),
pytest.param(
"mktemp.py", 9, "S306 Use of insecure and deprecated function (mktemp)."
),
pytest.param(
"mktemp.py", 10, "S306 Use of insecure and deprecated function (mktemp)."
),
pytest.param(
"multiline_statement.py",
1,
"S404 Consider possible security implications associated with subprocess module.",
),
pytest.param(
"multiline_statement.py",
5,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"new_candidates-all.py",
7,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"new_candidates-all.py",
9,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"new_candidates-all.py",
15,
"S506 Use of unsafe yaml load. Allows instantiation of arbitrary objects. Consider yaml.safe_load().",
),
pytest.param(
"new_candidates-all.py",
17,
"S506 Use of unsafe yaml load. Allows instantiation of arbitrary objects. Consider yaml.safe_load().",
),
pytest.param(
"new_candidates-all.py",
22,
"S317 Using xml.sax.make_parser to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.make_parser with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"new_candidates-all.py",
24,
"S317 Using xml.sax.make_parser to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.make_parser with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"new_candidates-nosec.py",
7,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"new_candidates-nosec.py",
13,
"S506 Use of unsafe yaml load. Allows instantiation of arbitrary objects. Consider yaml.safe_load().",
),
pytest.param(
"new_candidates-nosec.py",
18,
"S317 Using xml.sax.make_parser to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.make_parser with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"new_candidates-some.py",
7,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"new_candidates-some.py",
9,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"new_candidates-some.py",
15,
"S506 Use of unsafe yaml load. Allows instantiation of arbitrary objects. Consider yaml.safe_load().",
),
pytest.param(
"new_candidates-some.py",
20,
"S317 Using xml.sax.make_parser to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.make_parser with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"no_host_key_verification.py",
4,
"S507 Paramiko call with policy set to automatically trust the unknown host key.",
),
pytest.param(
"no_host_key_verification.py",
5,
"S507 Paramiko call with policy set to automatically trust the unknown host key.",
),
pytest.param(
"os-chmod-py3.py",
6,
"S103 Chmod setting a permissive mask 0o227 on file (/etc/passwd).",
),
pytest.param(
"os-chmod-py3.py",
7,
"S103 Chmod setting a permissive mask 0o7 on file (/etc/passwd).",
),
pytest.param(
"os-chmod-py3.py",
9,
"S103 Chmod setting a permissive mask 0o777 on file (/etc/passwd).",
),
pytest.param(
"os-chmod-py3.py",
10,
"S103 Chmod setting a permissive mask 0o770 on file (/etc/passwd).",
),
pytest.param(
"os-chmod-py3.py",
11,
"S103 Chmod setting a permissive mask 0o776 on file (/etc/passwd).",
),
pytest.param(
"os-chmod-py3.py",
13,
"S103 Chmod setting a permissive mask 0o777 on file (~/.bashrc).",
),
pytest.param(
"os-chmod-py3.py",
14,
"S103 Chmod setting a permissive mask 0o777 on file (/etc/hosts).",
),
pytest.param(
"os-chmod-py3.py",
15,
"S103 Chmod setting a permissive mask 0o777 on file (/tmp/oh_hai).",
),
pytest.param(
"os-chmod-py3.py",
15,
"S108 Probable insecure usage of temp file/directory.",
),
pytest.param(
"os-chmod-py3.py",
17,
"S103 Chmod setting a permissive mask 0o777 on file (key_file).",
),
pytest.param("os-exec.py", 3, "S606 Starting a process without a shell."),
pytest.param("os-exec.py", 4, "S606 Starting a process without a shell."),
pytest.param("os-exec.py", 5, "S606 Starting a process without a shell."),
pytest.param("os-exec.py", 6, "S606 Starting a process without a shell."),
pytest.param("os-exec.py", 7, "S606 Starting a process without a shell."),
pytest.param("os-exec.py", 8, "S606 Starting a process without a shell."),
pytest.param("os-exec.py", 9, "S606 Starting a process without a shell."),
pytest.param("os-exec.py", 10, "S606 Starting a process without a shell."),
pytest.param(
"os-popen.py",
6,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"os-popen.py",
7,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"os-popen.py",
8,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"os-popen.py",
9,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"os-popen.py",
10,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"os-popen.py",
11,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"os-popen.py",
12,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"os-popen.py",
14,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"os-popen.py",
15,
"S605 Starting a process with a shell, possible injection detected, security issue.",
),
pytest.param("os-spawn.py", 3, "S606 Starting a process without a shell."),
pytest.param("os-spawn.py", 4, "S606 Starting a process without a shell."),
pytest.param("os-spawn.py", 5, "S606 Starting a process without a shell."),
pytest.param("os-spawn.py", 6, "S606 Starting a process without a shell."),
pytest.param("os-spawn.py", 7, "S606 Starting a process without a shell."),
pytest.param("os-spawn.py", 8, "S606 Starting a process without a shell."),
pytest.param("os-spawn.py", 9, "S606 Starting a process without a shell."),
pytest.param("os-spawn.py", 10, "S606 Starting a process without a shell."),
pytest.param("os-startfile.py", 3, "S606 Starting a process without a shell."),
pytest.param("os-startfile.py", 4, "S606 Starting a process without a shell."),
pytest.param("os-startfile.py", 5, "S606 Starting a process without a shell."),
pytest.param(
"os_system.py",
3,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"paramiko_injection.py",
7,
"S601 Possible shell injection via Paramiko call, check inputs are properly sanitized.",
),
pytest.param(
"pickle_deserialize.py",
1,
"S403 Consider possible security implications associated with cPickle module.",
),
pytest.param(
"pickle_deserialize.py",
2,
"S403 Consider possible security implications associated with pickle module.",
),
pytest.param(
"pickle_deserialize.py",
8,
"S301 Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.",
),
pytest.param(
"pickle_deserialize.py",
13,
"S301 Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.",
),
pytest.param(
"pickle_deserialize.py",
16,
"S301 Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.",
),
pytest.param(
"pickle_deserialize.py",
20,
"S301 Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.",
),
pytest.param(
"pickle_deserialize.py",
25,
"S301 Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.",
),
pytest.param(
"pickle_deserialize.py",
28,
"S301 Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.",
),
pytest.param(
"popen_wrappers.py",
5,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"popen_wrappers.py",
6,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"popen_wrappers.py",
11,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"popen_wrappers.py",
12,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"popen_wrappers.py",
13,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"popen_wrappers.py",
14,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"popen_wrappers.py",
15,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"pycrypto.py",
1,
"S413 The pyCrypto library and its module AES are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"pycrypto.py",
2,
"S413 The pyCrypto library and its module Random are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"random_module.py",
5,
"S311 Standard pseudo-random generators are not suitable for security/cryptographic purposes.",
),
pytest.param(
"random_module.py",
6,
"S311 Standard pseudo-random generators are not suitable for security/cryptographic purposes.",
),
pytest.param(
"random_module.py",
7,
"S311 Standard pseudo-random generators are not suitable for security/cryptographic purposes.",
),
pytest.param(
"random_module.py",
8,
"S311 Standard pseudo-random generators are not suitable for security/cryptographic purposes.",
),
pytest.param(
"random_module.py",
9,
"S311 Standard pseudo-random generators are not suitable for security/cryptographic purposes.",
),
pytest.param(
"random_module.py",
10,
"S311 Standard pseudo-random generators are not suitable for security/cryptographic purposes.",
),
pytest.param(
"requests-ssl-verify-disabled.py",
4,
"S501 Requests call with verify=False disabling SSL certificate checks, security issue.",
),
pytest.param(
"requests-ssl-verify-disabled.py",
6,
"S501 Requests call with verify=False disabling SSL certificate checks, security issue.",
),
pytest.param(
"requests-ssl-verify-disabled.py",
8,
"S501 Requests call with verify=False disabling SSL certificate checks, security issue.",
),
pytest.param(
"requests-ssl-verify-disabled.py",
10,
"S501 Requests call with verify=False disabling SSL certificate checks, security issue.",
),
pytest.param(
"requests-ssl-verify-disabled.py",
12,
"S501 Requests call with verify=False disabling SSL certificate checks, security issue.",
),
pytest.param(
"requests-ssl-verify-disabled.py",
14,
"S501 Requests call with verify=False disabling SSL certificate checks, security issue.",
),
pytest.param(
"requests-ssl-verify-disabled.py",
16,
"S501 Requests call with verify=False disabling SSL certificate checks, security issue.",
),
pytest.param(
"skip.py",
1,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"skip.py",
2,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"skip.py",
3,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"skip.py",
4,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"skip.py",
5,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"skip.py",
6,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"skip.py",
7,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"sql_statements.py",
4,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
5,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
6,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
7,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
9,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
11,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
12,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
15,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
16,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
17,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
18,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
20,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
21,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"sql_statements.py",
35,
"S608 Possible SQL injection vector through string-based query construction.",
),
pytest.param(
"ssl-insecure-version.py",
4,
"S502 ssl.wrap_socket call with insecure SSL/TLS protocol version identified, security issue.",
),
pytest.param(
"ssl-insecure-version.py",
5,
"S502 SSL.Context call with insecure SSL/TLS protocol version identified, security issue.",
),
pytest.param(
"ssl-insecure-version.py",
6,
"S502 SSL.Context call with insecure SSL/TLS protocol version identified, security issue.",
),
pytest.param(
"ssl-insecure-version.py",
8,
"S502 Function call with insecure SSL/TLS protocol identified, possible security issue.",
),
pytest.param(
"ssl-insecure-version.py",
9,
"S502 Function call with insecure SSL/TLS protocol identified, possible security issue.",
),
pytest.param(
"ssl-insecure-version.py",
10,
"S502 Function call with insecure SSL/TLS protocol identified, possible security issue.",
),
pytest.param(
"ssl-insecure-version.py",
13,
"S502 ssl.wrap_socket call with insecure SSL/TLS protocol version identified, security issue.",
),
pytest.param(
"ssl-insecure-version.py",
14,
"S502 ssl.wrap_socket call with insecure SSL/TLS protocol version identified, security issue.",
),
pytest.param(
"ssl-insecure-version.py",
15,
"S502 SSL.Context call with insecure SSL/TLS protocol version identified, security issue.",
),
pytest.param(
"ssl-insecure-version.py",
16,
"S502 SSL.Context call with insecure SSL/TLS protocol version identified, security issue.",
),
pytest.param(
"ssl-insecure-version.py",
18,
"S502 Function call with insecure SSL/TLS protocol identified, possible security issue.",
),
pytest.param(
"ssl-insecure-version.py",
19,
"S502 Function call with insecure SSL/TLS protocol identified, possible security issue.",
),
pytest.param(
"ssl-insecure-version.py",
20,
"S502 Function call with insecure SSL/TLS protocol identified, possible security issue.",
),
pytest.param(
"ssl-insecure-version.py",
21,
"S502 Function call with insecure SSL/TLS protocol identified, possible security issue.",
),
pytest.param(
"ssl-insecure-version.py",
23,
"S504 ssl.wrap_socket call with no SSL/TLS protocol version specified, the default SSLv23 could be insecure, possible security issue.",
),
pytest.param(
"ssl-insecure-version.py",
25,
"S503 Function definition identified with insecure SSL/TLS protocol version by default, possible security issue.",
),
pytest.param(
"ssl-insecure-version.py",
28,
"S503 Function definition identified with insecure SSL/TLS protocol version by default, possible security issue.",
),
pytest.param(
"ssl-insecure-version.py",
31,
"S503 Function definition identified with insecure SSL/TLS protocol version by default, possible security issue.",
),
pytest.param(
"subprocess_shell.py",
1,
"S404 Consider possible security implications associated with subprocess module.",
),
pytest.param(
"subprocess_shell.py",
2,
"S404 Consider possible security implications associated with Popen module.",
),
pytest.param(
"subprocess_shell.py",
11,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"subprocess_shell.py",
12,
"S604 Function call with shell=True parameter identified, possible security issue.",
),
pytest.param(
"subprocess_shell.py",
14,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"subprocess_shell.py",
15,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"subprocess_shell.py",
16,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"subprocess_shell.py",
18,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"subprocess_shell.py",
21,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"subprocess_shell.py",
23,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"subprocess_shell.py",
24,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"subprocess_shell.py",
26,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"subprocess_shell.py",
27,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"subprocess_shell.py",
29,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"subprocess_shell.py",
30,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"subprocess_shell.py",
32,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"subprocess_shell.py",
33,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
34,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
37,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
39,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"subprocess_shell.py",
42,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
43,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
44,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
45,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
47,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
48,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
49,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
50,
"S602 subprocess call with shell=True identified, security issue.",
),
pytest.param(
"subprocess_shell.py",
52,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"subprocess_shell.py",
53,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"subprocess_shell.py",
54,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"subprocess_shell.py",
55,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"subprocess_shell.py",
56,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"telnetlib.py",
1,
"S401 A telnet-related module is being imported. Telnet is considered insecure. Use SSH or some other encrypted protocol.",
),
pytest.param(
"telnetlib.py",
8,
"S312 Telnet-related functions are being called. Telnet is considered insecure. Use SSH or some other encrypted protocol.",
),
pytest.param(
"tempnam.py",
5,
"S325 Use of os.tempnam() and os.tmpnam() is vulnerable to symlink attacks. Consider using tmpfile() instead.",
),
pytest.param(
"tempnam.py",
7,
"S325 Use of os.tempnam() and os.tmpnam() is vulnerable to symlink attacks. Consider using tmpfile() instead.",
),
pytest.param(
"tempnam.py",
9,
"S325 Use of os.tempnam() and os.tmpnam() is vulnerable to symlink attacks. Consider using tmpfile() instead.",
),
pytest.param(
"tempnam.py",
10,
"S325 Use of os.tempnam() and os.tmpnam() is vulnerable to symlink attacks. Consider using tmpfile() instead.",
),
pytest.param(
"tempnam.py",
12,
"S325 Use of os.tempnam() and os.tmpnam() is vulnerable to symlink attacks. Consider using tmpfile() instead.",
),
pytest.param(
"tempnam.py",
13,
"S325 Use of os.tempnam() and os.tmpnam() is vulnerable to symlink attacks. Consider using tmpfile() instead.",
),
pytest.param(
"try_except_continue.py", 5, "S112 Try, Except, Continue detected."
),
pytest.param(
"try_except_continue.py", 13, "S112 Try, Except, Continue detected."
),
pytest.param("try_except_pass.py", 4, "S110 Try, Except, Pass detected."),
pytest.param("try_except_pass.py", 11, "S110 Try, Except, Pass detected."),
pytest.param(
"unverified_context.py",
7,
"S323 By default, Python will create a secure, verified ssl context for use in such classes as HTTPSConnection. However, it still allows using an insecure context via the _create_unverified_context that reverts to the previous behavior that does not validate certificates or perform hostname checks.",
),
pytest.param(
"urlopen.py",
22,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
23,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
24,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
27,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
38,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
39,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
42,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
43,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
44,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
47,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
52,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
53,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
54,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"urlopen.py",
57,
"S310 Audit url open for permitted schemes. Allowing use of file:/ or custom schemes is often unexpected.",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
5,
"S413 The pyCrypto library and its module DSA are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
6,
"S413 The pyCrypto library and its module RSA are no longer actively maintained and have been deprecated. Consider using pyca/cryptography library.",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
38,
"S505 DSA key sizes below 2048 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
40,
"S505 EC key sizes below 224 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
42,
"S505 RSA key sizes below 2048 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
45,
"S505 DSA key sizes below 2048 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
46,
"S505 RSA key sizes below 2048 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
47,
"S505 DSA key sizes below 2048 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
48,
"S505 RSA key sizes below 2048 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
51,
"S505 DSA key sizes below 1024 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
53,
"S505 EC key sizes below 224 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
55,
"S505 RSA key sizes below 1024 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
58,
"S505 DSA key sizes below 1024 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
59,
"S505 RSA key sizes below 1024 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
60,
"S505 DSA key sizes below 1024 bits are considered breakable. ",
),
pytest.param(
"weak_cryptographic_key_sizes.py",
61,
"S505 RSA key sizes below 1024 bits are considered breakable. ",
),
pytest.param(
"wildcard-injection.py",
2,
"S404 Consider possible security implications associated with subprocess module.",
),
pytest.param(
"wildcard-injection.py",
5,
"S609 Possible wildcard injection in call: os.system",
),
pytest.param(
"wildcard-injection.py",
5,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"wildcard-injection.py",
6,
"S609 Possible wildcard injection in call: os.system",
),
pytest.param(
"wildcard-injection.py",
6,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"wildcard-injection.py",
7,
"S609 Possible wildcard injection in call: os.popen2",
),
pytest.param(
"wildcard-injection.py",
7,
"S605 Starting a process with a shell: Seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"wildcard-injection.py",
8,
"S609 Possible wildcard injection in call: subprocess.Popen",
),
pytest.param(
"wildcard-injection.py",
8,
"S602 subprocess call with shell=True seems safe, but may be changed in the future, consider rewriting without shell",
),
pytest.param(
"wildcard-injection.py",
11,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"wildcard-injection.py",
12,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"wildcard-injection.py",
13,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"wildcard-injection.py",
14,
"S603 subprocess call - check for execution of untrusted input.",
),
pytest.param(
"wildcard-injection.py", 16, "S606 Starting a process without a shell."
),
pytest.param(
"xml_etree_celementtree.py",
1,
"S405 Using xml.etree.cElementTree to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.cElementTree with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.",
),
pytest.param(
"xml_etree_celementtree.py",
7,
"S313 Using xml.etree.cElementTree.fromstring to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.cElementTree.fromstring with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_etree_celementtree.py",
9,
"S313 Using xml.etree.cElementTree.parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.cElementTree.parse with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_etree_celementtree.py",
10,
"S313 Using xml.etree.cElementTree.iterparse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.cElementTree.iterparse with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_etree_celementtree.py",
11,
"S313 Using xml.etree.cElementTree.XMLParser to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.cElementTree.XMLParser with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_etree_elementtree.py",
1,
"S405 Using xml.etree.ElementTree to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.ElementTree with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.",
),
pytest.param(
"xml_etree_elementtree.py",
7,
"S314 Using xml.etree.ElementTree.fromstring to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.ElementTree.fromstring with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_etree_elementtree.py",
9,
"S314 Using xml.etree.ElementTree.parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.ElementTree.parse with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_etree_elementtree.py",
10,
"S314 Using xml.etree.ElementTree.iterparse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.ElementTree.iterparse with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_etree_elementtree.py",
11,
"S314 Using xml.etree.ElementTree.XMLParser to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.etree.ElementTree.XMLParser with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_expatbuilder.py",
1,
"S407 Using xml.dom.expatbuilder to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.dom.expatbuilder with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.",
),
pytest.param(
"xml_expatbuilder.py",
4,
"S316 Using xml.dom.expatbuilder.parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.dom.expatbuilder.parse with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_expatbuilder.py",
9,
"S316 Using xml.dom.expatbuilder.parseString to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.dom.expatbuilder.parseString with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_expatreader.py",
1,
"S406 Using xml.sax.expatreader to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.expatreader with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.",
),
pytest.param(
"xml_expatreader.py",
4,
"S315 Using xml.sax.expatreader.create_parser to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.expatreader.create_parser with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_lxml.py",
1,
"S410 Using lxml.etree to parse untrusted XML data is known to be vulnerable to XML attacks. Replace lxml.etree with the equivalent defusedxml package.",
),
pytest.param(
"xml_lxml.py",
2,
"S410 Using lxml to parse untrusted XML data is known to be vulnerable to XML attacks. Replace lxml with the equivalent defusedxml package.",
),
pytest.param(
"xml_lxml.py",
3,
"S410 Using etree to parse untrusted XML data is known to be vulnerable to XML attacks. Replace etree with the equivalent defusedxml package.",
),
pytest.param(
"xml_lxml.py",
8,
"S320 Using lxml.etree.fromstring to parse untrusted XML data is known to be vulnerable to XML attacks. Replace lxml.etree.fromstring with its defusedxml equivalent function.",
),
pytest.param(
"xml_minidom.py",
1,
"S408 Using parseString to parse untrusted XML data is known to be vulnerable to XML attacks. Replace parseString with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.",
),
pytest.param(
"xml_minidom.py",
3,
"S318 Using xml.dom.minidom.parseString to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.dom.minidom.parseString with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_minidom.py",
9,
"S408 Using parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace parse with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.",
),
pytest.param(
"xml_minidom.py",
11,
"S318 Using xml.dom.minidom.parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.dom.minidom.parse with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_pulldom.py",
1,
"S409 Using parseString to parse untrusted XML data is known to be vulnerable to XML attacks. Replace parseString with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.",
),
pytest.param(
"xml_pulldom.py",
3,
"S319 Using xml.dom.pulldom.parseString to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.dom.pulldom.parseString with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_pulldom.py",
9,
"S409 Using parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace parse with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.",
),
pytest.param(
"xml_pulldom.py",
11,
"S319 Using xml.dom.pulldom.parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.dom.pulldom.parse with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_sax.py",
1,
"S406 Using xml.sax to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.",
),
pytest.param(
"xml_sax.py",
2,
"S406 Using sax to parse untrusted XML data is known to be vulnerable to XML attacks. Replace sax with the equivalent defusedxml package, or make sure defusedxml.defuse_stdlib() is called.",
),
pytest.param(
"xml_sax.py",
21,
"S317 Using xml.sax.parseString to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.parseString with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_sax.py",
22,
"S317 Using xml.sax.parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.parse with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_sax.py",
23,
"S317 Using xml.sax.parseString to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.parseString with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_sax.py",
24,
"S317 Using xml.sax.parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.parse with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_sax.py",
30,
"S317 Using xml.sax.make_parser to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.make_parser with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_sax.py",
31,
"S317 Using xml.sax.make_parser to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.make_parser with its defusedxml equivalent function or make sure defusedxml.defuse_stdlib() is called",
),
pytest.param(
"xml_xmlrpc.py",
1,
"S411 Using xmlrpclib to parse untrusted XML data is known to be vulnerable to XML attacks. Use defused.xmlrpc.monkey_patch() function to monkey-patch xmlrpclib and mitigate XML vulnerabilities.",
),
pytest.param(
"yaml_load.py",
7,
"S506 Use of unsafe yaml load. Allows instantiation of arbitrary objects. Consider yaml.safe_load().",
),
],
)
def test_outputs(filename, line, message):
errors = _get_errors(filename)
idxes = []
for idx, error in enumerate(errors):
# Some lines have multiple errors and
# we need to check both
if error[0] == line:
idxes.append(idx)
# Assume failing tests for multiple lines
_pass = False
for idx in idxes:
if errors[idx][2] != message:
continue
# We found a matching message in the
# index list
_pass = True
assert errors[idx][0] == line
assert errors[idx][1] == 0
assert errors[idx][2] == message
if not _pass:
print(errors[idx])
print(idxes)
assert _pass | 0.772874 | 0.61202 |
# pylint: disable=protected-access
import logging
import os
import pathlib
import subprocess
from contextlib import contextmanager
from shutil import rmtree
from typing import Any, Iterator, List, Type, Union
import pytest
from _pytest.monkeypatch import MonkeyPatch
from flaky import flaky
from packaging.version import Version
from pytest_mock import MockerFixture
from ansible_compat.constants import INVALID_PREREQUISITES_RC
from ansible_compat.errors import (
AnsibleCommandError,
AnsibleCompatError,
InvalidPrerequisiteError,
)
from ansible_compat.runtime import CompletedProcess, Runtime
def test_runtime_version(runtime: Runtime) -> None:
"""Tests version property."""
version = runtime.version
assert isinstance(version, Version)
# tests that caching property value worked (coverage)
assert version == runtime.version
@pytest.mark.parametrize(
"require_module",
(True, False),
ids=("module-required", "module-unrequired"),
)
def test_runtime_version_outdated(require_module: bool) -> None:
"""Checks that instantiation raises if version is outdated."""
with pytest.raises(RuntimeError, match="Found incompatible version of ansible"):
Runtime(min_required_version="9999.9.9", require_module=require_module)
def test_runtime_missing_ansible_module(monkeypatch: MonkeyPatch) -> None:
"""Checks that we produce a RuntimeError when ansible module is missing."""
class RaiseException:
"""Class to raise an exception."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
raise ModuleNotFoundError()
monkeypatch.setattr("importlib.import_module", RaiseException)
with pytest.raises(RuntimeError, match="Unable to find Ansible python module."):
Runtime(require_module=True)
def test_runtime_mismatch_ansible_module(monkeypatch: MonkeyPatch) -> None:
"""Test that missing module is detected."""
monkeypatch.setattr("ansible.release.__version__", "0.0.0", raising=False)
with pytest.raises(RuntimeError, match="versions do not match"):
Runtime(require_module=True)
def test_runtime_require_module() -> None:
"""Check that require_module successful pass."""
Runtime(require_module=True)
def test_runtime_version_fail_module(mocker: MockerFixture) -> None:
"""Tests for failure to detect Ansible version."""
patched = mocker.patch(
"ansible_compat.runtime.parse_ansible_version",
autospec=True,
)
patched.side_effect = InvalidPrerequisiteError(
"Unable to parse ansible cli version"
)
runtime = Runtime()
with pytest.raises(
InvalidPrerequisiteError, match="Unable to parse ansible cli version"
):
runtime.version # pylint: disable=pointless-statement
def test_runtime_version_fail_cli(mocker: MockerFixture) -> None:
"""Tests for failure to detect Ansible version."""
mocker.patch(
"ansible_compat.runtime.Runtime.exec",
return_value=CompletedProcess(
["x"], returncode=123, stdout="oops", stderr="some error"
),
autospec=True,
)
runtime = Runtime()
with pytest.raises(
RuntimeError, match="Unable to find a working copy of ansible executable."
):
runtime.version # pylint: disable=pointless-statement
def test_runtime_prepare_ansible_paths_validation() -> None:
"""Check that we validate collection_path."""
runtime = Runtime()
runtime.config.collections_paths = "invalid-value" # type: ignore
with pytest.raises(RuntimeError, match="Unexpected ansible configuration"):
runtime._prepare_ansible_paths()
@pytest.mark.parametrize(
("folder", "role_name", "isolated"),
(
("ansible-role-sample", "acme.sample", True),
("acme.sample2", "acme.sample2", True),
("sample3", "acme.sample3", True),
("sample4", "acme.sample4", False),
),
ids=("1", "2", "3", "4"),
)
def test_runtime_install_role(
caplog: pytest.LogCaptureFixture,
folder: str,
role_name: str,
isolated: bool,
) -> None:
"""Checks that we can install roles."""
caplog.set_level(logging.INFO)
project_dir = os.path.join(os.path.dirname(__file__), "roles", folder)
runtime = Runtime(isolated=isolated, project_dir=project_dir)
runtime.prepare_environment(install_local=True)
# check that role appears as installed now
result = runtime.exec(["ansible-galaxy", "list"])
assert result.returncode == 0, result
assert role_name in result.stdout
runtime.clean()
# also test that clean does not break when cache_dir is missing
tmp_dir = runtime.cache_dir
runtime.cache_dir = None
runtime.clean()
runtime.cache_dir = tmp_dir
def test_prepare_environment_with_collections(tmp_path: pathlib.Path) -> None:
"""Check that collections are correctly installed."""
runtime = Runtime(isolated=True, project_dir=str(tmp_path))
runtime.prepare_environment(required_collections={"community.molecule": "0.1.0"})
def test_runtime_install_requirements_missing_file() -> None:
"""Check that missing requirements file is ignored."""
# Do not rely on this behavior, it may be removed in the future
runtime = Runtime()
runtime.install_requirements("/that/does/not/exist")
@pytest.mark.parametrize(
("file", "exc", "msg"),
(
(
"/dev/null",
InvalidPrerequisiteError,
"file is not a valid Ansible requirements file",
),
(
os.path.join(
os.path.dirname(__file__),
"assets",
"requirements-invalid-collection.yml",
),
AnsibleCommandError,
"Got 1 exit code while running: ansible-galaxy",
),
(
os.path.join(
os.path.dirname(__file__),
"assets",
"requirements-invalid-role.yml",
),
AnsibleCommandError,
"Got 1 exit code while running: ansible-galaxy",
),
),
ids=("empty", "invalid-collection", "invalid-role"),
)
def test_runtime_install_requirements_invalid_file(
file: str, exc: Type[Any], msg: str
) -> None:
"""Check that invalid requirements file is raising."""
runtime = Runtime()
with pytest.raises(
exc,
match=msg,
):
runtime.install_requirements(file)
@contextmanager
def remember_cwd(cwd: str) -> Iterator[None]:
"""Context manager for chdir."""
curdir = os.getcwd()
try:
os.chdir(cwd)
yield
finally:
os.chdir(curdir)
# # https://github.com/box/flaky/issues/170
@flaky(max_runs=3) # type: ignore
def test_prerun_reqs_v1(caplog: pytest.LogCaptureFixture, runtime: Runtime) -> None:
"""Checks that the linter can auto-install requirements v1 when found."""
cwd = os.path.realpath(
os.path.join(
os.path.dirname(os.path.realpath(__file__)), "..", "examples", "reqs_v1"
)
)
with remember_cwd(cwd):
with caplog.at_level(logging.INFO):
runtime.prepare_environment()
assert any(
msg.startswith("Running ansible-galaxy role install") for msg in caplog.messages
)
assert all(
"Running ansible-galaxy collection install" not in msg
for msg in caplog.messages
)
@flaky(max_runs=3) # type: ignore
def test_prerun_reqs_v2(caplog: pytest.LogCaptureFixture, runtime: Runtime) -> None:
"""Checks that the linter can auto-install requirements v2 when found."""
cwd = os.path.realpath(
os.path.join(
os.path.dirname(os.path.realpath(__file__)), "..", "examples", "reqs_v2"
)
)
with remember_cwd(cwd):
with caplog.at_level(logging.INFO):
runtime.prepare_environment()
assert any(
msg.startswith("Running ansible-galaxy role install")
for msg in caplog.messages
)
assert any(
msg.startswith("Running ansible-galaxy collection install")
for msg in caplog.messages
)
def test__update_env_no_old_value_no_default_no_value(monkeypatch: MonkeyPatch) -> None:
"""Make sure empty value does not touch environment."""
monkeypatch.delenv("DUMMY_VAR", raising=False)
runtime = Runtime()
runtime._update_env("DUMMY_VAR", [])
assert "DUMMY_VAR" not in runtime.environ
def test__update_env_no_old_value_no_value(monkeypatch: MonkeyPatch) -> None:
"""Make sure empty value does not touch environment."""
monkeypatch.delenv("DUMMY_VAR", raising=False)
runtime = Runtime()
runtime._update_env("DUMMY_VAR", [], "a:b")
assert "DUMMY_VAR" not in runtime.environ
def test__update_env_no_default_no_value(monkeypatch: MonkeyPatch) -> None:
"""Make sure empty value does not touch environment."""
monkeypatch.setenv("DUMMY_VAR", "a:b")
runtime = Runtime()
runtime._update_env("DUMMY_VAR", [])
assert runtime.environ["DUMMY_VAR"] == "a:b"
@pytest.mark.parametrize(
("value", "result"),
(
(["a"], "a"),
(["a", "b"], "a:b"),
(["a", "b", "c"], "a:b:c"),
),
)
def test__update_env_no_old_value_no_default(
monkeypatch: MonkeyPatch, value: List[str], result: str
) -> None:
"""Values are concatenated using : as the separator."""
monkeypatch.delenv("DUMMY_VAR", raising=False)
runtime = Runtime()
runtime._update_env("DUMMY_VAR", value)
assert runtime.environ["DUMMY_VAR"] == result
@pytest.mark.parametrize(
("default", "value", "result"),
(
("a:b", ["c"], "c:a:b"),
("a:b", ["c:d"], "c:d:a:b"),
),
)
def test__update_env_no_old_value(
monkeypatch: MonkeyPatch, default: str, value: List[str], result: str
) -> None:
"""Values are appended to default value."""
monkeypatch.delenv("DUMMY_VAR", raising=False)
runtime = Runtime()
runtime._update_env("DUMMY_VAR", value, default)
assert runtime.environ["DUMMY_VAR"] == result
@pytest.mark.parametrize(
("old_value", "value", "result"),
(
("a:b", ["c"], "c:a:b"),
("a:b", ["c:d"], "c:d:a:b"),
),
)
def test__update_env_no_default(
monkeypatch: MonkeyPatch, old_value: str, value: List[str], result: str
) -> None:
"""Values are appended to preexisting value."""
monkeypatch.setenv("DUMMY_VAR", old_value)
runtime = Runtime()
runtime._update_env("DUMMY_VAR", value)
assert runtime.environ["DUMMY_VAR"] == result
@pytest.mark.parametrize(
("old_value", "default", "value", "result"),
(
("", "", ["e"], "e"),
("a", "", ["e"], "e:a"),
("", "c", ["e"], "e"),
("a", "c", ["e:f"], "e:f:a"),
),
)
def test__update_env(
monkeypatch: MonkeyPatch,
old_value: str,
default: str, # pylint: disable=unused-argument
value: List[str],
result: str,
) -> None:
"""Defaults are ignored when preexisting value is present."""
monkeypatch.setenv("DUMMY_VAR", old_value)
runtime = Runtime()
runtime._update_env("DUMMY_VAR", value)
assert runtime.environ["DUMMY_VAR"] == result
def test_require_collection_wrong_version(runtime: Runtime) -> None:
"""Tests behaviour of require_collection."""
subprocess.check_output(
[
"ansible-galaxy",
"collection",
"install",
"containers.podman",
"-p",
"~/.ansible/collections",
]
)
with pytest.raises(InvalidPrerequisiteError) as pytest_wrapped_e:
runtime.require_collection("containers.podman", "9999.9.9")
assert pytest_wrapped_e.type == InvalidPrerequisiteError
assert pytest_wrapped_e.value.code == INVALID_PREREQUISITES_RC
def test_require_collection_invalid_name(runtime: Runtime) -> None:
"""Check that require_collection raise with invalid collection name."""
with pytest.raises(
InvalidPrerequisiteError, match="Invalid collection name supplied:"
):
runtime.require_collection("that-is-invalid")
def test_require_collection_invalid_collections_path(runtime: Runtime) -> None:
"""Check that require_collection raise with invalid collections path."""
runtime.config.collections_paths = "/that/is/invalid" # type: ignore
with pytest.raises(
InvalidPrerequisiteError, match="Unable to determine ansible collection paths"
):
runtime.require_collection("community.molecule")
def test_require_collection_preexisting_broken(tmp_path: pathlib.Path) -> None:
"""Check that require_collection raise with broken pre-existing collection."""
runtime = Runtime(isolated=True, project_dir=str(tmp_path))
dest_path: str = runtime.config.collections_paths[0]
dest = os.path.join(dest_path, "ansible_collections", "foo", "bar")
os.makedirs(dest, exist_ok=True)
with pytest.raises(InvalidPrerequisiteError, match="missing MANIFEST.json"):
runtime.require_collection("foo.bar")
def test_require_collection(runtime_tmp: Runtime) -> None:
"""Check that require collection successful install case."""
runtime_tmp.require_collection("community.molecule", "0.1.0")
@pytest.mark.parametrize(
("name", "version", "install"),
(
("fake_namespace.fake_name", None, True),
("fake_namespace.fake_name", "9999.9.9", True),
("fake_namespace.fake_name", None, False),
),
ids=("a", "b", "c"),
)
def test_require_collection_missing(
name: str, version: str, install: bool, runtime: Runtime
) -> None:
"""Tests behaviour of require_collection, missing case."""
with pytest.raises(AnsibleCompatError) as pytest_wrapped_e:
runtime.require_collection(name=name, version=version, install=install)
assert pytest_wrapped_e.type == InvalidPrerequisiteError
assert pytest_wrapped_e.value.code == INVALID_PREREQUISITES_RC
def test_install_collection(runtime: Runtime) -> None:
"""Check that valid collection installs do not fail."""
runtime.install_collection("containers.podman:>=1.0")
def test_install_collection_dest(runtime: Runtime, tmp_path: pathlib.Path) -> None:
"""Check that valid collection to custom destination passes."""
runtime.install_collection("containers.podman:>=1.0", destination=tmp_path)
expected_file = (
tmp_path / "ansible_collections" / "containers" / "podman" / "MANIFEST.json"
)
assert expected_file.is_file()
def test_install_collection_fail(runtime: Runtime) -> None:
"""Check that invalid collection install fails."""
with pytest.raises(AnsibleCompatError) as pytest_wrapped_e:
runtime.install_collection("containers.podman:>=9999.0")
assert pytest_wrapped_e.type == InvalidPrerequisiteError
assert pytest_wrapped_e.value.code == INVALID_PREREQUISITES_RC
def test_install_galaxy_role(runtime_tmp: Runtime) -> None:
"""Check install role with empty galaxy file."""
pathlib.Path(f"{runtime_tmp.project_dir}/galaxy.yml").touch()
pathlib.Path(f"{runtime_tmp.project_dir}/meta").mkdir()
pathlib.Path(f"{runtime_tmp.project_dir}/meta/main.yml").touch()
# this should only raise a warning
runtime_tmp._install_galaxy_role(runtime_tmp.project_dir, role_name_check=1)
# this shoul test the bypass role name check path
runtime_tmp._install_galaxy_role(runtime_tmp.project_dir, role_name_check=2)
# this should raise an error
with pytest.raises(
InvalidPrerequisiteError, match="does not follow current galaxy requirements"
):
runtime_tmp._install_galaxy_role(runtime_tmp.project_dir, role_name_check=0)
def test_install_galaxy_role_unlink(
runtime_tmp: Runtime, caplog: pytest.LogCaptureFixture
) -> None:
"""Test ability to unlink incorrect symlinked roles."""
caplog.set_level(logging.INFO)
runtime_tmp.prepare_environment()
pathlib.Path(f"{runtime_tmp.cache_dir}/roles").mkdir(parents=True, exist_ok=True)
pathlib.Path(f"{runtime_tmp.cache_dir}/roles/acme.get_rich").symlink_to("/dev/null")
pathlib.Path(f"{runtime_tmp.project_dir}/meta").mkdir()
pathlib.Path(f"{runtime_tmp.project_dir}/meta/main.yml").write_text(
"""galaxy_info:
role_name: get_rich
namespace: acme
""",
encoding="utf-8",
)
runtime_tmp._install_galaxy_role(runtime_tmp.project_dir)
assert "symlink to current repository" in caplog.text
def test_install_galaxy_role_bad_namespace(runtime_tmp: Runtime) -> None:
"""Check install role with bad namespace in galaxy info."""
# pathlib.Path(f'{runtime_tmp.project_dir}/galaxy.yml').touch()
pathlib.Path(f"{runtime_tmp.project_dir}/meta").mkdir()
pathlib.Path(f"{runtime_tmp.project_dir}/meta/main.yml").write_text(
"""galaxy_info:
role_name: foo
author: bar
namespace: ["xxx"]
"""
)
# this should raise an error regardless the role_name_check value
with pytest.raises(AnsibleCompatError, match="Role namespace must be string, not"):
runtime_tmp._install_galaxy_role(runtime_tmp.project_dir, role_name_check=1)
def test_install_galaxy_role_no_checks(runtime_tmp: Runtime) -> None:
"""Check install role with bad namespace in galaxy info."""
runtime_tmp.prepare_environment()
pathlib.Path(f"{runtime_tmp.project_dir}/meta").mkdir()
pathlib.Path(f"{runtime_tmp.project_dir}/meta/main.yml").write_text(
"""galaxy_info:
role_name: foo
author: bar
namespace: acme
"""
)
runtime_tmp._install_galaxy_role(runtime_tmp.project_dir, role_name_check=2)
result = runtime_tmp.exec(["ansible-galaxy", "list"])
assert "- acme.foo," in result.stdout
assert result.returncode == 0, result
def test_upgrade_collection(runtime_tmp: Runtime) -> None:
"""Check that collection upgrade is possible."""
# ensure that we inject our tmp folders in ansible paths
runtime_tmp.prepare_environment()
# we install specific oudated version of a collection
runtime_tmp.install_collection("containers.podman:==1.6.0")
with pytest.raises(
InvalidPrerequisiteError,
match="Found containers.podman collection 1.6.0 but 1.6.1 or newer is required.",
):
# we check that when install=False, we raise error
runtime_tmp.require_collection("containers.podman", "1.6.1", install=False)
# now we really perform the upgrade
runtime_tmp.require_collection("containers.podman", "1.6.1")
def test_require_collection_no_cache_dir() -> None:
"""Check require_collection without a cache directory."""
runtime = Runtime()
assert not runtime.cache_dir
runtime.require_collection("community.molecule", "0.1.0", install=True)
def test_runtime_env_ansible_library(monkeypatch: MonkeyPatch) -> None:
"""Verify that custom path specified using ANSIBLE_LIBRARY is not lost."""
path_name = "foo"
monkeypatch.setenv("ANSIBLE_LIBRARY", path_name)
path_name = os.path.realpath(path_name)
runtime = Runtime()
runtime.prepare_environment()
assert path_name in runtime.config.default_module_path
@pytest.mark.parametrize(
("lower", "upper", "expected"),
(
("1.0", "9999.0", True),
(None, "9999.0", True),
("1.0", None, True),
("9999.0", None, False),
(None, "1.0", False),
),
ids=("1", "2", "3", "4", "5"),
)
def test_runtime_version_in_range(
lower: Union[str, None], upper: Union[str, None], expected: bool
) -> None:
"""Validate functioning of version_in_range."""
runtime = Runtime()
assert runtime.version_in_range(lower=lower, upper=upper) is expected
@pytest.mark.parametrize(
("path", "scenario"),
(
("test/collections/acme.goodies", "default"),
("test/collections/acme.goodies/roles/baz", "deep_scenario"),
),
ids=("normal", "deep"),
)
def test_install_collection_from_disk(path: str, scenario: str) -> None:
"""Tests ability to install a local collection."""
# ensure we do not have acme.google installed in user directory as it may
# produce false positives
rmtree(
os.path.expanduser("~/.ansible/collections/ansible_collections/acme/goodies"),
ignore_errors=True,
)
with remember_cwd(path):
runtime = Runtime(isolated=True)
# this should call install_collection_from_disk(".")
runtime.prepare_environment(install_local=True)
# that molecule converge playbook can be used without molecule and
# should validate that the installed collection is available.
result = runtime.exec(["ansible-playbook", f"molecule/{scenario}/converge.yml"])
assert result.returncode == 0, result.stdout
runtime.clean()
def test_install_collection_from_disk_fail() -> None:
"""Tests that we fail to install a broken collection."""
with remember_cwd("test/collections/acme.broken"):
runtime = Runtime(isolated=True)
exception: Type[Exception]
if runtime.version_in_range(upper="2.11"):
exception = AnsibleCommandError
msg = "Got 1 exit code while running: ansible-galaxy collection build"
else:
exception = InvalidPrerequisiteError
msg = "is missing the following mandatory"
with pytest.raises(exception, match=msg):
# this should call install_collection_from_disk(".")
runtime.prepare_environment(install_local=True)
def test_runtime_run(runtime: Runtime) -> None:
"""Check if tee and non tee mode return same kind of results."""
result1 = runtime.exec(["seq", "10"])
result2 = runtime.exec(["seq", "10"], tee=True)
assert result1.returncode == result2.returncode
assert result1.stderr == result2.stderr
assert result1.stdout == result2.stdout
def test_runtime_exec_cwd(runtime: Runtime) -> None:
"""Check if passing cwd works as expected."""
cwd = "/"
result1 = runtime.exec(["pwd"], cwd=cwd)
result2 = runtime.exec(["pwd"])
assert result1.stdout.rstrip() == cwd
assert result1.stdout != result2.stdout
def test_runtime_exec_env(runtime: Runtime) -> None:
"""Check if passing env works."""
result = runtime.exec(["printenv", "FOO"])
assert not result.stdout
result = runtime.exec(["printenv", "FOO"], env={"FOO": "bar"})
assert result.stdout.rstrip() == "bar"
runtime.environ["FOO"] = "bar"
result = runtime.exec(["printenv", "FOO"])
assert result.stdout.rstrip() == "bar" | test/test_runtime.py | # pylint: disable=protected-access
import logging
import os
import pathlib
import subprocess
from contextlib import contextmanager
from shutil import rmtree
from typing import Any, Iterator, List, Type, Union
import pytest
from _pytest.monkeypatch import MonkeyPatch
from flaky import flaky
from packaging.version import Version
from pytest_mock import MockerFixture
from ansible_compat.constants import INVALID_PREREQUISITES_RC
from ansible_compat.errors import (
AnsibleCommandError,
AnsibleCompatError,
InvalidPrerequisiteError,
)
from ansible_compat.runtime import CompletedProcess, Runtime
def test_runtime_version(runtime: Runtime) -> None:
"""Tests version property."""
version = runtime.version
assert isinstance(version, Version)
# tests that caching property value worked (coverage)
assert version == runtime.version
@pytest.mark.parametrize(
"require_module",
(True, False),
ids=("module-required", "module-unrequired"),
)
def test_runtime_version_outdated(require_module: bool) -> None:
"""Checks that instantiation raises if version is outdated."""
with pytest.raises(RuntimeError, match="Found incompatible version of ansible"):
Runtime(min_required_version="9999.9.9", require_module=require_module)
def test_runtime_missing_ansible_module(monkeypatch: MonkeyPatch) -> None:
"""Checks that we produce a RuntimeError when ansible module is missing."""
class RaiseException:
"""Class to raise an exception."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
raise ModuleNotFoundError()
monkeypatch.setattr("importlib.import_module", RaiseException)
with pytest.raises(RuntimeError, match="Unable to find Ansible python module."):
Runtime(require_module=True)
def test_runtime_mismatch_ansible_module(monkeypatch: MonkeyPatch) -> None:
"""Test that missing module is detected."""
monkeypatch.setattr("ansible.release.__version__", "0.0.0", raising=False)
with pytest.raises(RuntimeError, match="versions do not match"):
Runtime(require_module=True)
def test_runtime_require_module() -> None:
"""Check that require_module successful pass."""
Runtime(require_module=True)
def test_runtime_version_fail_module(mocker: MockerFixture) -> None:
"""Tests for failure to detect Ansible version."""
patched = mocker.patch(
"ansible_compat.runtime.parse_ansible_version",
autospec=True,
)
patched.side_effect = InvalidPrerequisiteError(
"Unable to parse ansible cli version"
)
runtime = Runtime()
with pytest.raises(
InvalidPrerequisiteError, match="Unable to parse ansible cli version"
):
runtime.version # pylint: disable=pointless-statement
def test_runtime_version_fail_cli(mocker: MockerFixture) -> None:
"""Tests for failure to detect Ansible version."""
mocker.patch(
"ansible_compat.runtime.Runtime.exec",
return_value=CompletedProcess(
["x"], returncode=123, stdout="oops", stderr="some error"
),
autospec=True,
)
runtime = Runtime()
with pytest.raises(
RuntimeError, match="Unable to find a working copy of ansible executable."
):
runtime.version # pylint: disable=pointless-statement
def test_runtime_prepare_ansible_paths_validation() -> None:
"""Check that we validate collection_path."""
runtime = Runtime()
runtime.config.collections_paths = "invalid-value" # type: ignore
with pytest.raises(RuntimeError, match="Unexpected ansible configuration"):
runtime._prepare_ansible_paths()
@pytest.mark.parametrize(
("folder", "role_name", "isolated"),
(
("ansible-role-sample", "acme.sample", True),
("acme.sample2", "acme.sample2", True),
("sample3", "acme.sample3", True),
("sample4", "acme.sample4", False),
),
ids=("1", "2", "3", "4"),
)
def test_runtime_install_role(
caplog: pytest.LogCaptureFixture,
folder: str,
role_name: str,
isolated: bool,
) -> None:
"""Checks that we can install roles."""
caplog.set_level(logging.INFO)
project_dir = os.path.join(os.path.dirname(__file__), "roles", folder)
runtime = Runtime(isolated=isolated, project_dir=project_dir)
runtime.prepare_environment(install_local=True)
# check that role appears as installed now
result = runtime.exec(["ansible-galaxy", "list"])
assert result.returncode == 0, result
assert role_name in result.stdout
runtime.clean()
# also test that clean does not break when cache_dir is missing
tmp_dir = runtime.cache_dir
runtime.cache_dir = None
runtime.clean()
runtime.cache_dir = tmp_dir
def test_prepare_environment_with_collections(tmp_path: pathlib.Path) -> None:
"""Check that collections are correctly installed."""
runtime = Runtime(isolated=True, project_dir=str(tmp_path))
runtime.prepare_environment(required_collections={"community.molecule": "0.1.0"})
def test_runtime_install_requirements_missing_file() -> None:
"""Check that missing requirements file is ignored."""
# Do not rely on this behavior, it may be removed in the future
runtime = Runtime()
runtime.install_requirements("/that/does/not/exist")
@pytest.mark.parametrize(
("file", "exc", "msg"),
(
(
"/dev/null",
InvalidPrerequisiteError,
"file is not a valid Ansible requirements file",
),
(
os.path.join(
os.path.dirname(__file__),
"assets",
"requirements-invalid-collection.yml",
),
AnsibleCommandError,
"Got 1 exit code while running: ansible-galaxy",
),
(
os.path.join(
os.path.dirname(__file__),
"assets",
"requirements-invalid-role.yml",
),
AnsibleCommandError,
"Got 1 exit code while running: ansible-galaxy",
),
),
ids=("empty", "invalid-collection", "invalid-role"),
)
def test_runtime_install_requirements_invalid_file(
file: str, exc: Type[Any], msg: str
) -> None:
"""Check that invalid requirements file is raising."""
runtime = Runtime()
with pytest.raises(
exc,
match=msg,
):
runtime.install_requirements(file)
@contextmanager
def remember_cwd(cwd: str) -> Iterator[None]:
"""Context manager for chdir."""
curdir = os.getcwd()
try:
os.chdir(cwd)
yield
finally:
os.chdir(curdir)
# # https://github.com/box/flaky/issues/170
@flaky(max_runs=3) # type: ignore
def test_prerun_reqs_v1(caplog: pytest.LogCaptureFixture, runtime: Runtime) -> None:
"""Checks that the linter can auto-install requirements v1 when found."""
cwd = os.path.realpath(
os.path.join(
os.path.dirname(os.path.realpath(__file__)), "..", "examples", "reqs_v1"
)
)
with remember_cwd(cwd):
with caplog.at_level(logging.INFO):
runtime.prepare_environment()
assert any(
msg.startswith("Running ansible-galaxy role install") for msg in caplog.messages
)
assert all(
"Running ansible-galaxy collection install" not in msg
for msg in caplog.messages
)
@flaky(max_runs=3) # type: ignore
def test_prerun_reqs_v2(caplog: pytest.LogCaptureFixture, runtime: Runtime) -> None:
"""Checks that the linter can auto-install requirements v2 when found."""
cwd = os.path.realpath(
os.path.join(
os.path.dirname(os.path.realpath(__file__)), "..", "examples", "reqs_v2"
)
)
with remember_cwd(cwd):
with caplog.at_level(logging.INFO):
runtime.prepare_environment()
assert any(
msg.startswith("Running ansible-galaxy role install")
for msg in caplog.messages
)
assert any(
msg.startswith("Running ansible-galaxy collection install")
for msg in caplog.messages
)
def test__update_env_no_old_value_no_default_no_value(monkeypatch: MonkeyPatch) -> None:
"""Make sure empty value does not touch environment."""
monkeypatch.delenv("DUMMY_VAR", raising=False)
runtime = Runtime()
runtime._update_env("DUMMY_VAR", [])
assert "DUMMY_VAR" not in runtime.environ
def test__update_env_no_old_value_no_value(monkeypatch: MonkeyPatch) -> None:
"""Make sure empty value does not touch environment."""
monkeypatch.delenv("DUMMY_VAR", raising=False)
runtime = Runtime()
runtime._update_env("DUMMY_VAR", [], "a:b")
assert "DUMMY_VAR" not in runtime.environ
def test__update_env_no_default_no_value(monkeypatch: MonkeyPatch) -> None:
"""Make sure empty value does not touch environment."""
monkeypatch.setenv("DUMMY_VAR", "a:b")
runtime = Runtime()
runtime._update_env("DUMMY_VAR", [])
assert runtime.environ["DUMMY_VAR"] == "a:b"
@pytest.mark.parametrize(
("value", "result"),
(
(["a"], "a"),
(["a", "b"], "a:b"),
(["a", "b", "c"], "a:b:c"),
),
)
def test__update_env_no_old_value_no_default(
monkeypatch: MonkeyPatch, value: List[str], result: str
) -> None:
"""Values are concatenated using : as the separator."""
monkeypatch.delenv("DUMMY_VAR", raising=False)
runtime = Runtime()
runtime._update_env("DUMMY_VAR", value)
assert runtime.environ["DUMMY_VAR"] == result
@pytest.mark.parametrize(
("default", "value", "result"),
(
("a:b", ["c"], "c:a:b"),
("a:b", ["c:d"], "c:d:a:b"),
),
)
def test__update_env_no_old_value(
monkeypatch: MonkeyPatch, default: str, value: List[str], result: str
) -> None:
"""Values are appended to default value."""
monkeypatch.delenv("DUMMY_VAR", raising=False)
runtime = Runtime()
runtime._update_env("DUMMY_VAR", value, default)
assert runtime.environ["DUMMY_VAR"] == result
@pytest.mark.parametrize(
("old_value", "value", "result"),
(
("a:b", ["c"], "c:a:b"),
("a:b", ["c:d"], "c:d:a:b"),
),
)
def test__update_env_no_default(
monkeypatch: MonkeyPatch, old_value: str, value: List[str], result: str
) -> None:
"""Values are appended to preexisting value."""
monkeypatch.setenv("DUMMY_VAR", old_value)
runtime = Runtime()
runtime._update_env("DUMMY_VAR", value)
assert runtime.environ["DUMMY_VAR"] == result
@pytest.mark.parametrize(
("old_value", "default", "value", "result"),
(
("", "", ["e"], "e"),
("a", "", ["e"], "e:a"),
("", "c", ["e"], "e"),
("a", "c", ["e:f"], "e:f:a"),
),
)
def test__update_env(
monkeypatch: MonkeyPatch,
old_value: str,
default: str, # pylint: disable=unused-argument
value: List[str],
result: str,
) -> None:
"""Defaults are ignored when preexisting value is present."""
monkeypatch.setenv("DUMMY_VAR", old_value)
runtime = Runtime()
runtime._update_env("DUMMY_VAR", value)
assert runtime.environ["DUMMY_VAR"] == result
def test_require_collection_wrong_version(runtime: Runtime) -> None:
"""Tests behaviour of require_collection."""
subprocess.check_output(
[
"ansible-galaxy",
"collection",
"install",
"containers.podman",
"-p",
"~/.ansible/collections",
]
)
with pytest.raises(InvalidPrerequisiteError) as pytest_wrapped_e:
runtime.require_collection("containers.podman", "9999.9.9")
assert pytest_wrapped_e.type == InvalidPrerequisiteError
assert pytest_wrapped_e.value.code == INVALID_PREREQUISITES_RC
def test_require_collection_invalid_name(runtime: Runtime) -> None:
"""Check that require_collection raise with invalid collection name."""
with pytest.raises(
InvalidPrerequisiteError, match="Invalid collection name supplied:"
):
runtime.require_collection("that-is-invalid")
def test_require_collection_invalid_collections_path(runtime: Runtime) -> None:
"""Check that require_collection raise with invalid collections path."""
runtime.config.collections_paths = "/that/is/invalid" # type: ignore
with pytest.raises(
InvalidPrerequisiteError, match="Unable to determine ansible collection paths"
):
runtime.require_collection("community.molecule")
def test_require_collection_preexisting_broken(tmp_path: pathlib.Path) -> None:
"""Check that require_collection raise with broken pre-existing collection."""
runtime = Runtime(isolated=True, project_dir=str(tmp_path))
dest_path: str = runtime.config.collections_paths[0]
dest = os.path.join(dest_path, "ansible_collections", "foo", "bar")
os.makedirs(dest, exist_ok=True)
with pytest.raises(InvalidPrerequisiteError, match="missing MANIFEST.json"):
runtime.require_collection("foo.bar")
def test_require_collection(runtime_tmp: Runtime) -> None:
"""Check that require collection successful install case."""
runtime_tmp.require_collection("community.molecule", "0.1.0")
@pytest.mark.parametrize(
("name", "version", "install"),
(
("fake_namespace.fake_name", None, True),
("fake_namespace.fake_name", "9999.9.9", True),
("fake_namespace.fake_name", None, False),
),
ids=("a", "b", "c"),
)
def test_require_collection_missing(
name: str, version: str, install: bool, runtime: Runtime
) -> None:
"""Tests behaviour of require_collection, missing case."""
with pytest.raises(AnsibleCompatError) as pytest_wrapped_e:
runtime.require_collection(name=name, version=version, install=install)
assert pytest_wrapped_e.type == InvalidPrerequisiteError
assert pytest_wrapped_e.value.code == INVALID_PREREQUISITES_RC
def test_install_collection(runtime: Runtime) -> None:
"""Check that valid collection installs do not fail."""
runtime.install_collection("containers.podman:>=1.0")
def test_install_collection_dest(runtime: Runtime, tmp_path: pathlib.Path) -> None:
"""Check that valid collection to custom destination passes."""
runtime.install_collection("containers.podman:>=1.0", destination=tmp_path)
expected_file = (
tmp_path / "ansible_collections" / "containers" / "podman" / "MANIFEST.json"
)
assert expected_file.is_file()
def test_install_collection_fail(runtime: Runtime) -> None:
"""Check that invalid collection install fails."""
with pytest.raises(AnsibleCompatError) as pytest_wrapped_e:
runtime.install_collection("containers.podman:>=9999.0")
assert pytest_wrapped_e.type == InvalidPrerequisiteError
assert pytest_wrapped_e.value.code == INVALID_PREREQUISITES_RC
def test_install_galaxy_role(runtime_tmp: Runtime) -> None:
"""Check install role with empty galaxy file."""
pathlib.Path(f"{runtime_tmp.project_dir}/galaxy.yml").touch()
pathlib.Path(f"{runtime_tmp.project_dir}/meta").mkdir()
pathlib.Path(f"{runtime_tmp.project_dir}/meta/main.yml").touch()
# this should only raise a warning
runtime_tmp._install_galaxy_role(runtime_tmp.project_dir, role_name_check=1)
# this shoul test the bypass role name check path
runtime_tmp._install_galaxy_role(runtime_tmp.project_dir, role_name_check=2)
# this should raise an error
with pytest.raises(
InvalidPrerequisiteError, match="does not follow current galaxy requirements"
):
runtime_tmp._install_galaxy_role(runtime_tmp.project_dir, role_name_check=0)
def test_install_galaxy_role_unlink(
runtime_tmp: Runtime, caplog: pytest.LogCaptureFixture
) -> None:
"""Test ability to unlink incorrect symlinked roles."""
caplog.set_level(logging.INFO)
runtime_tmp.prepare_environment()
pathlib.Path(f"{runtime_tmp.cache_dir}/roles").mkdir(parents=True, exist_ok=True)
pathlib.Path(f"{runtime_tmp.cache_dir}/roles/acme.get_rich").symlink_to("/dev/null")
pathlib.Path(f"{runtime_tmp.project_dir}/meta").mkdir()
pathlib.Path(f"{runtime_tmp.project_dir}/meta/main.yml").write_text(
"""galaxy_info:
role_name: get_rich
namespace: acme
""",
encoding="utf-8",
)
runtime_tmp._install_galaxy_role(runtime_tmp.project_dir)
assert "symlink to current repository" in caplog.text
def test_install_galaxy_role_bad_namespace(runtime_tmp: Runtime) -> None:
"""Check install role with bad namespace in galaxy info."""
# pathlib.Path(f'{runtime_tmp.project_dir}/galaxy.yml').touch()
pathlib.Path(f"{runtime_tmp.project_dir}/meta").mkdir()
pathlib.Path(f"{runtime_tmp.project_dir}/meta/main.yml").write_text(
"""galaxy_info:
role_name: foo
author: bar
namespace: ["xxx"]
"""
)
# this should raise an error regardless the role_name_check value
with pytest.raises(AnsibleCompatError, match="Role namespace must be string, not"):
runtime_tmp._install_galaxy_role(runtime_tmp.project_dir, role_name_check=1)
def test_install_galaxy_role_no_checks(runtime_tmp: Runtime) -> None:
"""Check install role with bad namespace in galaxy info."""
runtime_tmp.prepare_environment()
pathlib.Path(f"{runtime_tmp.project_dir}/meta").mkdir()
pathlib.Path(f"{runtime_tmp.project_dir}/meta/main.yml").write_text(
"""galaxy_info:
role_name: foo
author: bar
namespace: acme
"""
)
runtime_tmp._install_galaxy_role(runtime_tmp.project_dir, role_name_check=2)
result = runtime_tmp.exec(["ansible-galaxy", "list"])
assert "- acme.foo," in result.stdout
assert result.returncode == 0, result
def test_upgrade_collection(runtime_tmp: Runtime) -> None:
"""Check that collection upgrade is possible."""
# ensure that we inject our tmp folders in ansible paths
runtime_tmp.prepare_environment()
# we install specific oudated version of a collection
runtime_tmp.install_collection("containers.podman:==1.6.0")
with pytest.raises(
InvalidPrerequisiteError,
match="Found containers.podman collection 1.6.0 but 1.6.1 or newer is required.",
):
# we check that when install=False, we raise error
runtime_tmp.require_collection("containers.podman", "1.6.1", install=False)
# now we really perform the upgrade
runtime_tmp.require_collection("containers.podman", "1.6.1")
def test_require_collection_no_cache_dir() -> None:
"""Check require_collection without a cache directory."""
runtime = Runtime()
assert not runtime.cache_dir
runtime.require_collection("community.molecule", "0.1.0", install=True)
def test_runtime_env_ansible_library(monkeypatch: MonkeyPatch) -> None:
"""Verify that custom path specified using ANSIBLE_LIBRARY is not lost."""
path_name = "foo"
monkeypatch.setenv("ANSIBLE_LIBRARY", path_name)
path_name = os.path.realpath(path_name)
runtime = Runtime()
runtime.prepare_environment()
assert path_name in runtime.config.default_module_path
@pytest.mark.parametrize(
("lower", "upper", "expected"),
(
("1.0", "9999.0", True),
(None, "9999.0", True),
("1.0", None, True),
("9999.0", None, False),
(None, "1.0", False),
),
ids=("1", "2", "3", "4", "5"),
)
def test_runtime_version_in_range(
lower: Union[str, None], upper: Union[str, None], expected: bool
) -> None:
"""Validate functioning of version_in_range."""
runtime = Runtime()
assert runtime.version_in_range(lower=lower, upper=upper) is expected
@pytest.mark.parametrize(
("path", "scenario"),
(
("test/collections/acme.goodies", "default"),
("test/collections/acme.goodies/roles/baz", "deep_scenario"),
),
ids=("normal", "deep"),
)
def test_install_collection_from_disk(path: str, scenario: str) -> None:
"""Tests ability to install a local collection."""
# ensure we do not have acme.google installed in user directory as it may
# produce false positives
rmtree(
os.path.expanduser("~/.ansible/collections/ansible_collections/acme/goodies"),
ignore_errors=True,
)
with remember_cwd(path):
runtime = Runtime(isolated=True)
# this should call install_collection_from_disk(".")
runtime.prepare_environment(install_local=True)
# that molecule converge playbook can be used without molecule and
# should validate that the installed collection is available.
result = runtime.exec(["ansible-playbook", f"molecule/{scenario}/converge.yml"])
assert result.returncode == 0, result.stdout
runtime.clean()
def test_install_collection_from_disk_fail() -> None:
"""Tests that we fail to install a broken collection."""
with remember_cwd("test/collections/acme.broken"):
runtime = Runtime(isolated=True)
exception: Type[Exception]
if runtime.version_in_range(upper="2.11"):
exception = AnsibleCommandError
msg = "Got 1 exit code while running: ansible-galaxy collection build"
else:
exception = InvalidPrerequisiteError
msg = "is missing the following mandatory"
with pytest.raises(exception, match=msg):
# this should call install_collection_from_disk(".")
runtime.prepare_environment(install_local=True)
def test_runtime_run(runtime: Runtime) -> None:
"""Check if tee and non tee mode return same kind of results."""
result1 = runtime.exec(["seq", "10"])
result2 = runtime.exec(["seq", "10"], tee=True)
assert result1.returncode == result2.returncode
assert result1.stderr == result2.stderr
assert result1.stdout == result2.stdout
def test_runtime_exec_cwd(runtime: Runtime) -> None:
"""Check if passing cwd works as expected."""
cwd = "/"
result1 = runtime.exec(["pwd"], cwd=cwd)
result2 = runtime.exec(["pwd"])
assert result1.stdout.rstrip() == cwd
assert result1.stdout != result2.stdout
def test_runtime_exec_env(runtime: Runtime) -> None:
"""Check if passing env works."""
result = runtime.exec(["printenv", "FOO"])
assert not result.stdout
result = runtime.exec(["printenv", "FOO"], env={"FOO": "bar"})
assert result.stdout.rstrip() == "bar"
runtime.environ["FOO"] = "bar"
result = runtime.exec(["printenv", "FOO"])
assert result.stdout.rstrip() == "bar" | 0.783492 | 0.272787 |
import os
import shutil
import errno
from ..errors import error_response
from .fileio import joinpath
from flask import current_app
__all__ = ['get_lob_file', 'put_lob_file']
def get_lob_file(fsrc, fdest):
pass
def put_lob_file(fsrc, fdest):
'''Store the file to lobceder destination specified'''
if fdest.startswith(current_app.config['LOBCDER_DAV_ROOT']):
fdest = joinpath(current_app.config['LOBCDER_FOLDER'], fdest.split(current_app.config['LOBCDER_DAV_ROOT'])[-1])
# Check if we are still rooted to LOBCDER_FOLDER mount point
if fdest.startswith(current_app.config['LOBCDER_FOLDER']):
if not os.path.exists(os.path.dirname(fdest)):
try:
os.makedirs(os.path.dirname(fdest))
except OSError, e:
if e.errno != errno.EEXIST:
err_msg = {"server_error": "And the OS survey said: %s." % os.strerror(e.errno)}
return error_response(500, err_msg)
else:
err_msg = {"client_error": "Insecure file path specified."}
return error_response(403, err_msg)
if os.path.isdir(fdest):
try:
# Save file to directory
shutil.copy2(fsrc, joinpath(fdest, fsrc.filename))
# fsrc.save(joinpath(fdest, fsrc.filename))
except OSError, e:
if e.errno != errno.EEXIST:
err_msg = {"server_error": "And the OS survey said: %s." % os.strerror(e.errno)}
return error_response(500, err_msg)
else:
try:
# Save file to dest filename
print "saving file" + fdest
shutil.copy2(fsrc, fdest)
# fsrc.save(fdest)
except OSError, e:
if e.errno != errno.EEXIST:
err_msg = {"server_error": "And the OS survey said: %s." % os.strerror(e.errno)}
return error_response(500, err_msg)
return None
else:
err_msg = {"client_error": "Destination path must start with %s." % current_app.config['LOBCDER_DAV_ROOT']}
return error_response(412, err_msg) | transmogrifier/api/utils/lobcder.py | import os
import shutil
import errno
from ..errors import error_response
from .fileio import joinpath
from flask import current_app
__all__ = ['get_lob_file', 'put_lob_file']
def get_lob_file(fsrc, fdest):
pass
def put_lob_file(fsrc, fdest):
'''Store the file to lobceder destination specified'''
if fdest.startswith(current_app.config['LOBCDER_DAV_ROOT']):
fdest = joinpath(current_app.config['LOBCDER_FOLDER'], fdest.split(current_app.config['LOBCDER_DAV_ROOT'])[-1])
# Check if we are still rooted to LOBCDER_FOLDER mount point
if fdest.startswith(current_app.config['LOBCDER_FOLDER']):
if not os.path.exists(os.path.dirname(fdest)):
try:
os.makedirs(os.path.dirname(fdest))
except OSError, e:
if e.errno != errno.EEXIST:
err_msg = {"server_error": "And the OS survey said: %s." % os.strerror(e.errno)}
return error_response(500, err_msg)
else:
err_msg = {"client_error": "Insecure file path specified."}
return error_response(403, err_msg)
if os.path.isdir(fdest):
try:
# Save file to directory
shutil.copy2(fsrc, joinpath(fdest, fsrc.filename))
# fsrc.save(joinpath(fdest, fsrc.filename))
except OSError, e:
if e.errno != errno.EEXIST:
err_msg = {"server_error": "And the OS survey said: %s." % os.strerror(e.errno)}
return error_response(500, err_msg)
else:
try:
# Save file to dest filename
print "saving file" + fdest
shutil.copy2(fsrc, fdest)
# fsrc.save(fdest)
except OSError, e:
if e.errno != errno.EEXIST:
err_msg = {"server_error": "And the OS survey said: %s." % os.strerror(e.errno)}
return error_response(500, err_msg)
return None
else:
err_msg = {"client_error": "Destination path must start with %s." % current_app.config['LOBCDER_DAV_ROOT']}
return error_response(412, err_msg) | 0.121178 | 0.077483 |
import logging
import os
import subprocess
from common import app
from common import service
from common import utils
from common import docker_lib
from common import constants
from common import fm_logger
from manager.service_handler.mysql import aws_handler as awsh
fmlogging = fm_logger.Logging()
class AWSBuilder(object):
def __init__(self, task_def):
self.task_def = task_def
if task_def.app_data:
self.app_dir = task_def.app_data['app_location']
self.app_name = task_def.app_data['app_name']
self.app_version = task_def.app_data['app_version']
self.services = {}
if task_def.service_data:
self.service_obj = service.Service(task_def.service_data[0])
if self.service_obj.get_service_type() == 'mysql':
self.services['mysql'] = awsh.MySQLServiceHandler(self.task_def)
self.docker_handler = docker_lib.DockerLib()
def _build_app_container(self, app_obj):
#cwd = os.getcwd()
app_dir = self.task_def.app_data['app_location']
app_name = self.task_def.app_data['app_name']
docker_file_loc = app_dir + "/" + app_name
#os.chdir(app_dir + "/" + app_name)
cont_name = app_obj.get_cont_name()
fmlogging.debug("Container name that will be used in building:%s" % cont_name)
self.docker_handler.build_container_image(cont_name,
docker_file_loc + "/Dockerfile.deploy", df_context=docker_file_loc)
#os.chdir(cwd)
def build_for_logs(self, info):
fmlogging.debug("AWS builder called for getting app logs of app:%s" % info['app_name'])
app_name = info['app_name']
app_version = info['app_version']
app_dir = (constants.APP_STORE_PATH + "/{app_name}/{app_version}/{app_name}").format(app_name=app_name,
app_version=app_version)
#cwd = os.getcwd()
#os.chdir(app_dir)
output = ''
try:
cont_name = app_name + "-" + app_version
cmd = ("docker build -t {app_name}-getec2-ip -f {app_dir}/Dockerfile.get-instance-ip {app_dir}").format(app_name=cont_name,
app_dir=app_dir)
output = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=True).communicate()[0]
except Exception as e:
self.logger.error(e)
# Parse the PublicIPAddress of the EC2 instance
env_name = utils.read_environment_name(app_dir)
public_ip = ""
public_ip_of_ec2_instance = ''
for line in output.split("\n"):
if line.find("PublicIp") >= 0:
prts = line.split(":")
public_ip = prts[1].rstrip().lstrip().replace(",","").replace("\"","")
if line.find("Value") >= 0:
prts = line.split(":")
is_env_name = prts[1].rstrip().lstrip().replace(",","").replace("\"","")
if line.find("Key") >= 0:
prts = line.split(":")
if prts and len(prts) >= 3:
env_key = prts[1].rstrip().lstrip().replace(",","").replace("\"","")
env_key1 = prts[2].rstrip().lstrip().replace(",","").replace("\"","")
if env_key.find("elasticbeanstalk") >= 0 and env_key1.find("environment-name") >= 0:
if is_env_name == env_name:
fmlogging.debug("Public IP of EC2 instance:%s" % public_ip)
public_ip_of_ec2_instance = public_ip
break
# Plug the public_ip in Dockerfile.retrieve-logs
pem_file = env_name + ".pem"
fp = open(app_dir + "/Dockerfile.retrieve-logs", "a")
ssh_cmd = (" && ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no "
"-i ~/.ssh/{pem_file} ec2-user@{public_ip} 'bash -s' < {ret_log_sh} \ \n "
).format(pem_file=pem_file, public_ip=public_ip_of_ec2_instance, ret_log_sh=constants.RETRIEVE_LOG_PATH)
runtime_log = app_version + constants.RUNTIME_LOG
scp_cmd = (" && scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no "
"-i ~/.ssh/{pem_file} ec2-user@{public_ip}:/home/ec2-user/uwsgi.log {runtime_log} \n "
).format(pem_file=pem_file, public_ip=public_ip_of_ec2_instance, runtime_log=runtime_log)
fp.write(ssh_cmd)
fp.write(scp_cmd)
fp.flush()
fp.close()
log_cont_name = ("{app_name}-retrieve-logs").format(app_name=cont_name)
cmd = ("docker build -t {log_cont_name} -f {app_dir}/Dockerfile.retrieve-logs {app_dir}").format(log_cont_name=log_cont_name,
app_dir=app_dir)
os.system(cmd)
#os.chdir(cwd)
def build_for_delete(self, info):
cont_name = ''
work_dir = ''
if info['app_name']:
fmlogging.debug("AWS builder called for delete of app:%s" % info['app_name'])
app_name = info['app_name']
app_version = info['app_version']
cont_name = app_name + "-" + app_version
work_dir = (constants.APP_STORE_PATH + "/{app_name}/{app_version}/{app_name}").format(app_name=app_name,
app_version=app_version)
if info['service_name']:
service_name = info['service_name']
service_version = info['service_version']
if not cont_name:
cont_name = service_name + "-" + service_version
if not work_dir:
work_dir = (constants.SERVICE_STORE_PATH + "/{service_name}/{service_version}/").format(service_name=service_name,
service_version=service_version)
#cwd = os.getcwd()
#os.chdir(work_dir)
self.docker_handler.build_container_image(cont_name + "-delete", work_dir + "/Dockerfile.delete", df_context=work_dir)
if os.path.exists(work_dir + "/Dockerfile.status"):
self.docker_handler.build_container_image(cont_name + "-status", work_dir + "/Dockerfile.status", df_context=work_dir)
#os.chdir(cwd)
self.docker_handler.remove_container_image(cont_name + "-delete", "done deleting the app")
def build_to_secure(self, info):
fmlogging.debug("AWS builder called for securing service:%s" % info['service_name'])
cont_name = ''
work_dir = ''
if info['service_name']:
service_name = info['service_name']
service_version = info['service_version']
if not cont_name:
cont_name = service_name + "-" + service_version
modify_cont = cont_name + "-modify"
status_cont = cont_name + "-status"
if not work_dir:
work_dir = (constants.SERVICE_STORE_PATH + "/{service_name}/{service_version}/").format(service_name=service_name,
service_version=service_version)
self.docker_handler.build_container_image(modify_cont, work_dir + "/Dockerfile.modify", df_context=work_dir)
if os.path.exists(work_dir + "/Dockerfile.status"):
self.docker_handler.build_container_image(status_cont, work_dir + "/Dockerfile.status", df_context=work_dir)
def build(self, build_type, build_name):
if build_type == 'service':
fmlogging.debug("AWS builder called for service")
for serv in self.task_def.service_data:
serv_handler = self.services[serv['service']['type']]
utils.update_status(self.service_obj.get_status_file_location(),
"BUILDING_ARTIFACTS_FOR_PROVISIONING_SERVICE_INSTANCE")
# Invoke public interface
serv_handler.build_instance_artifacts()
elif build_type == 'app':
fmlogging.debug("Local builder called for app %s" %
self.task_def.app_data['app_name'])
app_obj = app.App(self.task_def.app_data)
app_obj.update_app_status(constants.BUILDING_APP)
self._build_app_container(app_obj) | manager/builder/aws_builder.py | import logging
import os
import subprocess
from common import app
from common import service
from common import utils
from common import docker_lib
from common import constants
from common import fm_logger
from manager.service_handler.mysql import aws_handler as awsh
fmlogging = fm_logger.Logging()
class AWSBuilder(object):
def __init__(self, task_def):
self.task_def = task_def
if task_def.app_data:
self.app_dir = task_def.app_data['app_location']
self.app_name = task_def.app_data['app_name']
self.app_version = task_def.app_data['app_version']
self.services = {}
if task_def.service_data:
self.service_obj = service.Service(task_def.service_data[0])
if self.service_obj.get_service_type() == 'mysql':
self.services['mysql'] = awsh.MySQLServiceHandler(self.task_def)
self.docker_handler = docker_lib.DockerLib()
def _build_app_container(self, app_obj):
#cwd = os.getcwd()
app_dir = self.task_def.app_data['app_location']
app_name = self.task_def.app_data['app_name']
docker_file_loc = app_dir + "/" + app_name
#os.chdir(app_dir + "/" + app_name)
cont_name = app_obj.get_cont_name()
fmlogging.debug("Container name that will be used in building:%s" % cont_name)
self.docker_handler.build_container_image(cont_name,
docker_file_loc + "/Dockerfile.deploy", df_context=docker_file_loc)
#os.chdir(cwd)
def build_for_logs(self, info):
fmlogging.debug("AWS builder called for getting app logs of app:%s" % info['app_name'])
app_name = info['app_name']
app_version = info['app_version']
app_dir = (constants.APP_STORE_PATH + "/{app_name}/{app_version}/{app_name}").format(app_name=app_name,
app_version=app_version)
#cwd = os.getcwd()
#os.chdir(app_dir)
output = ''
try:
cont_name = app_name + "-" + app_version
cmd = ("docker build -t {app_name}-getec2-ip -f {app_dir}/Dockerfile.get-instance-ip {app_dir}").format(app_name=cont_name,
app_dir=app_dir)
output = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, shell=True).communicate()[0]
except Exception as e:
self.logger.error(e)
# Parse the PublicIPAddress of the EC2 instance
env_name = utils.read_environment_name(app_dir)
public_ip = ""
public_ip_of_ec2_instance = ''
for line in output.split("\n"):
if line.find("PublicIp") >= 0:
prts = line.split(":")
public_ip = prts[1].rstrip().lstrip().replace(",","").replace("\"","")
if line.find("Value") >= 0:
prts = line.split(":")
is_env_name = prts[1].rstrip().lstrip().replace(",","").replace("\"","")
if line.find("Key") >= 0:
prts = line.split(":")
if prts and len(prts) >= 3:
env_key = prts[1].rstrip().lstrip().replace(",","").replace("\"","")
env_key1 = prts[2].rstrip().lstrip().replace(",","").replace("\"","")
if env_key.find("elasticbeanstalk") >= 0 and env_key1.find("environment-name") >= 0:
if is_env_name == env_name:
fmlogging.debug("Public IP of EC2 instance:%s" % public_ip)
public_ip_of_ec2_instance = public_ip
break
# Plug the public_ip in Dockerfile.retrieve-logs
pem_file = env_name + ".pem"
fp = open(app_dir + "/Dockerfile.retrieve-logs", "a")
ssh_cmd = (" && ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no "
"-i ~/.ssh/{pem_file} ec2-user@{public_ip} 'bash -s' < {ret_log_sh} \ \n "
).format(pem_file=pem_file, public_ip=public_ip_of_ec2_instance, ret_log_sh=constants.RETRIEVE_LOG_PATH)
runtime_log = app_version + constants.RUNTIME_LOG
scp_cmd = (" && scp -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no "
"-i ~/.ssh/{pem_file} ec2-user@{public_ip}:/home/ec2-user/uwsgi.log {runtime_log} \n "
).format(pem_file=pem_file, public_ip=public_ip_of_ec2_instance, runtime_log=runtime_log)
fp.write(ssh_cmd)
fp.write(scp_cmd)
fp.flush()
fp.close()
log_cont_name = ("{app_name}-retrieve-logs").format(app_name=cont_name)
cmd = ("docker build -t {log_cont_name} -f {app_dir}/Dockerfile.retrieve-logs {app_dir}").format(log_cont_name=log_cont_name,
app_dir=app_dir)
os.system(cmd)
#os.chdir(cwd)
def build_for_delete(self, info):
cont_name = ''
work_dir = ''
if info['app_name']:
fmlogging.debug("AWS builder called for delete of app:%s" % info['app_name'])
app_name = info['app_name']
app_version = info['app_version']
cont_name = app_name + "-" + app_version
work_dir = (constants.APP_STORE_PATH + "/{app_name}/{app_version}/{app_name}").format(app_name=app_name,
app_version=app_version)
if info['service_name']:
service_name = info['service_name']
service_version = info['service_version']
if not cont_name:
cont_name = service_name + "-" + service_version
if not work_dir:
work_dir = (constants.SERVICE_STORE_PATH + "/{service_name}/{service_version}/").format(service_name=service_name,
service_version=service_version)
#cwd = os.getcwd()
#os.chdir(work_dir)
self.docker_handler.build_container_image(cont_name + "-delete", work_dir + "/Dockerfile.delete", df_context=work_dir)
if os.path.exists(work_dir + "/Dockerfile.status"):
self.docker_handler.build_container_image(cont_name + "-status", work_dir + "/Dockerfile.status", df_context=work_dir)
#os.chdir(cwd)
self.docker_handler.remove_container_image(cont_name + "-delete", "done deleting the app")
def build_to_secure(self, info):
fmlogging.debug("AWS builder called for securing service:%s" % info['service_name'])
cont_name = ''
work_dir = ''
if info['service_name']:
service_name = info['service_name']
service_version = info['service_version']
if not cont_name:
cont_name = service_name + "-" + service_version
modify_cont = cont_name + "-modify"
status_cont = cont_name + "-status"
if not work_dir:
work_dir = (constants.SERVICE_STORE_PATH + "/{service_name}/{service_version}/").format(service_name=service_name,
service_version=service_version)
self.docker_handler.build_container_image(modify_cont, work_dir + "/Dockerfile.modify", df_context=work_dir)
if os.path.exists(work_dir + "/Dockerfile.status"):
self.docker_handler.build_container_image(status_cont, work_dir + "/Dockerfile.status", df_context=work_dir)
def build(self, build_type, build_name):
if build_type == 'service':
fmlogging.debug("AWS builder called for service")
for serv in self.task_def.service_data:
serv_handler = self.services[serv['service']['type']]
utils.update_status(self.service_obj.get_status_file_location(),
"BUILDING_ARTIFACTS_FOR_PROVISIONING_SERVICE_INSTANCE")
# Invoke public interface
serv_handler.build_instance_artifacts()
elif build_type == 'app':
fmlogging.debug("Local builder called for app %s" %
self.task_def.app_data['app_name'])
app_obj = app.App(self.task_def.app_data)
app_obj.update_app_status(constants.BUILDING_APP)
self._build_app_container(app_obj) | 0.21684 | 0.046012 |
import fileinput
import sys
import subprocess
import os
class OtaAfrProject:
"""OtaAfrProject represents the Amazon FreeRTOS code base for OTA.
This class is used to update the Amazon FreeRTOS project for OTA.
Attributes:
_buildConfig(dict): Build configuration from 'build_config' field in board.json.
_projectRootDir(str): The root of the Amazon FreeRTOS project i.e. $AFR_ROOT/demos or $AFR_ROOT/tests.
_boardPortablePath(str): the vendor/board path of the Amazon FreeRTOS project.
Methods:
initializeOtaProject()
buildProject()
setClientCredentialForThingName(thingName)
setClientCredentialKeys(certificate, privateKey)
setApplicationVersion(major, minor, bugfix)
setCodesignerCertificate(codesignerCertificatePath)
__setDemoRunnerForOtaDemo()
setClientCredentialsForWifi()
setClientCredentialsForAwsIotEndpoint()
__setIdentifierInFile(prefixToValue, filePath)
Example:
from aws_ota_aws_agent import AwsIoTThing
otaProject = OtaAfrProject('C:/amazon-freertos', buildConfig)
otaProject.initializeOtaProject()
iotThing = AWSIoTThing('boardName')
otaProject.setClientCredentialForThingName(iotThing.thing_name)
otaProject.setClientCredentialKeys(iotThing.cert, iotThing.priv_key)
otaProject.buildProject()
"""
DEMO_RUNNER_PATH = 'common/demo_runner/aws_demo_runner.c'
CLIENT_CREDENTIAL_PATH = 'common/include/aws_clientcredential.h'
APPLICATION_VERSION_PATH = 'common/include/aws_application_version.h'
CLIENT_CREDENTIAL_KEYS_PATH ='common/include/aws_clientcredential_keys.h'
OTA_CODESIGNER_CERTIFICATE_PATH = 'common/include/aws_ota_codesigner_certificate.h'
OTA_UPDATE_DEMO_PATH = 'demos/common/ota/aws_ota_update_demo.c'
OTA_BOOTLOADER_CONFIG_PATH = 'demos/common/ota/bootloader/utility/user-config/ota-descriptor.config'
OTA_BOOTLOADER_CERTIFICATE_PATH = 'demos/common/ota/bootloader/utility/codesigner_cert_utility/aws_ota_codesigner_certificate.pem'
OTA_FACTORY_IMAGE_GENERATOR_PATH = 'demos/common/ota/bootloader/utility/factory_image_generator.py'
def __init__(self, projectRootDir, boardPortablePath, buildConfig):
self._buildConfig = buildConfig
self._projectRootDir = projectRootDir
self._boardPortablePath = boardPortablePath
self._bootloaderSequenceNumber = 0
def initializeOtaProject(self):
"""Initialize the Amazon FreeRTOS project for OTA.
"""
base = os.path.basename(self._projectRootDir)
if base == 'demos':
self.__setDemoRunnerForOtaDemo()
elif base == 'tests':
self.__setTestRunnerForOtaDemo()
else:
raise Exception('ERROR: Invalid project root \"{}\". The valid values are \"demos\" and \"tests\".'.format(base))
def generateFactoryImage(self):
# If this board uses the Amazon FreeRTOS reference bootlaoder, then we want to
# build and flash the factory image.
if self._buildConfig.get('use_reference_bootloader', False):
factoryImageGenCommand = \
'python ' + os.path.join(self._projectRootDir, '..', OtaAfrProject.OTA_FACTORY_IMAGE_GENERATOR_PATH) + ' ' + \
'-b ' + self._buildConfig['output'] + ' ' + \
'-p ' + self._buildConfig['bootloader_hardware_platform'] + ' ' + \
'-k ' + self._buildConfig['bootloader_private_key_path'] + ' ' + \
'-x ' + self._buildConfig['bootloader_output']
subprocess.call(
factoryImageGenCommand,
shell=True
)
def buildProject(self):
"""Build the Amazon FreeRTOS project represented by this object.
"""
# Update the bootloader sequence number for every new build
self.__incrementBootloaderSequenceNumber()
# Save the system path to restore.
system_path = os.environ['PATH']
# Add the tool_paths to the system PATH
for path in self._buildConfig['tool_paths']:
os.environ['PATH'] += ';' + path
buildCommands = self._buildConfig['commands']
print('Building project {}...'.format(self._buildConfig['project_dir']))
for command in buildCommands:
command = command.format(**self._buildConfig)
subprocess.Popen(command + ' >> build_output.txt 2>&1', shell=True).wait()
output = self._buildConfig['output']
if not os.path.exists(output):
print("ERROR: Could not find the output binary, the build might have failed.")
raise Exception("Error building project check build_output.txt")
print('Build finished, output: {}'.format(self._buildConfig['output']))
# Restore the system path
os.environ['PATH'] = system_path
def __incrementBootloaderSequenceNumber(self):
self._bootloaderSequenceNumber += 1
self.__setBootloaderSequenceNumber(self._bootloaderSequenceNumber)
def __setBootloaderSequenceNumber(self, number):
self.__setIdentifierInFile(
{
'SEQUENCE_NUMBER': '= ' + str(number)
},
os.path.join(self._projectRootDir, '..', OtaAfrProject.OTA_BOOTLOADER_CONFIG_PATH)
)
def copyCodesignerCertificateToBootloader(self, certificate):
"""Copies the input certificate to a file named: aws_ota_codesigner_certificate.pem under
demos/common/ota/bootloader/utility/codesigner_cert_utility.
"""
with open(os.path.join(self._projectRootDir, '..', OtaAfrProject.OTA_BOOTLOADER_CERTIFICATE_PATH), 'w') as f:
f.write(certificate)
def __setDemoRunnerForOtaDemo(self):
"""
Updates the aws_demo_runner.c to disable the default MQTT Echo demo and enable the OTA
update demo.
"""
demoRunnerFilePath = os.path.join(self._projectRootDir, OtaAfrProject.DEMO_RUNNER_PATH)
vStartMQTTEchoDemo = "vStartMQTTEchoDemo"
vStartotaUpdateDemoTask = "vStartOTAUpdateDemoTask"
for line in fileinput.input(files=demoRunnerFilePath, inplace=True):
if (vStartMQTTEchoDemo in line) and ("//" not in line) and ("/*" not in line):
line = "//" + line
if vStartotaUpdateDemoTask in line:
line = line.replace("/* ", "")
line = line.replace(" */", "")
# print(line) will place an extra newline character in the file.
sys.stdout.write(line)
def __setTestRunnerForOtaDemo(self):
"""
Updates the aws_test_runner_config.h file to enable the OTA demo.
"""
self.__setIdentifierInFile(
{
'#define testrunnerFULL_TCP_ENABLED': '0',
'#define testrunnerOTA_END_TO_END_ENABLED': '1'
},
os.path.join(self._projectRootDir, self._boardPortablePath, 'common', 'config_files', 'aws_test_runner_config.h')
)
def setClientCredentialsForWifi(self, ssid, password, security):
"""
Updates the aws_clientcredential.h file for the wifi configurations defined in
the board.json
"""
self.__setIdentifierInFile(
{
'#define clientcredentialWIFI_SSID': '\"' + ssid + '\"',
'#define clientcredentialWIFI_PASSWORD': '\"' + password + '\"',
'#define clientcredentialWIFI_SECURITY': security
},
os.path.join(self._projectRootDir, OtaAfrProject.CLIENT_CREDENTIAL_PATH)
)
def setClientCredentialsForAwsIotEndpoint(self, awsIotEndpoint, awsIotEndpointPort = None):
"""
Updates aws_clientcredential.g for the AWS IoT endpoint defined in board.json
args:
awsIotEndpoint(str): Sets clientcredentialMQTT_BROKER_ENDPOINT[]
awsIotEndpointPort(str): Optionally sets clientcredentialMQTT_BROKER_PORT, if specified.
"""
self.__setIdentifierInFile(
{
'static const char clientcredentialMQTT_BROKER_ENDPOINT[] =': '\"' + awsIotEndpoint + '\";',
'#define clientcredentialMQTT_BROKER_PORT' : awsIotEndpointPort
},
os.path.join(self._projectRootDir, OtaAfrProject.CLIENT_CREDENTIAL_PATH)
)
def __setIdentifierInFile(self, prefixToValue, filePath):
"""
Set the indentied value, from prefix the input prefixToValue map, in the file path
specified.
If the value in the prefixToValue dictionary is None then the prefix is ignored if encountered.
Args:
prefixToValue (dict[str:str]): Identifier to value.
"""
for line in fileinput.input(files=filePath, inplace=True):
if any(line.startswith(prefix) for prefix in prefixToValue.keys()):
prefix = next(prefix for prefix in prefixToValue.keys() if line.startswith(prefix))
if prefixToValue[prefix] != None:
line = '{} {}\n'.format(prefix, prefixToValue[prefix])
# print(line) will place an extra newline character in the file.
sys.stdout.write(line)
def setMqttLogsOn(self):
"""Set the MQTT debug logs to on in aws_mqtt_config.h
"""
self.__setIdentifierInFile(
{ '#define mqttconfigENABLE_DEBUG_LOGS': '1' },
os.path.join(self._projectRootDir, self._boardPortablePath, 'common', 'config_files', 'aws_mqtt_config.h')
)
def setFreeRtosConfigNetworkInterface(self, networkInterface):
"""Set the configNETWORK_INTERFACE_TO_USE in FreeRTOSConfig.h to networkInterface.
Args:
networkInterface (int): The number of the network interface
"""
self.__setIdentifierInFile(
{
'#define configNETWORK_INTERFACE_TO_USE': str(networkInterface)
},
os.path.join(self._projectRootDir, self._boardPortablePath, 'common', 'config_files', 'FreeRTOSConfig.h')
)
def setClientCredentialForThingName(self, thingName):
"""Set aws_clientcredential.h with the input thingName.
"""
self.__setIdentifierInFile(
{ '#define clientcredentialIOT_THING_NAME': '\"' + thingName + '\"' },
os.path.join(self._projectRootDir, OtaAfrProject.CLIENT_CREDENTIAL_PATH)
)
def setClientCredentialKeys(self, certificate, privateKey):
"""Set the certificate and private key in aws_clientcredential_keys.h
"""
self.__setIdentifierInFile(
{
'#define keyCLIENT_CERTIFICATE_PEM': '\"' + certificate.replace('\n', '\\n') + '\"',
'#define keyCLIENT_PRIVATE_KEY_PEM': '\"' + privateKey.replace('\n', '\\n') + '\"'
},
os.path.join(self._projectRootDir, OtaAfrProject.CLIENT_CREDENTIAL_KEYS_PATH)
)
def setApplicationVersion(self, major, minor, bugfix):
"""Set aws_application_version.h with the input version.
"""
self.__setIdentifierInFile(
{
'#define APP_VERSION_MAJOR': major,
'#define APP_VERSION_MINOR': minor,
'#define APP_VERSION_BUILD': bugfix
},
os.path.join(self._projectRootDir, OtaAfrProject.APPLICATION_VERSION_PATH)
)
def setCodesignerCertificate(self, certificate):
"""Set aws_ota_codesigner_certificate.h with the certificate specified.
"""
codeSignerCertificatePath = os.path.join(self._projectRootDir, OtaAfrProject.OTA_CODESIGNER_CERTIFICATE_PATH)
signerCertificateTag = 'static const char signingcredentialSIGNING_CERTIFICATE_PEM[] = '
for line in fileinput.input(files=codeSignerCertificatePath, inplace=True):
if (signerCertificateTag in line):
line = '{} {}\n'.format(signerCertificateTag, '\"' + certificate.replace('\n', '\\n') + '\";')
sys.stdout.write(line)
def setOtaUpdateDemoForRootCA(self):
"""Sets the secure connection certificate in the MQTT connection parameters
in the OTA update demo.
"""
self.__setIdentifierInFile(
{
' xConnectParams.pcCertificate =': '( char* ) clientcredentialROOT_CA_PEM;',
' xConnectParams.ulCertificateSize =': 'sizeof(clientcredentialROOT_CA_PEM)-1;'
},
os.path.join(self._projectRootDir, '..', OtaAfrProject.OTA_UPDATE_DEMO_PATH)
)
def setOtaUpdateDemoForNullCertificate(self):
"""Sets the secure connection certificate in the MQTT connection parameters
in the OTA update demo.
"""
self.__setIdentifierInFile(
{
' xConnectParams.pcCertificate =': 'NULL;',
' xConnectParams.ulCertificateSize =': '0;'
},
os.path.join(self._projectRootDir, '..', OtaAfrProject.OTA_UPDATE_DEMO_PATH)
)
def setOtaDemoRunnerForSNIDisabled(self):
"""Disabled SNI by setting mqttagentURL_IS_IP_ADDRESS in the connection parameters.
"""
self.__setIdentifierInFile(
{
' xConnectParams.xFlags =': 'mqttagentREQUIRE_TLS | mqttagentURL_IS_IP_ADDRESS;'
},
os.path.join(self._projectRootDir, '..', OtaAfrProject.OTA_UPDATE_DEMO_PATH)
)
def addRootCAToClientCredentialKeys(self, certificate):
"""Adds the Beta endpoint's root Certificate Authority to aws_clientcredential_keys.h.
The root CA was retrieved with openssl s_client -showcerts -connect iotmoonraker.us-east-1.beta.funkypineapple.io:8883
"""
clientCertificateKeysPath = os.path.join(self._projectRootDir, OtaAfrProject.CLIENT_CREDENTIAL_KEYS_PATH)
rootCAPemTag = 'static const char clientcredentialROOT_CA_PEM[] ='
found = False
for line in fileinput.input(files=clientCertificateKeysPath, inplace=True):
if (rootCAPemTag in line):
line = '{} {}\n'.format(rootCAPemTag, ' \"' + certificate + '\";\n')
found = True
sys.stdout.write(line)
if not found:
with open(clientCertificateKeysPath, 'a') as f:
f.write('\nstatic const char clientcredentialROOT_CA_PEM[] = \"' + certificate + '\";\n') | tools/ota_e2e_tests/aws_ota_test/aws_ota_project.py | import fileinput
import sys
import subprocess
import os
class OtaAfrProject:
"""OtaAfrProject represents the Amazon FreeRTOS code base for OTA.
This class is used to update the Amazon FreeRTOS project for OTA.
Attributes:
_buildConfig(dict): Build configuration from 'build_config' field in board.json.
_projectRootDir(str): The root of the Amazon FreeRTOS project i.e. $AFR_ROOT/demos or $AFR_ROOT/tests.
_boardPortablePath(str): the vendor/board path of the Amazon FreeRTOS project.
Methods:
initializeOtaProject()
buildProject()
setClientCredentialForThingName(thingName)
setClientCredentialKeys(certificate, privateKey)
setApplicationVersion(major, minor, bugfix)
setCodesignerCertificate(codesignerCertificatePath)
__setDemoRunnerForOtaDemo()
setClientCredentialsForWifi()
setClientCredentialsForAwsIotEndpoint()
__setIdentifierInFile(prefixToValue, filePath)
Example:
from aws_ota_aws_agent import AwsIoTThing
otaProject = OtaAfrProject('C:/amazon-freertos', buildConfig)
otaProject.initializeOtaProject()
iotThing = AWSIoTThing('boardName')
otaProject.setClientCredentialForThingName(iotThing.thing_name)
otaProject.setClientCredentialKeys(iotThing.cert, iotThing.priv_key)
otaProject.buildProject()
"""
DEMO_RUNNER_PATH = 'common/demo_runner/aws_demo_runner.c'
CLIENT_CREDENTIAL_PATH = 'common/include/aws_clientcredential.h'
APPLICATION_VERSION_PATH = 'common/include/aws_application_version.h'
CLIENT_CREDENTIAL_KEYS_PATH ='common/include/aws_clientcredential_keys.h'
OTA_CODESIGNER_CERTIFICATE_PATH = 'common/include/aws_ota_codesigner_certificate.h'
OTA_UPDATE_DEMO_PATH = 'demos/common/ota/aws_ota_update_demo.c'
OTA_BOOTLOADER_CONFIG_PATH = 'demos/common/ota/bootloader/utility/user-config/ota-descriptor.config'
OTA_BOOTLOADER_CERTIFICATE_PATH = 'demos/common/ota/bootloader/utility/codesigner_cert_utility/aws_ota_codesigner_certificate.pem'
OTA_FACTORY_IMAGE_GENERATOR_PATH = 'demos/common/ota/bootloader/utility/factory_image_generator.py'
def __init__(self, projectRootDir, boardPortablePath, buildConfig):
self._buildConfig = buildConfig
self._projectRootDir = projectRootDir
self._boardPortablePath = boardPortablePath
self._bootloaderSequenceNumber = 0
def initializeOtaProject(self):
"""Initialize the Amazon FreeRTOS project for OTA.
"""
base = os.path.basename(self._projectRootDir)
if base == 'demos':
self.__setDemoRunnerForOtaDemo()
elif base == 'tests':
self.__setTestRunnerForOtaDemo()
else:
raise Exception('ERROR: Invalid project root \"{}\". The valid values are \"demos\" and \"tests\".'.format(base))
def generateFactoryImage(self):
# If this board uses the Amazon FreeRTOS reference bootlaoder, then we want to
# build and flash the factory image.
if self._buildConfig.get('use_reference_bootloader', False):
factoryImageGenCommand = \
'python ' + os.path.join(self._projectRootDir, '..', OtaAfrProject.OTA_FACTORY_IMAGE_GENERATOR_PATH) + ' ' + \
'-b ' + self._buildConfig['output'] + ' ' + \
'-p ' + self._buildConfig['bootloader_hardware_platform'] + ' ' + \
'-k ' + self._buildConfig['bootloader_private_key_path'] + ' ' + \
'-x ' + self._buildConfig['bootloader_output']
subprocess.call(
factoryImageGenCommand,
shell=True
)
def buildProject(self):
"""Build the Amazon FreeRTOS project represented by this object.
"""
# Update the bootloader sequence number for every new build
self.__incrementBootloaderSequenceNumber()
# Save the system path to restore.
system_path = os.environ['PATH']
# Add the tool_paths to the system PATH
for path in self._buildConfig['tool_paths']:
os.environ['PATH'] += ';' + path
buildCommands = self._buildConfig['commands']
print('Building project {}...'.format(self._buildConfig['project_dir']))
for command in buildCommands:
command = command.format(**self._buildConfig)
subprocess.Popen(command + ' >> build_output.txt 2>&1', shell=True).wait()
output = self._buildConfig['output']
if not os.path.exists(output):
print("ERROR: Could not find the output binary, the build might have failed.")
raise Exception("Error building project check build_output.txt")
print('Build finished, output: {}'.format(self._buildConfig['output']))
# Restore the system path
os.environ['PATH'] = system_path
def __incrementBootloaderSequenceNumber(self):
self._bootloaderSequenceNumber += 1
self.__setBootloaderSequenceNumber(self._bootloaderSequenceNumber)
def __setBootloaderSequenceNumber(self, number):
self.__setIdentifierInFile(
{
'SEQUENCE_NUMBER': '= ' + str(number)
},
os.path.join(self._projectRootDir, '..', OtaAfrProject.OTA_BOOTLOADER_CONFIG_PATH)
)
def copyCodesignerCertificateToBootloader(self, certificate):
"""Copies the input certificate to a file named: aws_ota_codesigner_certificate.pem under
demos/common/ota/bootloader/utility/codesigner_cert_utility.
"""
with open(os.path.join(self._projectRootDir, '..', OtaAfrProject.OTA_BOOTLOADER_CERTIFICATE_PATH), 'w') as f:
f.write(certificate)
def __setDemoRunnerForOtaDemo(self):
"""
Updates the aws_demo_runner.c to disable the default MQTT Echo demo and enable the OTA
update demo.
"""
demoRunnerFilePath = os.path.join(self._projectRootDir, OtaAfrProject.DEMO_RUNNER_PATH)
vStartMQTTEchoDemo = "vStartMQTTEchoDemo"
vStartotaUpdateDemoTask = "vStartOTAUpdateDemoTask"
for line in fileinput.input(files=demoRunnerFilePath, inplace=True):
if (vStartMQTTEchoDemo in line) and ("//" not in line) and ("/*" not in line):
line = "//" + line
if vStartotaUpdateDemoTask in line:
line = line.replace("/* ", "")
line = line.replace(" */", "")
# print(line) will place an extra newline character in the file.
sys.stdout.write(line)
def __setTestRunnerForOtaDemo(self):
"""
Updates the aws_test_runner_config.h file to enable the OTA demo.
"""
self.__setIdentifierInFile(
{
'#define testrunnerFULL_TCP_ENABLED': '0',
'#define testrunnerOTA_END_TO_END_ENABLED': '1'
},
os.path.join(self._projectRootDir, self._boardPortablePath, 'common', 'config_files', 'aws_test_runner_config.h')
)
def setClientCredentialsForWifi(self, ssid, password, security):
"""
Updates the aws_clientcredential.h file for the wifi configurations defined in
the board.json
"""
self.__setIdentifierInFile(
{
'#define clientcredentialWIFI_SSID': '\"' + ssid + '\"',
'#define clientcredentialWIFI_PASSWORD': '\"' + password + '\"',
'#define clientcredentialWIFI_SECURITY': security
},
os.path.join(self._projectRootDir, OtaAfrProject.CLIENT_CREDENTIAL_PATH)
)
def setClientCredentialsForAwsIotEndpoint(self, awsIotEndpoint, awsIotEndpointPort = None):
"""
Updates aws_clientcredential.g for the AWS IoT endpoint defined in board.json
args:
awsIotEndpoint(str): Sets clientcredentialMQTT_BROKER_ENDPOINT[]
awsIotEndpointPort(str): Optionally sets clientcredentialMQTT_BROKER_PORT, if specified.
"""
self.__setIdentifierInFile(
{
'static const char clientcredentialMQTT_BROKER_ENDPOINT[] =': '\"' + awsIotEndpoint + '\";',
'#define clientcredentialMQTT_BROKER_PORT' : awsIotEndpointPort
},
os.path.join(self._projectRootDir, OtaAfrProject.CLIENT_CREDENTIAL_PATH)
)
def __setIdentifierInFile(self, prefixToValue, filePath):
"""
Set the indentied value, from prefix the input prefixToValue map, in the file path
specified.
If the value in the prefixToValue dictionary is None then the prefix is ignored if encountered.
Args:
prefixToValue (dict[str:str]): Identifier to value.
"""
for line in fileinput.input(files=filePath, inplace=True):
if any(line.startswith(prefix) for prefix in prefixToValue.keys()):
prefix = next(prefix for prefix in prefixToValue.keys() if line.startswith(prefix))
if prefixToValue[prefix] != None:
line = '{} {}\n'.format(prefix, prefixToValue[prefix])
# print(line) will place an extra newline character in the file.
sys.stdout.write(line)
def setMqttLogsOn(self):
"""Set the MQTT debug logs to on in aws_mqtt_config.h
"""
self.__setIdentifierInFile(
{ '#define mqttconfigENABLE_DEBUG_LOGS': '1' },
os.path.join(self._projectRootDir, self._boardPortablePath, 'common', 'config_files', 'aws_mqtt_config.h')
)
def setFreeRtosConfigNetworkInterface(self, networkInterface):
"""Set the configNETWORK_INTERFACE_TO_USE in FreeRTOSConfig.h to networkInterface.
Args:
networkInterface (int): The number of the network interface
"""
self.__setIdentifierInFile(
{
'#define configNETWORK_INTERFACE_TO_USE': str(networkInterface)
},
os.path.join(self._projectRootDir, self._boardPortablePath, 'common', 'config_files', 'FreeRTOSConfig.h')
)
def setClientCredentialForThingName(self, thingName):
"""Set aws_clientcredential.h with the input thingName.
"""
self.__setIdentifierInFile(
{ '#define clientcredentialIOT_THING_NAME': '\"' + thingName + '\"' },
os.path.join(self._projectRootDir, OtaAfrProject.CLIENT_CREDENTIAL_PATH)
)
def setClientCredentialKeys(self, certificate, privateKey):
"""Set the certificate and private key in aws_clientcredential_keys.h
"""
self.__setIdentifierInFile(
{
'#define keyCLIENT_CERTIFICATE_PEM': '\"' + certificate.replace('\n', '\\n') + '\"',
'#define keyCLIENT_PRIVATE_KEY_PEM': '\"' + privateKey.replace('\n', '\\n') + '\"'
},
os.path.join(self._projectRootDir, OtaAfrProject.CLIENT_CREDENTIAL_KEYS_PATH)
)
def setApplicationVersion(self, major, minor, bugfix):
"""Set aws_application_version.h with the input version.
"""
self.__setIdentifierInFile(
{
'#define APP_VERSION_MAJOR': major,
'#define APP_VERSION_MINOR': minor,
'#define APP_VERSION_BUILD': bugfix
},
os.path.join(self._projectRootDir, OtaAfrProject.APPLICATION_VERSION_PATH)
)
def setCodesignerCertificate(self, certificate):
"""Set aws_ota_codesigner_certificate.h with the certificate specified.
"""
codeSignerCertificatePath = os.path.join(self._projectRootDir, OtaAfrProject.OTA_CODESIGNER_CERTIFICATE_PATH)
signerCertificateTag = 'static const char signingcredentialSIGNING_CERTIFICATE_PEM[] = '
for line in fileinput.input(files=codeSignerCertificatePath, inplace=True):
if (signerCertificateTag in line):
line = '{} {}\n'.format(signerCertificateTag, '\"' + certificate.replace('\n', '\\n') + '\";')
sys.stdout.write(line)
def setOtaUpdateDemoForRootCA(self):
"""Sets the secure connection certificate in the MQTT connection parameters
in the OTA update demo.
"""
self.__setIdentifierInFile(
{
' xConnectParams.pcCertificate =': '( char* ) clientcredentialROOT_CA_PEM;',
' xConnectParams.ulCertificateSize =': 'sizeof(clientcredentialROOT_CA_PEM)-1;'
},
os.path.join(self._projectRootDir, '..', OtaAfrProject.OTA_UPDATE_DEMO_PATH)
)
def setOtaUpdateDemoForNullCertificate(self):
"""Sets the secure connection certificate in the MQTT connection parameters
in the OTA update demo.
"""
self.__setIdentifierInFile(
{
' xConnectParams.pcCertificate =': 'NULL;',
' xConnectParams.ulCertificateSize =': '0;'
},
os.path.join(self._projectRootDir, '..', OtaAfrProject.OTA_UPDATE_DEMO_PATH)
)
def setOtaDemoRunnerForSNIDisabled(self):
"""Disabled SNI by setting mqttagentURL_IS_IP_ADDRESS in the connection parameters.
"""
self.__setIdentifierInFile(
{
' xConnectParams.xFlags =': 'mqttagentREQUIRE_TLS | mqttagentURL_IS_IP_ADDRESS;'
},
os.path.join(self._projectRootDir, '..', OtaAfrProject.OTA_UPDATE_DEMO_PATH)
)
def addRootCAToClientCredentialKeys(self, certificate):
"""Adds the Beta endpoint's root Certificate Authority to aws_clientcredential_keys.h.
The root CA was retrieved with openssl s_client -showcerts -connect iotmoonraker.us-east-1.beta.funkypineapple.io:8883
"""
clientCertificateKeysPath = os.path.join(self._projectRootDir, OtaAfrProject.CLIENT_CREDENTIAL_KEYS_PATH)
rootCAPemTag = 'static const char clientcredentialROOT_CA_PEM[] ='
found = False
for line in fileinput.input(files=clientCertificateKeysPath, inplace=True):
if (rootCAPemTag in line):
line = '{} {}\n'.format(rootCAPemTag, ' \"' + certificate + '\";\n')
found = True
sys.stdout.write(line)
if not found:
with open(clientCertificateKeysPath, 'a') as f:
f.write('\nstatic const char clientcredentialROOT_CA_PEM[] = \"' + certificate + '\";\n') | 0.295738 | 0.075687 |
import json
import os
import sys
import pandas.io.sql as psql
import requests
crypto_tools_dir = os.getcwd().split('/scripts/')[0] + '/scripts/'
sys.path.append(crypto_tools_dir)
from crypto_tools import *
class PopulateCryptoCoinone(object):
"""
"""
def __init__(self):
"""
"""
self.port = 3306
self.host = "172.16.31.10"
self.database_name = 'crypto_test'
self.user = 'toby'
self.password = '<PASSWORD>$'
self.database = DatabaseConnect(self.host, self.database_name, self.user, self.password, self.port)
self.database.database_connect()
self.get_coinone_exchange_id()
def get_coinone_exchange_id(self):
"""
"""
sql_str = """SELECT id FROM crypto_test.exchange
WHERE name = 'coinone' """
results = psql.read_sql(sql_str,con = self.database.mydb)
self.exchange_id = results['id'].loc[0]
def get_coinone_asset_pairs_lookup(self):
"""
"""
sql_str = """SELECT apl.name,apl.id AS asset_pairs_lookup_id
FROM crypto_test.asset_pairs_lookup apl
INNER JOIN crypto_test.exchange e ON e.id = apl.exchange_id
WHERE e.name = 'coinone'"""
results = psql.read_sql(sql_str,con = self.database.mydb)
asset_pairs_lookup_dict = {}
self.asset_pairs_list = results['name'].tolist()
self.asset_pairs_str = ','.join(self.asset_pairs_list)
print (self.asset_pairs_str)
for ind,row in results.T.iteritems():
name = row['name']
asset_pairs_lookup_dict[name] = row['asset_pairs_lookup_id']
self.asset_pairs_lookup_dict = asset_pairs_lookup_dict
def populate_coinone_data(self):
"""Please note that there is no server_time for coinone so default is order_time,
which is universal across trades
"""
self.get_coinone_asset_pairs_lookup()
for coinone_asset_pair in self.asset_pairs_list:
print (coinone_asset_pair)
url = """https://api.coinone.co.kr/orderbook?currency=%s"""%(coinone_asset_pair)
all_response = requests.get(url)
all_json = all_response.text
all_json_dict = json.loads(all_json)
timestamp = all_json_dict['timestamp']
#coinone timestamp, no order time of order
order_time = datetime.fromtimestamp(int(timestamp)).strftime('%Y-%m-%d %H:%M:%S')
bids = all_json_dict['bid']
asks = all_json_dict['ask']
asset_pairs_lookup_id = self.asset_pairs_lookup_dict[coinone_asset_pair]
bid_ask_list = [[1,bids],[2,asks]]
for order_type in bid_ask_list:
order_type_id = order_type[0]
x = 0
for order in order_type[1]:
x = x + 1
price = order['price']
quantity = order['qty']
#need to remove trailing zeros before and after decimal
new_price = '{0:g}'.format(float(price))
new_quantity = '{0:g}'.format(float(quantity))
ut = datetime.now()
sql_str = """INSERT IGNORE INTO crypto_test.order_book(asset_pairs_lookup_id,order_type_id,price,quantity,order_time,server_time,ut)
VALUES(%s,%s,%s,%s,"%s","%s","%s")
"""%(asset_pairs_lookup_id,order_type_id,float(new_price),float(quantity),order_time,order_time,ut)
self.database.cursor.execute(sql_str)
try:
self.database.mydb.commit()
except:
self.database.mydb.rollback()
if x < 6:
ut = datetime.now()
ob_last_row_id = self.database.cursor.lastrowid
sql_str = """INSERT IGNORE INTO crypto_test.order_book_live(order_book_id,ut)
VALUES(%s,"%s")
"""%(ob_last_row_id,ut)
self.database.cursor.execute(sql_str)
try:
self.database.mydb.commit()
except:
self.database.mydb.rollback()
def main():
"""
"""
PC = PopulateCryptoCoinone()
PC.populate_coinone_data()
if __name__=="__main__":
main() | scripts/populate_database/populate_coinone.py | import json
import os
import sys
import pandas.io.sql as psql
import requests
crypto_tools_dir = os.getcwd().split('/scripts/')[0] + '/scripts/'
sys.path.append(crypto_tools_dir)
from crypto_tools import *
class PopulateCryptoCoinone(object):
"""
"""
def __init__(self):
"""
"""
self.port = 3306
self.host = "172.16.31.10"
self.database_name = 'crypto_test'
self.user = 'toby'
self.password = '<PASSWORD>$'
self.database = DatabaseConnect(self.host, self.database_name, self.user, self.password, self.port)
self.database.database_connect()
self.get_coinone_exchange_id()
def get_coinone_exchange_id(self):
"""
"""
sql_str = """SELECT id FROM crypto_test.exchange
WHERE name = 'coinone' """
results = psql.read_sql(sql_str,con = self.database.mydb)
self.exchange_id = results['id'].loc[0]
def get_coinone_asset_pairs_lookup(self):
"""
"""
sql_str = """SELECT apl.name,apl.id AS asset_pairs_lookup_id
FROM crypto_test.asset_pairs_lookup apl
INNER JOIN crypto_test.exchange e ON e.id = apl.exchange_id
WHERE e.name = 'coinone'"""
results = psql.read_sql(sql_str,con = self.database.mydb)
asset_pairs_lookup_dict = {}
self.asset_pairs_list = results['name'].tolist()
self.asset_pairs_str = ','.join(self.asset_pairs_list)
print (self.asset_pairs_str)
for ind,row in results.T.iteritems():
name = row['name']
asset_pairs_lookup_dict[name] = row['asset_pairs_lookup_id']
self.asset_pairs_lookup_dict = asset_pairs_lookup_dict
def populate_coinone_data(self):
"""Please note that there is no server_time for coinone so default is order_time,
which is universal across trades
"""
self.get_coinone_asset_pairs_lookup()
for coinone_asset_pair in self.asset_pairs_list:
print (coinone_asset_pair)
url = """https://api.coinone.co.kr/orderbook?currency=%s"""%(coinone_asset_pair)
all_response = requests.get(url)
all_json = all_response.text
all_json_dict = json.loads(all_json)
timestamp = all_json_dict['timestamp']
#coinone timestamp, no order time of order
order_time = datetime.fromtimestamp(int(timestamp)).strftime('%Y-%m-%d %H:%M:%S')
bids = all_json_dict['bid']
asks = all_json_dict['ask']
asset_pairs_lookup_id = self.asset_pairs_lookup_dict[coinone_asset_pair]
bid_ask_list = [[1,bids],[2,asks]]
for order_type in bid_ask_list:
order_type_id = order_type[0]
x = 0
for order in order_type[1]:
x = x + 1
price = order['price']
quantity = order['qty']
#need to remove trailing zeros before and after decimal
new_price = '{0:g}'.format(float(price))
new_quantity = '{0:g}'.format(float(quantity))
ut = datetime.now()
sql_str = """INSERT IGNORE INTO crypto_test.order_book(asset_pairs_lookup_id,order_type_id,price,quantity,order_time,server_time,ut)
VALUES(%s,%s,%s,%s,"%s","%s","%s")
"""%(asset_pairs_lookup_id,order_type_id,float(new_price),float(quantity),order_time,order_time,ut)
self.database.cursor.execute(sql_str)
try:
self.database.mydb.commit()
except:
self.database.mydb.rollback()
if x < 6:
ut = datetime.now()
ob_last_row_id = self.database.cursor.lastrowid
sql_str = """INSERT IGNORE INTO crypto_test.order_book_live(order_book_id,ut)
VALUES(%s,"%s")
"""%(ob_last_row_id,ut)
self.database.cursor.execute(sql_str)
try:
self.database.mydb.commit()
except:
self.database.mydb.rollback()
def main():
"""
"""
PC = PopulateCryptoCoinone()
PC.populate_coinone_data()
if __name__=="__main__":
main() | 0.130729 | 0.079997 |
import os
import yaml
from launch import LaunchDescription
from launch.actions import ExecuteProcess
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory
import xacro
def load_file(package_name, file_path):
package_path = get_package_share_directory(package_name)
absolute_file_path = os.path.join(package_path, file_path)
try:
with open(absolute_file_path, "r") as file:
return file.read()
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
return None
def load_yaml(package_name, file_path):
package_path = get_package_share_directory(package_name)
absolute_file_path = os.path.join(package_path, file_path)
try:
with open(absolute_file_path, "r") as file:
return yaml.safe_load(file)
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
return None
def generate_launch_description():
# Get URDF and SRDF
robot_description_config = xacro.process_file(
os.path.join(
get_package_share_directory("moveit_resources_panda_moveit_config"),
"config",
"panda.urdf.xacro",
)
)
robot_description = {"robot_description": robot_description_config.toxml()}
robot_description_semantic_config = load_file(
"moveit_resources_panda_moveit_config", "config/panda.srdf"
)
robot_description_semantic = {
"robot_description_semantic": robot_description_semantic_config
}
# Get parameters for the Pose Tracking node
pose_tracking_yaml = load_yaml("moveit_servo", "config/pose_tracking_settings.yaml")
pose_tracking_params = {"moveit_servo": pose_tracking_yaml}
# Get parameters for the Servo node
servo_yaml = load_yaml(
"moveit_servo", "config/panda_simulated_config_pose_tracking.yaml"
)
servo_params = {"moveit_servo": servo_yaml}
kinematics_yaml = load_yaml(
"moveit_resources_panda_moveit_config", "config/kinematics.yaml"
)
joint_limits_yaml = {
"robot_description_planning": load_yaml(
"moveit_resources_panda_moveit_config", "config/joint_limits.yaml"
)
}
# RViz
rviz_config_file = (
get_package_share_directory("moveit_servo")
+ "/config/demo_rviz_pose_tracking.rviz"
)
rviz_node = Node(
package="rviz2",
executable="rviz2",
name="rviz2",
# prefix=['xterm -e gdb -ex run --args'],
output="log",
arguments=["-d", rviz_config_file],
parameters=[
robot_description,
robot_description_semantic,
kinematics_yaml,
joint_limits_yaml,
],
)
# Publishes tf's for the robot
robot_state_publisher = Node(
package="robot_state_publisher",
executable="robot_state_publisher",
output="screen",
parameters=[robot_description],
)
# A node to publish world -> panda_link0 transform
static_tf = Node(
package="tf2_ros",
executable="static_transform_publisher",
name="static_transform_publisher",
output="log",
arguments=["0.0", "0.0", "0.0", "0.0", "0.0", "0.0", "world", "panda_link0"],
)
pose_tracking_node = Node(
package="moveit_servo",
executable="servo_pose_tracking_demo",
# prefix=['xterm -e gdb -ex run --args'],
output="screen",
parameters=[
robot_description,
robot_description_semantic,
kinematics_yaml,
pose_tracking_params,
servo_params,
joint_limits_yaml,
],
)
# ros2_control using FakeSystem as hardware
ros2_controllers_path = os.path.join(
get_package_share_directory("moveit_resources_panda_moveit_config"),
"config",
"panda_ros_controllers.yaml",
)
ros2_control_node = Node(
package="controller_manager",
executable="ros2_control_node",
parameters=[robot_description, ros2_controllers_path],
output={
"stdout": "screen",
"stderr": "screen",
},
)
# Load controllers
load_controllers = []
for controller in ["panda_arm_controller", "joint_state_broadcaster"]:
load_controllers += [
ExecuteProcess(
cmd=["ros2 run controller_manager spawner {}".format(controller)],
shell=True,
output="screen",
)
]
return LaunchDescription(
[
rviz_node,
static_tf,
pose_tracking_node,
ros2_control_node,
robot_state_publisher,
]
+ load_controllers
) | moveit_ros/moveit_servo/launch/pose_tracking_example.launch.py | import os
import yaml
from launch import LaunchDescription
from launch.actions import ExecuteProcess
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory
import xacro
def load_file(package_name, file_path):
package_path = get_package_share_directory(package_name)
absolute_file_path = os.path.join(package_path, file_path)
try:
with open(absolute_file_path, "r") as file:
return file.read()
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
return None
def load_yaml(package_name, file_path):
package_path = get_package_share_directory(package_name)
absolute_file_path = os.path.join(package_path, file_path)
try:
with open(absolute_file_path, "r") as file:
return yaml.safe_load(file)
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
return None
def generate_launch_description():
# Get URDF and SRDF
robot_description_config = xacro.process_file(
os.path.join(
get_package_share_directory("moveit_resources_panda_moveit_config"),
"config",
"panda.urdf.xacro",
)
)
robot_description = {"robot_description": robot_description_config.toxml()}
robot_description_semantic_config = load_file(
"moveit_resources_panda_moveit_config", "config/panda.srdf"
)
robot_description_semantic = {
"robot_description_semantic": robot_description_semantic_config
}
# Get parameters for the Pose Tracking node
pose_tracking_yaml = load_yaml("moveit_servo", "config/pose_tracking_settings.yaml")
pose_tracking_params = {"moveit_servo": pose_tracking_yaml}
# Get parameters for the Servo node
servo_yaml = load_yaml(
"moveit_servo", "config/panda_simulated_config_pose_tracking.yaml"
)
servo_params = {"moveit_servo": servo_yaml}
kinematics_yaml = load_yaml(
"moveit_resources_panda_moveit_config", "config/kinematics.yaml"
)
joint_limits_yaml = {
"robot_description_planning": load_yaml(
"moveit_resources_panda_moveit_config", "config/joint_limits.yaml"
)
}
# RViz
rviz_config_file = (
get_package_share_directory("moveit_servo")
+ "/config/demo_rviz_pose_tracking.rviz"
)
rviz_node = Node(
package="rviz2",
executable="rviz2",
name="rviz2",
# prefix=['xterm -e gdb -ex run --args'],
output="log",
arguments=["-d", rviz_config_file],
parameters=[
robot_description,
robot_description_semantic,
kinematics_yaml,
joint_limits_yaml,
],
)
# Publishes tf's for the robot
robot_state_publisher = Node(
package="robot_state_publisher",
executable="robot_state_publisher",
output="screen",
parameters=[robot_description],
)
# A node to publish world -> panda_link0 transform
static_tf = Node(
package="tf2_ros",
executable="static_transform_publisher",
name="static_transform_publisher",
output="log",
arguments=["0.0", "0.0", "0.0", "0.0", "0.0", "0.0", "world", "panda_link0"],
)
pose_tracking_node = Node(
package="moveit_servo",
executable="servo_pose_tracking_demo",
# prefix=['xterm -e gdb -ex run --args'],
output="screen",
parameters=[
robot_description,
robot_description_semantic,
kinematics_yaml,
pose_tracking_params,
servo_params,
joint_limits_yaml,
],
)
# ros2_control using FakeSystem as hardware
ros2_controllers_path = os.path.join(
get_package_share_directory("moveit_resources_panda_moveit_config"),
"config",
"panda_ros_controllers.yaml",
)
ros2_control_node = Node(
package="controller_manager",
executable="ros2_control_node",
parameters=[robot_description, ros2_controllers_path],
output={
"stdout": "screen",
"stderr": "screen",
},
)
# Load controllers
load_controllers = []
for controller in ["panda_arm_controller", "joint_state_broadcaster"]:
load_controllers += [
ExecuteProcess(
cmd=["ros2 run controller_manager spawner {}".format(controller)],
shell=True,
output="screen",
)
]
return LaunchDescription(
[
rviz_node,
static_tf,
pose_tracking_node,
ros2_control_node,
robot_state_publisher,
]
+ load_controllers
) | 0.580114 | 0.230216 |
import torch
import torch.nn as nn
import copy
import time
import shutil
import operator
import numpy as np
import random
import math
from PIL import Image, ImageOps
from torchvision import transforms
class AverageMeter():
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def precision(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
"""
Transform class to randomly rotate images
"""
class RandomRotate(object):
def __call__(self, img):
size = img.size
angle = random.randint(-10, 10)
img = img.rotate(angle, resample=Image.BICUBIC)
img = img.resize(size, Image.ANTIALIAS)
return img
class TenCrop(object):
def __init__(self, size, opt):
self.size = size
self.opt = opt
def __call__(self, img):
centerCrop = transforms.CenterCrop(self.size)
toPILImage = transforms.ToPILImage()
toTensor = transforms.ToTensor()
if self.opt.dataset == 'tuberlin':
normalize = transforms.Normalize(mean=[0.06,], std=[0.93])
if self.opt.dataset == 'sketchyrecognition':
normalize = transforms.Normalize(mean=[0.0465,], std=[0.9])
w, h = img.size(2), img.size(1)
temp_output = []
output = torch.FloatTensor(10, img.size(0), self.size, self.size)
img = toPILImage(img)
for img_cur in [img, img.transpose(Image.FLIP_LEFT_RIGHT)]:
temp_output.append(centerCrop(img_cur))
temp_output.append(img_cur.crop([0, 0, self.size, self.size]))
temp_output.append(img_cur.crop([w-self.size, 0, w, self.size]))
temp_output.append(img_cur.crop([0, h-self.size, self.size, h]))
temp_output.append(img_cur.crop([w-self.size, h-self.size, w, h]))
for img_idx in range(10):
img_cur = temp_output[img_idx]
img_cur = toTensor(img_cur)
img_cur = normalize(img_cur)
output[img_idx] = img_cur.view(img_cur.size(0), img_cur.size(1), img_cur.size(2))
return output
def adjust_learning_rate(opt, optimizer, epoch):
epoch = copy.deepcopy(epoch)
lr = opt.maxlr
if opt.learningratescheduler == 'decayschedular':
while epoch >= opt.decayinterval:
lr = lr*opt.decaylevel
epoch = epoch - opt.decayinterval
elif opt.learningratescheduler == 'imagenetschedular':
lr = lr * (0.1 ** (epoch // 30))
elif opt.learningratescheduler == 'cifarschedular':
lr = lr * (0.1 ** (epoch // 150)) * (0.1 ** (epoch // 225))
lr = max(lr,opt.minlr)
opt.lr = lr
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def get_mean_and_std(dataloader):
'''Compute the mean and std value of dataset.'''
mean = torch.zeros(3)
std = torch.zeros(3)
len_dataset = 0
print('==> Computing mean and std..')
for inputs, targets in dataloader:
len_dataset += 1
for i in range(len(inputs[0])):
mean[i] += inputs[:,i,:,:].mean()
std[i] += inputs[:,i,:,:].std()
mean.div_(len_dataset)
std.div_(len_dataset)
return mean, std
def weights_init(model, opt):
'''Add your favourite weight initializations.'''
for m in model.modules():
if isinstance(m, nn.Conv2d):
m.weight.data = nn.init.kaiming_normal(m.weight.data, mode='fan_out')
#c = math.sqrt(2.0 / (m.kernel_size[0] * m.kernel_size[1] * m.out_channels))
#m.weight.data = torch.randn(m.weight.data.size()).cuda() * c
if m.bias is not None:
nn.init.constant(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
if m.affine == True:
nn.init.constant(m.weight, 1)
nn.init.constant(m.bias, 0)
elif isinstance(m, nn.Linear):
m.weight.data = nn.init.kaiming_normal(m.weight.data, mode='fan_out')
#c = math.sqrt(2.0 / m.weight.data.size(1));
#m.weight.data = torch.randn(m.weight.data.size()).cuda() * c
# TODO: Check bias
if m.bias is not None:
nn.init.constant(m.bias, 0) | code/utils.py | import torch
import torch.nn as nn
import copy
import time
import shutil
import operator
import numpy as np
import random
import math
from PIL import Image, ImageOps
from torchvision import transforms
class AverageMeter():
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
def precision(output, target, topk=(1,)):
"""Computes the precision@k for the specified values of k"""
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
res.append(correct_k.mul_(100.0 / batch_size))
return res
"""
Transform class to randomly rotate images
"""
class RandomRotate(object):
def __call__(self, img):
size = img.size
angle = random.randint(-10, 10)
img = img.rotate(angle, resample=Image.BICUBIC)
img = img.resize(size, Image.ANTIALIAS)
return img
class TenCrop(object):
def __init__(self, size, opt):
self.size = size
self.opt = opt
def __call__(self, img):
centerCrop = transforms.CenterCrop(self.size)
toPILImage = transforms.ToPILImage()
toTensor = transforms.ToTensor()
if self.opt.dataset == 'tuberlin':
normalize = transforms.Normalize(mean=[0.06,], std=[0.93])
if self.opt.dataset == 'sketchyrecognition':
normalize = transforms.Normalize(mean=[0.0465,], std=[0.9])
w, h = img.size(2), img.size(1)
temp_output = []
output = torch.FloatTensor(10, img.size(0), self.size, self.size)
img = toPILImage(img)
for img_cur in [img, img.transpose(Image.FLIP_LEFT_RIGHT)]:
temp_output.append(centerCrop(img_cur))
temp_output.append(img_cur.crop([0, 0, self.size, self.size]))
temp_output.append(img_cur.crop([w-self.size, 0, w, self.size]))
temp_output.append(img_cur.crop([0, h-self.size, self.size, h]))
temp_output.append(img_cur.crop([w-self.size, h-self.size, w, h]))
for img_idx in range(10):
img_cur = temp_output[img_idx]
img_cur = toTensor(img_cur)
img_cur = normalize(img_cur)
output[img_idx] = img_cur.view(img_cur.size(0), img_cur.size(1), img_cur.size(2))
return output
def adjust_learning_rate(opt, optimizer, epoch):
epoch = copy.deepcopy(epoch)
lr = opt.maxlr
if opt.learningratescheduler == 'decayschedular':
while epoch >= opt.decayinterval:
lr = lr*opt.decaylevel
epoch = epoch - opt.decayinterval
elif opt.learningratescheduler == 'imagenetschedular':
lr = lr * (0.1 ** (epoch // 30))
elif opt.learningratescheduler == 'cifarschedular':
lr = lr * (0.1 ** (epoch // 150)) * (0.1 ** (epoch // 225))
lr = max(lr,opt.minlr)
opt.lr = lr
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def get_mean_and_std(dataloader):
'''Compute the mean and std value of dataset.'''
mean = torch.zeros(3)
std = torch.zeros(3)
len_dataset = 0
print('==> Computing mean and std..')
for inputs, targets in dataloader:
len_dataset += 1
for i in range(len(inputs[0])):
mean[i] += inputs[:,i,:,:].mean()
std[i] += inputs[:,i,:,:].std()
mean.div_(len_dataset)
std.div_(len_dataset)
return mean, std
def weights_init(model, opt):
'''Add your favourite weight initializations.'''
for m in model.modules():
if isinstance(m, nn.Conv2d):
m.weight.data = nn.init.kaiming_normal(m.weight.data, mode='fan_out')
#c = math.sqrt(2.0 / (m.kernel_size[0] * m.kernel_size[1] * m.out_channels))
#m.weight.data = torch.randn(m.weight.data.size()).cuda() * c
if m.bias is not None:
nn.init.constant(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
if m.affine == True:
nn.init.constant(m.weight, 1)
nn.init.constant(m.bias, 0)
elif isinstance(m, nn.Linear):
m.weight.data = nn.init.kaiming_normal(m.weight.data, mode='fan_out')
#c = math.sqrt(2.0 / m.weight.data.size(1));
#m.weight.data = torch.randn(m.weight.data.size()).cuda() * c
# TODO: Check bias
if m.bias is not None:
nn.init.constant(m.bias, 0) | 0.743913 | 0.375477 |
import json
import falcon
from mock import PropertyMock, MagicMock, patch
from ddt import ddt, data, unpack
from tests import RestTestBase
from monitorrent.rest.settings_proxy import SettingsProxyEnabled, SettingsProxy
from monitorrent.settings_manager import SettingsManager
@ddt
class SettingsProxyEnabledTest(RestTestBase):
api_url = '/api/settings/proxy/enabled'
@data(True, False)
def test_get_is_proxy_enabled(self, value):
settings_manager = SettingsManager()
get_is_proxy_enabled_mock = MagicMock(return_value=value)
settings_manager.get_is_proxy_enabled = get_is_proxy_enabled_mock
settings_proxy_enabled_resource = SettingsProxyEnabled(settings_manager)
self.api.add_route(self.api_url, settings_proxy_enabled_resource)
body = self.simulate_request(self.api_url, decode='utf-8')
self.assertEqual(self.srmock.status, falcon.HTTP_OK)
self.assertTrue('application/json' in self.srmock.headers_dict['Content-Type'])
result = json.loads(body)
self.assertEqual(result, {'enabled': value})
get_is_proxy_enabled_mock.assert_called_once_with()
@data(True, False)
def test_set_is_proxy_enabled(self, value):
settings_manager = SettingsManager()
set_is_proxy_enabled_mock = MagicMock()
settings_manager.set_is_proxy_enabled = set_is_proxy_enabled_mock
settings_proxy_enabled_resource = SettingsProxyEnabled(settings_manager)
self.api.add_route(self.api_url, settings_proxy_enabled_resource)
request = {'enabled': value}
self.simulate_request(self.api_url, method="PUT", body=json.dumps(request))
self.assertEqual(self.srmock.status, falcon.HTTP_NO_CONTENT)
set_is_proxy_enabled_mock.assert_called_once_with(value)
@data({'enabled': 'random_text'},
{'enabled': 'True'},
{'wrong_param': 'Value'},
None)
def test_bad_request(self, body):
settings_manager = SettingsManager()
settings_proxy_enabled_resource = SettingsProxyEnabled(settings_manager)
self.api.add_route(self.api_url, settings_proxy_enabled_resource)
self.simulate_request(self.api_url, method="PUT", body=json.dumps(body) if body else None)
self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
@ddt
class SettingsProxyTest(RestTestBase):
api_url = '/api/settings/proxy'
@data(('http', 'http://1.1.1.1:8888'), ('https', 'http://2.2.2.2:8888'))
@unpack
def test_get_proxy(self, key, proxy):
settings_manager = SettingsManager()
get_proxy_mock = MagicMock(return_value=proxy)
settings_manager.get_proxy = get_proxy_mock
settings_proxy_resource = SettingsProxy(settings_manager)
self.api.add_route(self.api_url, settings_proxy_resource)
body = self.simulate_request(self.api_url, decode='utf-8', query_string="key="+key)
self.assertEqual(self.srmock.status, falcon.HTTP_OK)
self.assertTrue('application/json' in self.srmock.headers_dict['Content-Type'])
result = json.loads(body)
self.assertEqual(result, {'url': proxy})
get_proxy_mock.assert_called_once_with(key)
def test_get_proxy_not_found(self):
settings_manager = SettingsManager()
get_proxy_mock = MagicMock(return_value=None)
settings_manager.get_proxy = get_proxy_mock
settings_proxy_resource = SettingsProxy(settings_manager)
self.api.add_route(self.api_url, settings_proxy_resource)
self.simulate_request(self.api_url, decode='utf-8', query_string="key=http")
self.assertEqual(self.srmock.status, falcon.HTTP_NOT_FOUND)
get_proxy_mock.assert_called_once_with('http')
@data(('http', 'http://1.1.1.1:8888'), ('https', 'http://2.2.2.2:8888'))
@unpack
def test_put_proxy(self, key, proxy):
settings_manager = SettingsManager()
set_proxy_mock = MagicMock()
settings_manager.set_proxy = set_proxy_mock
settings_proxy_resource = SettingsProxy(settings_manager)
self.api.add_route(self.api_url, settings_proxy_resource)
request = {'url': proxy}
self.simulate_request(self.api_url, decode='utf-8', method='PUT', query_string="key="+key,
body=json.dumps(request))
self.assertEqual(self.srmock.status, falcon.HTTP_NO_CONTENT)
set_proxy_mock.assert_called_once_with(key, proxy)
def test_put_proxy_bad_request_1(self):
settings_proxy_resource = SettingsProxy(SettingsManager())
self.api.add_route(self.api_url, settings_proxy_resource)
self.simulate_request(self.api_url, decode='utf-8', method='PUT', query_string="key=http")
self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
def test_put_proxy_bad_request_2(self):
settings_proxy_resource = SettingsProxy(SettingsManager())
self.api.add_route(self.api_url, settings_proxy_resource)
self.simulate_request(self.api_url, decode='utf-8', method='PUT', query_string="key=http",
body=json.dumps({'url': None}))
self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
self.simulate_request(self.api_url, decode='utf-8', method='PUT', query_string="key=http",
body=json.dumps({'nourl': 'http://1.1.1.1:8888'}))
self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
@data('http', 'https')
def test_delete_proxy(self, key):
settings_manager = SettingsManager()
set_proxy_mock = MagicMock()
settings_manager.set_proxy = set_proxy_mock
settings_proxy_resource = SettingsProxy(settings_manager)
self.api.add_route(self.api_url, settings_proxy_resource)
self.simulate_request(self.api_url, decode='utf-8', method='DELETE', query_string="key="+key)
self.assertEqual(self.srmock.status, falcon.HTTP_NO_CONTENT)
set_proxy_mock.assert_called_once_with(key, None) | tests/rest/test_api_settings_proxy.py | import json
import falcon
from mock import PropertyMock, MagicMock, patch
from ddt import ddt, data, unpack
from tests import RestTestBase
from monitorrent.rest.settings_proxy import SettingsProxyEnabled, SettingsProxy
from monitorrent.settings_manager import SettingsManager
@ddt
class SettingsProxyEnabledTest(RestTestBase):
api_url = '/api/settings/proxy/enabled'
@data(True, False)
def test_get_is_proxy_enabled(self, value):
settings_manager = SettingsManager()
get_is_proxy_enabled_mock = MagicMock(return_value=value)
settings_manager.get_is_proxy_enabled = get_is_proxy_enabled_mock
settings_proxy_enabled_resource = SettingsProxyEnabled(settings_manager)
self.api.add_route(self.api_url, settings_proxy_enabled_resource)
body = self.simulate_request(self.api_url, decode='utf-8')
self.assertEqual(self.srmock.status, falcon.HTTP_OK)
self.assertTrue('application/json' in self.srmock.headers_dict['Content-Type'])
result = json.loads(body)
self.assertEqual(result, {'enabled': value})
get_is_proxy_enabled_mock.assert_called_once_with()
@data(True, False)
def test_set_is_proxy_enabled(self, value):
settings_manager = SettingsManager()
set_is_proxy_enabled_mock = MagicMock()
settings_manager.set_is_proxy_enabled = set_is_proxy_enabled_mock
settings_proxy_enabled_resource = SettingsProxyEnabled(settings_manager)
self.api.add_route(self.api_url, settings_proxy_enabled_resource)
request = {'enabled': value}
self.simulate_request(self.api_url, method="PUT", body=json.dumps(request))
self.assertEqual(self.srmock.status, falcon.HTTP_NO_CONTENT)
set_is_proxy_enabled_mock.assert_called_once_with(value)
@data({'enabled': 'random_text'},
{'enabled': 'True'},
{'wrong_param': 'Value'},
None)
def test_bad_request(self, body):
settings_manager = SettingsManager()
settings_proxy_enabled_resource = SettingsProxyEnabled(settings_manager)
self.api.add_route(self.api_url, settings_proxy_enabled_resource)
self.simulate_request(self.api_url, method="PUT", body=json.dumps(body) if body else None)
self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
@ddt
class SettingsProxyTest(RestTestBase):
api_url = '/api/settings/proxy'
@data(('http', 'http://1.1.1.1:8888'), ('https', 'http://2.2.2.2:8888'))
@unpack
def test_get_proxy(self, key, proxy):
settings_manager = SettingsManager()
get_proxy_mock = MagicMock(return_value=proxy)
settings_manager.get_proxy = get_proxy_mock
settings_proxy_resource = SettingsProxy(settings_manager)
self.api.add_route(self.api_url, settings_proxy_resource)
body = self.simulate_request(self.api_url, decode='utf-8', query_string="key="+key)
self.assertEqual(self.srmock.status, falcon.HTTP_OK)
self.assertTrue('application/json' in self.srmock.headers_dict['Content-Type'])
result = json.loads(body)
self.assertEqual(result, {'url': proxy})
get_proxy_mock.assert_called_once_with(key)
def test_get_proxy_not_found(self):
settings_manager = SettingsManager()
get_proxy_mock = MagicMock(return_value=None)
settings_manager.get_proxy = get_proxy_mock
settings_proxy_resource = SettingsProxy(settings_manager)
self.api.add_route(self.api_url, settings_proxy_resource)
self.simulate_request(self.api_url, decode='utf-8', query_string="key=http")
self.assertEqual(self.srmock.status, falcon.HTTP_NOT_FOUND)
get_proxy_mock.assert_called_once_with('http')
@data(('http', 'http://1.1.1.1:8888'), ('https', 'http://2.2.2.2:8888'))
@unpack
def test_put_proxy(self, key, proxy):
settings_manager = SettingsManager()
set_proxy_mock = MagicMock()
settings_manager.set_proxy = set_proxy_mock
settings_proxy_resource = SettingsProxy(settings_manager)
self.api.add_route(self.api_url, settings_proxy_resource)
request = {'url': proxy}
self.simulate_request(self.api_url, decode='utf-8', method='PUT', query_string="key="+key,
body=json.dumps(request))
self.assertEqual(self.srmock.status, falcon.HTTP_NO_CONTENT)
set_proxy_mock.assert_called_once_with(key, proxy)
def test_put_proxy_bad_request_1(self):
settings_proxy_resource = SettingsProxy(SettingsManager())
self.api.add_route(self.api_url, settings_proxy_resource)
self.simulate_request(self.api_url, decode='utf-8', method='PUT', query_string="key=http")
self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
def test_put_proxy_bad_request_2(self):
settings_proxy_resource = SettingsProxy(SettingsManager())
self.api.add_route(self.api_url, settings_proxy_resource)
self.simulate_request(self.api_url, decode='utf-8', method='PUT', query_string="key=http",
body=json.dumps({'url': None}))
self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
self.simulate_request(self.api_url, decode='utf-8', method='PUT', query_string="key=http",
body=json.dumps({'nourl': 'http://1.1.1.1:8888'}))
self.assertEqual(self.srmock.status, falcon.HTTP_BAD_REQUEST)
@data('http', 'https')
def test_delete_proxy(self, key):
settings_manager = SettingsManager()
set_proxy_mock = MagicMock()
settings_manager.set_proxy = set_proxy_mock
settings_proxy_resource = SettingsProxy(settings_manager)
self.api.add_route(self.api_url, settings_proxy_resource)
self.simulate_request(self.api_url, decode='utf-8', method='DELETE', query_string="key="+key)
self.assertEqual(self.srmock.status, falcon.HTTP_NO_CONTENT)
set_proxy_mock.assert_called_once_with(key, None) | 0.5564 | 0.160036 |
import numpy as np
import tensorflow as tf
import gpflow as gpf
from kernel import LfmKernel
# TODO add docs
class LfmModel(gpf.models.GPR):
def __init__(
self,
data,
kernel,
num_output,
num_latent,
mean_function=None,
noise_variance=1.0,
):
"""
LFM Model implementation for a simple GP Regression case.
:param data:
:param kernel:
:param num_output:
:param num_latent:
:param mean_function:
:param noise_variance:
"""
if not isinstance(kernel, LfmKernel):
raise NotImplementedError('LfmModel only implemented for convolved square exponential kernel!')
super().__init__(data, kernel, mean_function=mean_function, noise_variance=noise_variance)
self.num_output = num_output # P
self.num_latent = num_latent # R
def cross_covariance_yf(self, X, Xnew):
"""
Cross-covariance function for single f from LFM paper [Alvarez et al., 2009].
There is one type in the derivation of the paper, X_dist should have plus sign in both places.
:param X:
:param Xnew:
:return:
"""
X_val = X[:, 0] # (N1,)
X_p_idx = tf.cast(X[:, 1], tf.int32) # (N1,)
Xnew_val = Xnew[:, 0] # (N2, )
ell = self.kernel.lengthscales[:, None, None] # (R, 1, 1)
X_dist = X_val[:, None] - Xnew_val[None, :] # (N1, N2)
X_dist = X_dist[None, :, :] # (1, N1, N2)
Dp = tf.gather(self.kernel.D, X_p_idx)[None, :, None] # (1, N1, 1)
Sp = tf.transpose(tf.gather(self.kernel.S, X_p_idx))[:, :, None] # (R, N1, 1)
vp = (ell * Dp / 2) # (R, N1, 1)
mult = 0.5 * np.sqrt(np.pi) * Sp * ell * tf.exp(tf.square(vp)) # (R, N1, 1)
mult_exp = tf.exp(-Dp * X_dist) # (1, N1, N2)
erf_term1 = X_dist / ell - vp # (R, N1, N2)
erf_term2 = Xnew_val[None, None, :] / ell + vp # (R, N1, N2)
cc = mult * mult_exp * (tf.math.erf(erf_term1) + tf.math.erf(erf_term2))
# TODO extra transpose
return tf.transpose(cc, (1, 0, 2))
def predict_lf(
self, Xnew, full_cov=False,
):
"""
:param Xnew: (N, 2)
Same Xnew is assumed for all latent factors f_r(.). This is a reasonable assumption, as we're
mostly interested in latent factors in the same space. Besides, if they're active on different regions
one can pass the union of regions as Xnew (though this would result in extra computation),
or pass them as Xnew one by one.
:param full_cov: To get the full covariance or just the variance (diag).
:return:
"""
X, Y = self.data
Xnew_val = Xnew[:, 0] # (N2, )
kmm = self.kernel(X)
se_kernel = gpf.kernels.SquaredExponential(lengthscales=self.kernel.lengthscales)
knn = se_kernel(Xnew_val[:, None], full_cov=full_cov)
kmm_plus_s = self._add_noise_cov(kmm)
kmn = self.cross_covariance_yf(X, Xnew,) # (N1, R, N2)
conditional = gpf.conditionals.base_conditional
f_mean, f_var = conditional(
kmn, kmm_plus_s, knn, Y, full_cov=full_cov, white=False
)
return f_mean, f_var | model.py | import numpy as np
import tensorflow as tf
import gpflow as gpf
from kernel import LfmKernel
# TODO add docs
class LfmModel(gpf.models.GPR):
def __init__(
self,
data,
kernel,
num_output,
num_latent,
mean_function=None,
noise_variance=1.0,
):
"""
LFM Model implementation for a simple GP Regression case.
:param data:
:param kernel:
:param num_output:
:param num_latent:
:param mean_function:
:param noise_variance:
"""
if not isinstance(kernel, LfmKernel):
raise NotImplementedError('LfmModel only implemented for convolved square exponential kernel!')
super().__init__(data, kernel, mean_function=mean_function, noise_variance=noise_variance)
self.num_output = num_output # P
self.num_latent = num_latent # R
def cross_covariance_yf(self, X, Xnew):
"""
Cross-covariance function for single f from LFM paper [Alvarez et al., 2009].
There is one type in the derivation of the paper, X_dist should have plus sign in both places.
:param X:
:param Xnew:
:return:
"""
X_val = X[:, 0] # (N1,)
X_p_idx = tf.cast(X[:, 1], tf.int32) # (N1,)
Xnew_val = Xnew[:, 0] # (N2, )
ell = self.kernel.lengthscales[:, None, None] # (R, 1, 1)
X_dist = X_val[:, None] - Xnew_val[None, :] # (N1, N2)
X_dist = X_dist[None, :, :] # (1, N1, N2)
Dp = tf.gather(self.kernel.D, X_p_idx)[None, :, None] # (1, N1, 1)
Sp = tf.transpose(tf.gather(self.kernel.S, X_p_idx))[:, :, None] # (R, N1, 1)
vp = (ell * Dp / 2) # (R, N1, 1)
mult = 0.5 * np.sqrt(np.pi) * Sp * ell * tf.exp(tf.square(vp)) # (R, N1, 1)
mult_exp = tf.exp(-Dp * X_dist) # (1, N1, N2)
erf_term1 = X_dist / ell - vp # (R, N1, N2)
erf_term2 = Xnew_val[None, None, :] / ell + vp # (R, N1, N2)
cc = mult * mult_exp * (tf.math.erf(erf_term1) + tf.math.erf(erf_term2))
# TODO extra transpose
return tf.transpose(cc, (1, 0, 2))
def predict_lf(
self, Xnew, full_cov=False,
):
"""
:param Xnew: (N, 2)
Same Xnew is assumed for all latent factors f_r(.). This is a reasonable assumption, as we're
mostly interested in latent factors in the same space. Besides, if they're active on different regions
one can pass the union of regions as Xnew (though this would result in extra computation),
or pass them as Xnew one by one.
:param full_cov: To get the full covariance or just the variance (diag).
:return:
"""
X, Y = self.data
Xnew_val = Xnew[:, 0] # (N2, )
kmm = self.kernel(X)
se_kernel = gpf.kernels.SquaredExponential(lengthscales=self.kernel.lengthscales)
knn = se_kernel(Xnew_val[:, None], full_cov=full_cov)
kmm_plus_s = self._add_noise_cov(kmm)
kmn = self.cross_covariance_yf(X, Xnew,) # (N1, R, N2)
conditional = gpf.conditionals.base_conditional
f_mean, f_var = conditional(
kmn, kmm_plus_s, knn, Y, full_cov=full_cov, white=False
)
return f_mean, f_var | 0.456168 | 0.50592 |
import numpy as np
from copy import copy
import warnings
from ..data import Dataset
import scipy.stats as stats
class VarianceThreshold:
def __init__(self, threshold=0):
"""
the variance threshold is a simple baseline approach to feature selection
it removes all features which variance doesn't meet some threshold limit
it removes all zero-variance features, i.e..
"""
self.var = None
if threshold < 0:
raise Exception('Threshold must be a non negative value')
else:
self.threshold = threshold
def fit(self, dataset): # guarda a variância das colunas num vetor
X = dataset.X
self.var = np.var(X, axis=0)
def transform(self, dataset, inline=False):
X = dataset.X
cond = self.var > self.threshold # vetor de booleanos, onde a variancia for maior que o threshold definido, será True
ind = [] # lista que irá ter os indices das features que têm uma variância superior ao threshold
for i in range(len(cond)):
if cond[i]:
ind.append(i)
X_trans = X[:, ind] # vai buscar todas as linhas, mas apenas as colunas onde se verifica a condição
xnames = [dataset._xnames[i] for i in ind]
if inline:
dataset.X = X_trans
dataset._xnames = xnames
return dataset
else:
return Dataset(X_trans, copy(dataset.Y), xnames, copy(dataset._yname))
def fit_transform(self, dataset, inline=False): # faz tod o processo de verificação da variância e eliminação de features
self.fit(dataset)
return self.transform(dataset, inline)
class SelectKBest:
def __init__(self, k, funcao_score="f_regress"):
self.feat_num = k
if funcao_score == "f_regress":
self.function = f_regress
self.fscore = None
self.pvalue = None
def fit(self, dataset):
self.fscore, self.pvalue = self.function(dataset)
def transform(self, dataset, inline=False):
X = copy(dataset.X)
xnames = copy(dataset._xnames)
sel_list = np.argsort(self.fscore)[-self.feat_num:]
featdata = X[:, sel_list]
featnames = [xnames[index] for index in sel_list]
if inline:
dataset.X = featdata
dataset._xnames = featnames
return dataset
else:
return Dataset(featdata, copy(dataset.Y), featnames, copy(dataset._yname))
def fit_transform(self, dataset, inline=False):
self.fit(dataset)
return self.transform(dataset, inline=inline)
def f_regress(dataset):
X, y = dataset.getXy()
args = []
for k in np.unique(y):
args.append(X[y == k, :])
from scipy.stats import f_oneway
F_stat, pvalue = f_oneway(*args)
return F_stat, pvalue | src/si/data/feature_selection.py | import numpy as np
from copy import copy
import warnings
from ..data import Dataset
import scipy.stats as stats
class VarianceThreshold:
def __init__(self, threshold=0):
"""
the variance threshold is a simple baseline approach to feature selection
it removes all features which variance doesn't meet some threshold limit
it removes all zero-variance features, i.e..
"""
self.var = None
if threshold < 0:
raise Exception('Threshold must be a non negative value')
else:
self.threshold = threshold
def fit(self, dataset): # guarda a variância das colunas num vetor
X = dataset.X
self.var = np.var(X, axis=0)
def transform(self, dataset, inline=False):
X = dataset.X
cond = self.var > self.threshold # vetor de booleanos, onde a variancia for maior que o threshold definido, será True
ind = [] # lista que irá ter os indices das features que têm uma variância superior ao threshold
for i in range(len(cond)):
if cond[i]:
ind.append(i)
X_trans = X[:, ind] # vai buscar todas as linhas, mas apenas as colunas onde se verifica a condição
xnames = [dataset._xnames[i] for i in ind]
if inline:
dataset.X = X_trans
dataset._xnames = xnames
return dataset
else:
return Dataset(X_trans, copy(dataset.Y), xnames, copy(dataset._yname))
def fit_transform(self, dataset, inline=False): # faz tod o processo de verificação da variância e eliminação de features
self.fit(dataset)
return self.transform(dataset, inline)
class SelectKBest:
def __init__(self, k, funcao_score="f_regress"):
self.feat_num = k
if funcao_score == "f_regress":
self.function = f_regress
self.fscore = None
self.pvalue = None
def fit(self, dataset):
self.fscore, self.pvalue = self.function(dataset)
def transform(self, dataset, inline=False):
X = copy(dataset.X)
xnames = copy(dataset._xnames)
sel_list = np.argsort(self.fscore)[-self.feat_num:]
featdata = X[:, sel_list]
featnames = [xnames[index] for index in sel_list]
if inline:
dataset.X = featdata
dataset._xnames = featnames
return dataset
else:
return Dataset(featdata, copy(dataset.Y), featnames, copy(dataset._yname))
def fit_transform(self, dataset, inline=False):
self.fit(dataset)
return self.transform(dataset, inline=inline)
def f_regress(dataset):
X, y = dataset.getXy()
args = []
for k in np.unique(y):
args.append(X[y == k, :])
from scipy.stats import f_oneway
F_stat, pvalue = f_oneway(*args)
return F_stat, pvalue | 0.53607 | 0.597373 |
from flask import Flask, render_template, jsonify, request
from bokeh.plotting import figure
import requests
from bokeh.embed import components
from bokeh.models import AjaxDataSource, CustomJS
from sys import stderr
from bokeh.models.widgets import DataTable, TableColumn
from datetime import datetime
from bokeh.models.layouts import WidgetBox
# -------------------------------------------------------------------------------------------------
app = Flask(__name__)
TAIR_URL = 'http://gateway:3000/airTemperature?id=1'
TSOIL_URL = 'http://gateway:3000/soilTemperature?id=1'
RHPERCENT_URL = 'http://gateway:3000/RHpercent?id=1'
WATERCONTENT_URL = 'http://gateway:3000/waterContent?id=1'
NOTIFICATIONS_URL = 'http://gateway:3000/notifications'
# -------------------------------------------------------------------------------------------------
def print_log(*args, **kwargs):
print(*args, file=stderr, **kwargs)
def getData(url, key, value):
res = requests.get(url)
pts = res.json()
pts = pts[key]
x = []
y = []
for i, data in enumerate(pts):
y.append(data[value])
x.append(i)
return { 'x': x, 'y': y}
def makePlot(period, route, title, line_color):
source = AjaxDataSource(data_url = request.url_root + route, polling_interval = period, method = 'GET', mode = 'replace')
source.data = dict(x=[], y=[])
plot = figure(plot_height = 200, plot_width = 500, sizing_mode = 'scale_width', title = title)
plot.line('x', 'y', source = source, line_width = 4, line_color = line_color)
script, div = components(plot)
return script, div
def makeTable(period, route):
source = AjaxDataSource(data_url = request.url_root + route, polling_interval = period, method = 'GET', mode = 'replace')
source.data = dict(x = [], y = [])
colx = TableColumn(field = "x", title = "Time")
coly = TableColumn(field = "y", title = "Info")
table = DataTable(source = source, columns = [colx, coly], height = 300)
script, div = components(table)
return script, div
# -------------------------------------------------------------------------------------------------
@app.route('/api/NotificationData', methods = ['GET'])
def GetNotificationData():
if request.method == 'GET':
x = []
y = []
res = requests.get(NOTIFICATIONS_URL)
pts = res.json()
pts = pts['data']['series'][0]['values']
#print_log(pts)
for notification in pts:
x.append(notification[0])
y.append(notification[1])
return { 'x': x, 'y': y}
@app.route('/api/Dashboard', methods = ['GET'])
def ShowDashboard():
if request.method == 'GET':
#res = requests.get(TAIR_URL)
#print_log(res.text)
plots = []
plots.append(makeAirTemperaturePlot())
plots.append(makeSoilTemperaturePlot())
plots.append(makeRHpercentPlot())
plots.append(makeWaterContentPlot())
table = makeTable(10000, '/api/NotificationData')
return render_template('dashboard.html', plots = plots, table = table)
@app.route('/api/AirTemperature', methods = ['GET'])
def GetAirTemperature():
if request.method == 'GET':
return getData(TAIR_URL, 'data', 'airTemperature')
@app.route('/api/SoilTemperature', methods = ['GET'])
def GetSoilTemperature():
if request.method == 'GET':
return getData(TSOIL_URL, 'data', 'soilTemperature')
@app.route('/api/RHpercent', methods = ['GET'])
def GetRHpercent():
if request.method == 'GET':
return getData(RHPERCENT_URL, 'data', 'RHpercent')
@app.route('/api/WaterContent', methods = ['GET'])
def GetWaterContent():
if request.method == 'GET':
return getData(WATERCONTENT_URL, 'data', 'waterContent')
# -------------------------------------------------------------------------------------------------
def makeAirTemperaturePlot():
return makePlot(10000, '/api/AirTemperature', "Air temperature on Y ", "gray")
def makeSoilTemperaturePlot():
return makePlot(10000, '/api/SoilTemperature', "Soil temperature on Y ", "black")
def makeRHpercentPlot():
return makePlot(10000, '/api/RHpercent', "RH percent on Y ", "red")
def makeWaterContentPlot():
return makePlot(10000, '/api/WaterContent', "Water content on Y ", "blue")
# -------------------------------------------------------------------------------------------------
if __name__ == '__main__':
app.run(debug = False, host = '0.0.0.0', port = 80) | dashboard/app.py | from flask import Flask, render_template, jsonify, request
from bokeh.plotting import figure
import requests
from bokeh.embed import components
from bokeh.models import AjaxDataSource, CustomJS
from sys import stderr
from bokeh.models.widgets import DataTable, TableColumn
from datetime import datetime
from bokeh.models.layouts import WidgetBox
# -------------------------------------------------------------------------------------------------
app = Flask(__name__)
TAIR_URL = 'http://gateway:3000/airTemperature?id=1'
TSOIL_URL = 'http://gateway:3000/soilTemperature?id=1'
RHPERCENT_URL = 'http://gateway:3000/RHpercent?id=1'
WATERCONTENT_URL = 'http://gateway:3000/waterContent?id=1'
NOTIFICATIONS_URL = 'http://gateway:3000/notifications'
# -------------------------------------------------------------------------------------------------
def print_log(*args, **kwargs):
print(*args, file=stderr, **kwargs)
def getData(url, key, value):
res = requests.get(url)
pts = res.json()
pts = pts[key]
x = []
y = []
for i, data in enumerate(pts):
y.append(data[value])
x.append(i)
return { 'x': x, 'y': y}
def makePlot(period, route, title, line_color):
source = AjaxDataSource(data_url = request.url_root + route, polling_interval = period, method = 'GET', mode = 'replace')
source.data = dict(x=[], y=[])
plot = figure(plot_height = 200, plot_width = 500, sizing_mode = 'scale_width', title = title)
plot.line('x', 'y', source = source, line_width = 4, line_color = line_color)
script, div = components(plot)
return script, div
def makeTable(period, route):
source = AjaxDataSource(data_url = request.url_root + route, polling_interval = period, method = 'GET', mode = 'replace')
source.data = dict(x = [], y = [])
colx = TableColumn(field = "x", title = "Time")
coly = TableColumn(field = "y", title = "Info")
table = DataTable(source = source, columns = [colx, coly], height = 300)
script, div = components(table)
return script, div
# -------------------------------------------------------------------------------------------------
@app.route('/api/NotificationData', methods = ['GET'])
def GetNotificationData():
if request.method == 'GET':
x = []
y = []
res = requests.get(NOTIFICATIONS_URL)
pts = res.json()
pts = pts['data']['series'][0]['values']
#print_log(pts)
for notification in pts:
x.append(notification[0])
y.append(notification[1])
return { 'x': x, 'y': y}
@app.route('/api/Dashboard', methods = ['GET'])
def ShowDashboard():
if request.method == 'GET':
#res = requests.get(TAIR_URL)
#print_log(res.text)
plots = []
plots.append(makeAirTemperaturePlot())
plots.append(makeSoilTemperaturePlot())
plots.append(makeRHpercentPlot())
plots.append(makeWaterContentPlot())
table = makeTable(10000, '/api/NotificationData')
return render_template('dashboard.html', plots = plots, table = table)
@app.route('/api/AirTemperature', methods = ['GET'])
def GetAirTemperature():
if request.method == 'GET':
return getData(TAIR_URL, 'data', 'airTemperature')
@app.route('/api/SoilTemperature', methods = ['GET'])
def GetSoilTemperature():
if request.method == 'GET':
return getData(TSOIL_URL, 'data', 'soilTemperature')
@app.route('/api/RHpercent', methods = ['GET'])
def GetRHpercent():
if request.method == 'GET':
return getData(RHPERCENT_URL, 'data', 'RHpercent')
@app.route('/api/WaterContent', methods = ['GET'])
def GetWaterContent():
if request.method == 'GET':
return getData(WATERCONTENT_URL, 'data', 'waterContent')
# -------------------------------------------------------------------------------------------------
def makeAirTemperaturePlot():
return makePlot(10000, '/api/AirTemperature', "Air temperature on Y ", "gray")
def makeSoilTemperaturePlot():
return makePlot(10000, '/api/SoilTemperature', "Soil temperature on Y ", "black")
def makeRHpercentPlot():
return makePlot(10000, '/api/RHpercent', "RH percent on Y ", "red")
def makeWaterContentPlot():
return makePlot(10000, '/api/WaterContent', "Water content on Y ", "blue")
# -------------------------------------------------------------------------------------------------
if __name__ == '__main__':
app.run(debug = False, host = '0.0.0.0', port = 80) | 0.314051 | 0.210746 |
from oslo_log import log as logging
from oslo_utils import importutils
from ironic.common import boot_devices
from ironic.common import exception
from ironic.drivers import base
from ironic.drivers.modules.cimc import common
imcsdk = importutils.try_import('ImcSdk')
LOG = logging.getLogger(__name__)
CIMC_TO_IRONIC_BOOT_DEVICE = {
'storage-read-write': boot_devices.DISK,
'lan-read-only': boot_devices.PXE,
'vm-read-only': boot_devices.CDROM
}
IRONIC_TO_CIMC_BOOT_DEVICE = {
boot_devices.DISK: ('lsbootStorage', 'storage-read-write',
'storage', 'read-write'),
boot_devices.PXE: ('lsbootLan', 'lan-read-only',
'lan', 'read-only'),
boot_devices.CDROM: ('lsbootVirtualMedia', 'vm-read-only',
'virtual-media', 'read-only')
}
class CIMCManagement(base.ManagementInterface):
def get_properties(self):
"""Return the properties of the interface.
:returns: dictionary of <property name>:<property description> entries.
"""
return common.COMMON_PROPERTIES
def validate(self, task):
"""Check if node.driver_info contains the required CIMC credentials.
:param task: a TaskManager instance.
:raises: InvalidParameterValue if required CIMC credentials are
missing.
"""
common.parse_driver_info(task.node)
def get_supported_boot_devices(self, task):
"""Get a list of the supported boot devices.
:param task: a task from TaskManager.
:returns: A list with the supported boot devices defined
in :mod:`ironic.common.boot_devices`.
"""
return list(CIMC_TO_IRONIC_BOOT_DEVICE.values())
def get_boot_device(self, task):
"""Get the current boot device for a node.
Provides the current boot device of the node. Be aware that not
all drivers support this.
:param task: a task from TaskManager.
:raises: MissingParameterValue if a required parameter is missing
:raises: CIMCException if there is an error from CIMC
:returns: a dictionary containing:
:boot_device:
the boot device, one of :mod:`ironic.common.boot_devices` or
None if it is unknown.
:persistent:
Whether the boot device will persist to all future boots or
not, None if it is unknown.
"""
with common.cimc_handle(task) as handle:
method = imcsdk.ImcCore.ExternalMethod("ConfigResolveClass")
method.Cookie = handle.cookie
method.InDn = "sys/rack-unit-1"
method.InHierarchical = "true"
method.ClassId = "lsbootDef"
try:
resp = handle.xml_query(method, imcsdk.WriteXmlOption.DIRTY)
except imcsdk.ImcException as e:
raise exception.CIMCException(node=task.node.uuid, error=e)
error = getattr(resp, 'error_code', None)
if error:
raise exception.CIMCException(node=task.node.uuid, error=error)
bootDevs = resp.OutConfigs.child[0].child
first_device = None
for dev in bootDevs:
try:
if int(dev.Order) == 1:
first_device = dev
break
except (ValueError, AttributeError):
pass
boot_device = (CIMC_TO_IRONIC_BOOT_DEVICE.get(
first_device.Rn) if first_device else None)
# Every boot device in CIMC is persistent right now
persistent = True if boot_device else None
return {'boot_device': boot_device, 'persistent': persistent}
def set_boot_device(self, task, device, persistent=True):
"""Set the boot device for a node.
Set the boot device to use on next reboot of the node.
:param task: a task from TaskManager.
:param device: the boot device, one of
:mod:`ironic.common.boot_devices`.
:param persistent: Every boot device in CIMC is persistent right now,
so this value is ignored.
:raises: InvalidParameterValue if an invalid boot device is
specified.
:raises: MissingParameterValue if a required parameter is missing
:raises: CIMCException if there is an error from CIMC
"""
with common.cimc_handle(task) as handle:
dev = IRONIC_TO_CIMC_BOOT_DEVICE[device]
method = imcsdk.ImcCore.ExternalMethod("ConfigConfMo")
method.Cookie = handle.cookie
method.Dn = "sys/rack-unit-1/boot-policy"
method.InHierarchical = "true"
config = imcsdk.Imc.ConfigConfig()
bootMode = imcsdk.ImcCore.ManagedObject(dev[0])
bootMode.set_attr("access", dev[3])
bootMode.set_attr("type", dev[2])
bootMode.set_attr("Rn", dev[1])
bootMode.set_attr("order", "1")
config.add_child(bootMode)
method.InConfig = config
try:
resp = handle.xml_query(method, imcsdk.WriteXmlOption.DIRTY)
except imcsdk.ImcException as e:
raise exception.CIMCException(node=task.node.uuid, error=e)
error = getattr(resp, 'error_code')
if error:
raise exception.CIMCException(node=task.node.uuid, error=error)
def get_sensors_data(self, task):
raise NotImplementedError() | ironic/drivers/modules/cimc/management.py |
from oslo_log import log as logging
from oslo_utils import importutils
from ironic.common import boot_devices
from ironic.common import exception
from ironic.drivers import base
from ironic.drivers.modules.cimc import common
imcsdk = importutils.try_import('ImcSdk')
LOG = logging.getLogger(__name__)
CIMC_TO_IRONIC_BOOT_DEVICE = {
'storage-read-write': boot_devices.DISK,
'lan-read-only': boot_devices.PXE,
'vm-read-only': boot_devices.CDROM
}
IRONIC_TO_CIMC_BOOT_DEVICE = {
boot_devices.DISK: ('lsbootStorage', 'storage-read-write',
'storage', 'read-write'),
boot_devices.PXE: ('lsbootLan', 'lan-read-only',
'lan', 'read-only'),
boot_devices.CDROM: ('lsbootVirtualMedia', 'vm-read-only',
'virtual-media', 'read-only')
}
class CIMCManagement(base.ManagementInterface):
def get_properties(self):
"""Return the properties of the interface.
:returns: dictionary of <property name>:<property description> entries.
"""
return common.COMMON_PROPERTIES
def validate(self, task):
"""Check if node.driver_info contains the required CIMC credentials.
:param task: a TaskManager instance.
:raises: InvalidParameterValue if required CIMC credentials are
missing.
"""
common.parse_driver_info(task.node)
def get_supported_boot_devices(self, task):
"""Get a list of the supported boot devices.
:param task: a task from TaskManager.
:returns: A list with the supported boot devices defined
in :mod:`ironic.common.boot_devices`.
"""
return list(CIMC_TO_IRONIC_BOOT_DEVICE.values())
def get_boot_device(self, task):
"""Get the current boot device for a node.
Provides the current boot device of the node. Be aware that not
all drivers support this.
:param task: a task from TaskManager.
:raises: MissingParameterValue if a required parameter is missing
:raises: CIMCException if there is an error from CIMC
:returns: a dictionary containing:
:boot_device:
the boot device, one of :mod:`ironic.common.boot_devices` or
None if it is unknown.
:persistent:
Whether the boot device will persist to all future boots or
not, None if it is unknown.
"""
with common.cimc_handle(task) as handle:
method = imcsdk.ImcCore.ExternalMethod("ConfigResolveClass")
method.Cookie = handle.cookie
method.InDn = "sys/rack-unit-1"
method.InHierarchical = "true"
method.ClassId = "lsbootDef"
try:
resp = handle.xml_query(method, imcsdk.WriteXmlOption.DIRTY)
except imcsdk.ImcException as e:
raise exception.CIMCException(node=task.node.uuid, error=e)
error = getattr(resp, 'error_code', None)
if error:
raise exception.CIMCException(node=task.node.uuid, error=error)
bootDevs = resp.OutConfigs.child[0].child
first_device = None
for dev in bootDevs:
try:
if int(dev.Order) == 1:
first_device = dev
break
except (ValueError, AttributeError):
pass
boot_device = (CIMC_TO_IRONIC_BOOT_DEVICE.get(
first_device.Rn) if first_device else None)
# Every boot device in CIMC is persistent right now
persistent = True if boot_device else None
return {'boot_device': boot_device, 'persistent': persistent}
def set_boot_device(self, task, device, persistent=True):
"""Set the boot device for a node.
Set the boot device to use on next reboot of the node.
:param task: a task from TaskManager.
:param device: the boot device, one of
:mod:`ironic.common.boot_devices`.
:param persistent: Every boot device in CIMC is persistent right now,
so this value is ignored.
:raises: InvalidParameterValue if an invalid boot device is
specified.
:raises: MissingParameterValue if a required parameter is missing
:raises: CIMCException if there is an error from CIMC
"""
with common.cimc_handle(task) as handle:
dev = IRONIC_TO_CIMC_BOOT_DEVICE[device]
method = imcsdk.ImcCore.ExternalMethod("ConfigConfMo")
method.Cookie = handle.cookie
method.Dn = "sys/rack-unit-1/boot-policy"
method.InHierarchical = "true"
config = imcsdk.Imc.ConfigConfig()
bootMode = imcsdk.ImcCore.ManagedObject(dev[0])
bootMode.set_attr("access", dev[3])
bootMode.set_attr("type", dev[2])
bootMode.set_attr("Rn", dev[1])
bootMode.set_attr("order", "1")
config.add_child(bootMode)
method.InConfig = config
try:
resp = handle.xml_query(method, imcsdk.WriteXmlOption.DIRTY)
except imcsdk.ImcException as e:
raise exception.CIMCException(node=task.node.uuid, error=e)
error = getattr(resp, 'error_code')
if error:
raise exception.CIMCException(node=task.node.uuid, error=error)
def get_sensors_data(self, task):
raise NotImplementedError() | 0.662141 | 0.11088 |
import superimport
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize, line_search
def aoki_vectorized(x):
"""
F(x,y) = 0.5 (x^2 - y)^2 + 0.5 (x-1)^2
"""
f = 0.5 * np.square(np.square(x[:][0]) - x[:][1]) + 0.5 * np.square(x[:][0] - 1)
return f
def aoki(x):
"""
F(x,y) = 0.5 (x^2 - y)^2 + 0.5 (x-1)^2
"""
f = 0.5 * np.square(np.square(x[0]) - x[1]) + 0.5 * np.square(x[0] - 1)
return f
def aoki_gd(x):
"""
First-Order derivative of aoki function(Nabia - 1)
"""
g_x = 2 * np.dot((np.square(x[0]) - x[1]), x[0]) + x[0] - 1
g_y = -1 * (np.square(x[0]) - x[1])
return np.array((g_x, g_y))
def aoki_hess(x):
"""
Second-Order derivative - Hessian Matrix of aoki function(Nabia - 2)
"""
g_xx = 6 * np.square(x[0]) - 2*x[1] + 1
g_xy = -2 * x[0]
g_yy = 1
H = np.diag((2,2))
H[0][0] = g_xx
H[0][1] = g_xy
H[1][0] = g_xy
H[1][1] = g_yy
return H
def gradient_descent(x0, f, f_prime, hessian, stepsize = None):
"""
Steepest-Descent algorithm with option for line search
"""
x_i, y_i = x0
all_x_i = list()
all_y_i = list()
all_f_i = list()
for i in range(1, 100):
all_x_i.append(x_i)
all_y_i.append(y_i)
all_f_i.append(f([x_i, y_i]))
dx_i, dy_i = f_prime(np.asarray([x_i, y_i]))
if stepsize is None:
# Compute a step size using a line_search to satisfy the Wolf
# conditions
step = line_search(f, f_prime,
np.r_[x_i, y_i], -np.r_[dx_i, dy_i],
np.r_[dx_i, dy_i], c2=.05)
step = step[0]
if step is None:
step = 0
else:
step = stepsize
x_i += - step*dx_i
y_i += - step*dy_i
if np.abs(all_f_i[-1]) < 1e-16:
break
return all_x_i, all_y_i, all_f_i
def main():
x1 = np.arange(0, 2, 0.1)
x2 = np.arange(-0.5, 3, 0.1)
x = np.meshgrid(x1, x2)
z = aoki_vectorized(np.array(x))
step_sizes = [None, 0.1, 0.6]
for i, step in enumerate(step_sizes):
plt.contour(x1, x2, z, 50)
plt.plot(1, 1, 'go', markersize=10)
x0 = np.array((0.0, 0.0))
if step == None:
xs, ys, fs = gradient_descent(x0, aoki, aoki_gd, hessian = aoki_hess, stepsize = None)
ttl = 'exact line search'
fname = 'steepestDescentDemo_linesearch'
else:
xs, ys, fx = gradient_descent(x0, aoki, aoki_gd, hessian = aoki_hess, stepsize = step)
ttl = 'step size {:0.3f}'.format(step)
fname = 'steepestDescentDemo_step{:d}'.format(int(step*10))
nsteps = 20
plt.scatter(xs[:nsteps], ys[:nsteps])
plt.plot(xs[:nsteps], ys[:nsteps])
plt.title(ttl)
plt.tight_layout()
plt.savefig(f'../figures/{fname}.pdf', dpi = 300)
plt.show()
if __name__ == "__main__":
main() | scripts/steepestDescentDemo.py | import superimport
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize, line_search
def aoki_vectorized(x):
"""
F(x,y) = 0.5 (x^2 - y)^2 + 0.5 (x-1)^2
"""
f = 0.5 * np.square(np.square(x[:][0]) - x[:][1]) + 0.5 * np.square(x[:][0] - 1)
return f
def aoki(x):
"""
F(x,y) = 0.5 (x^2 - y)^2 + 0.5 (x-1)^2
"""
f = 0.5 * np.square(np.square(x[0]) - x[1]) + 0.5 * np.square(x[0] - 1)
return f
def aoki_gd(x):
"""
First-Order derivative of aoki function(Nabia - 1)
"""
g_x = 2 * np.dot((np.square(x[0]) - x[1]), x[0]) + x[0] - 1
g_y = -1 * (np.square(x[0]) - x[1])
return np.array((g_x, g_y))
def aoki_hess(x):
"""
Second-Order derivative - Hessian Matrix of aoki function(Nabia - 2)
"""
g_xx = 6 * np.square(x[0]) - 2*x[1] + 1
g_xy = -2 * x[0]
g_yy = 1
H = np.diag((2,2))
H[0][0] = g_xx
H[0][1] = g_xy
H[1][0] = g_xy
H[1][1] = g_yy
return H
def gradient_descent(x0, f, f_prime, hessian, stepsize = None):
"""
Steepest-Descent algorithm with option for line search
"""
x_i, y_i = x0
all_x_i = list()
all_y_i = list()
all_f_i = list()
for i in range(1, 100):
all_x_i.append(x_i)
all_y_i.append(y_i)
all_f_i.append(f([x_i, y_i]))
dx_i, dy_i = f_prime(np.asarray([x_i, y_i]))
if stepsize is None:
# Compute a step size using a line_search to satisfy the Wolf
# conditions
step = line_search(f, f_prime,
np.r_[x_i, y_i], -np.r_[dx_i, dy_i],
np.r_[dx_i, dy_i], c2=.05)
step = step[0]
if step is None:
step = 0
else:
step = stepsize
x_i += - step*dx_i
y_i += - step*dy_i
if np.abs(all_f_i[-1]) < 1e-16:
break
return all_x_i, all_y_i, all_f_i
def main():
x1 = np.arange(0, 2, 0.1)
x2 = np.arange(-0.5, 3, 0.1)
x = np.meshgrid(x1, x2)
z = aoki_vectorized(np.array(x))
step_sizes = [None, 0.1, 0.6]
for i, step in enumerate(step_sizes):
plt.contour(x1, x2, z, 50)
plt.plot(1, 1, 'go', markersize=10)
x0 = np.array((0.0, 0.0))
if step == None:
xs, ys, fs = gradient_descent(x0, aoki, aoki_gd, hessian = aoki_hess, stepsize = None)
ttl = 'exact line search'
fname = 'steepestDescentDemo_linesearch'
else:
xs, ys, fx = gradient_descent(x0, aoki, aoki_gd, hessian = aoki_hess, stepsize = step)
ttl = 'step size {:0.3f}'.format(step)
fname = 'steepestDescentDemo_step{:d}'.format(int(step*10))
nsteps = 20
plt.scatter(xs[:nsteps], ys[:nsteps])
plt.plot(xs[:nsteps], ys[:nsteps])
plt.title(ttl)
plt.tight_layout()
plt.savefig(f'../figures/{fname}.pdf', dpi = 300)
plt.show()
if __name__ == "__main__":
main() | 0.556159 | 0.613237 |
import os
from pathlib import Path
from pants.base.build_environment import get_buildroot
from pants.option.scope import GLOBAL_SCOPE_CONFIG_SECTION
from pants.testutil.pants_run_integration_test import PantsRunIntegrationTest
class RunnerIntegrationTest(PantsRunIntegrationTest):
"""Test logic performed in PantsRunner."""
def test_warning_filter(self):
# We load the testprojects pants-plugins to get some testing tasks and subsystems.
cmdline = [
'--no-enable-pantsd',
f"--pythonpath=+['{Path(get_buildroot(), 'testprojects/pants-plugins/src/python')}']",
f"--backend-packages=+['test_pants_plugin']",
# This task will always emit a DeprecationWarning.
'deprecation-warning-task',
]
warning_run = self.run_pants(cmdline)
self.assert_success(warning_run)
self.assertRegex(
warning_run.stderr_data,
'\\[WARN\\].*DeprecationWarning: DEPRECATED: This is a test warning!')
non_warning_run = self.run_pants(cmdline, config={
GLOBAL_SCOPE_CONFIG_SECTION: {
# NB: We do *not* include the exclamation point at the end, which tests that the regexps
# match from the beginning of the warning string, and don't require matching the entire
# string! We also lowercase the message to check that they are matched case-insensitively.
'ignore_pants_warnings': ['deprecated: this is a test warning']
},
})
self.assert_success(non_warning_run)
self.assertNotIn('test warning', non_warning_run.stderr_data)
def test_parent_build_id_set_only_for_pants_runs_called_by_other_pants_runs(self):
with self.temporary_workdir() as workdir:
command = [
'run',
'testprojects/src/python/nested_runs',
'--',
workdir,
]
result = self.run_pants_with_workdir(
command,
workdir,
)
self.assert_success(result)
run_tracker_dir = os.path.join(workdir, 'run-tracker')
self.assertTrue(os.path.isdir(run_tracker_dir), f'dir path {run_tracker_dir} does not exist!')
run_tracker_sub_dirs = (os.path.join(run_tracker_dir, dir_name) for dir_name in os.listdir(run_tracker_dir) if dir_name != 'latest')
for run_tracker_sub_dir in run_tracker_sub_dirs:
info_path = os.path.join(run_tracker_sub_dir, 'info')
self.assert_is_file(info_path)
with open(info_path, 'r') as info_f:
lines = dict(line.split(': ', 1) for line in info_f.readlines())
if 'goals' in lines['cmd_line']:
self.assertIn('parent_build_id', lines)
else:
self.assertNotIn('parent_build_id', lines) | tests/python/pants_test/bin/test_runner_integration.py |
import os
from pathlib import Path
from pants.base.build_environment import get_buildroot
from pants.option.scope import GLOBAL_SCOPE_CONFIG_SECTION
from pants.testutil.pants_run_integration_test import PantsRunIntegrationTest
class RunnerIntegrationTest(PantsRunIntegrationTest):
"""Test logic performed in PantsRunner."""
def test_warning_filter(self):
# We load the testprojects pants-plugins to get some testing tasks and subsystems.
cmdline = [
'--no-enable-pantsd',
f"--pythonpath=+['{Path(get_buildroot(), 'testprojects/pants-plugins/src/python')}']",
f"--backend-packages=+['test_pants_plugin']",
# This task will always emit a DeprecationWarning.
'deprecation-warning-task',
]
warning_run = self.run_pants(cmdline)
self.assert_success(warning_run)
self.assertRegex(
warning_run.stderr_data,
'\\[WARN\\].*DeprecationWarning: DEPRECATED: This is a test warning!')
non_warning_run = self.run_pants(cmdline, config={
GLOBAL_SCOPE_CONFIG_SECTION: {
# NB: We do *not* include the exclamation point at the end, which tests that the regexps
# match from the beginning of the warning string, and don't require matching the entire
# string! We also lowercase the message to check that they are matched case-insensitively.
'ignore_pants_warnings': ['deprecated: this is a test warning']
},
})
self.assert_success(non_warning_run)
self.assertNotIn('test warning', non_warning_run.stderr_data)
def test_parent_build_id_set_only_for_pants_runs_called_by_other_pants_runs(self):
with self.temporary_workdir() as workdir:
command = [
'run',
'testprojects/src/python/nested_runs',
'--',
workdir,
]
result = self.run_pants_with_workdir(
command,
workdir,
)
self.assert_success(result)
run_tracker_dir = os.path.join(workdir, 'run-tracker')
self.assertTrue(os.path.isdir(run_tracker_dir), f'dir path {run_tracker_dir} does not exist!')
run_tracker_sub_dirs = (os.path.join(run_tracker_dir, dir_name) for dir_name in os.listdir(run_tracker_dir) if dir_name != 'latest')
for run_tracker_sub_dir in run_tracker_sub_dirs:
info_path = os.path.join(run_tracker_sub_dir, 'info')
self.assert_is_file(info_path)
with open(info_path, 'r') as info_f:
lines = dict(line.split(': ', 1) for line in info_f.readlines())
if 'goals' in lines['cmd_line']:
self.assertIn('parent_build_id', lines)
else:
self.assertNotIn('parent_build_id', lines) | 0.510741 | 0.276447 |
import timm
from torch import nn
from config import CFG
from loss_module import ArcMarginProduct, CurricularFace
class ShopeeModel(nn.Module):
def __init__(
self,
n_classes = CFG.CLASSES,
model_name = CFG.MODEL_NAME,
fc_dim = CFG.FC_DIM,
margin = CFG.MARGIN,
scale = CFG.SCALE,
use_fc = True,
pretrained = True,
use_arcface = CFG.USE_ARCFACE):
super(ShopeeModel,self).__init__()
print(f'Building Model Backbone for {model_name} model, margin = {margin}')
self.backbone = timm.create_model(model_name, pretrained=pretrained)
if 'efficientnet' in model_name:
final_in_features = self.backbone.classifier.in_features
self.backbone.classifier = nn.Identity()
self.backbone.global_pool = nn.Identity()
elif 'resnet' in model_name:
final_in_features = self.backbone.fc.in_features
self.backbone.fc = nn.Identity()
self.backbone.global_pool = nn.Identity()
elif 'resnext' in model_name:
final_in_features = self.backbone.fc.in_features
self.backbone.fc = nn.Identity()
self.backbone.global_pool = nn.Identity()
elif 'densenet' in model_name:
final_in_features = self.backbone.classifier.in_features
self.backbone.classifier = nn.Identity()
self.backbone.global_pool = nn.Identity()
elif 'nfnet' in model_name:
final_in_features = self.backbone.head.fc.in_features
self.backbone.head.fc = nn.Identity()
self.backbone.head.global_pool = nn.Identity()
self.pooling = nn.AdaptiveAvgPool2d(1)
self.use_fc = use_fc
if use_fc:
self.dropout = nn.Dropout(p=0.0)
self.fc = nn.Linear(final_in_features, fc_dim)
self.bn = nn.BatchNorm1d(fc_dim)
self._init_params()
final_in_features = fc_dim
if use_arcface:
self.final = ArcMarginProduct(final_in_features,
n_classes,
s=scale,
m=margin)
else:
self.final = CurricularFace(final_in_features,
n_classes,
s=scale,
m=margin)
def _init_params(self):
nn.init.xavier_normal_(self.fc.weight)
nn.init.constant_(self.fc.bias, 0)
nn.init.constant_(self.bn.weight, 1)
nn.init.constant_(self.bn.bias, 0)
def forward(self, image, label):
feature = self.extract_feat(image)
logits = self.final(feature,label)
return logits
def extract_feat(self, x):
batch_size = x.shape[0]
x = self.backbone(x)
x = self.pooling(x).view(batch_size, -1)
if self.use_fc:
x = self.dropout(x)
x = self.fc(x)
x = self.bn(x)
return x | input/shopee-competition-utils/shopee_image_model.py | import timm
from torch import nn
from config import CFG
from loss_module import ArcMarginProduct, CurricularFace
class ShopeeModel(nn.Module):
def __init__(
self,
n_classes = CFG.CLASSES,
model_name = CFG.MODEL_NAME,
fc_dim = CFG.FC_DIM,
margin = CFG.MARGIN,
scale = CFG.SCALE,
use_fc = True,
pretrained = True,
use_arcface = CFG.USE_ARCFACE):
super(ShopeeModel,self).__init__()
print(f'Building Model Backbone for {model_name} model, margin = {margin}')
self.backbone = timm.create_model(model_name, pretrained=pretrained)
if 'efficientnet' in model_name:
final_in_features = self.backbone.classifier.in_features
self.backbone.classifier = nn.Identity()
self.backbone.global_pool = nn.Identity()
elif 'resnet' in model_name:
final_in_features = self.backbone.fc.in_features
self.backbone.fc = nn.Identity()
self.backbone.global_pool = nn.Identity()
elif 'resnext' in model_name:
final_in_features = self.backbone.fc.in_features
self.backbone.fc = nn.Identity()
self.backbone.global_pool = nn.Identity()
elif 'densenet' in model_name:
final_in_features = self.backbone.classifier.in_features
self.backbone.classifier = nn.Identity()
self.backbone.global_pool = nn.Identity()
elif 'nfnet' in model_name:
final_in_features = self.backbone.head.fc.in_features
self.backbone.head.fc = nn.Identity()
self.backbone.head.global_pool = nn.Identity()
self.pooling = nn.AdaptiveAvgPool2d(1)
self.use_fc = use_fc
if use_fc:
self.dropout = nn.Dropout(p=0.0)
self.fc = nn.Linear(final_in_features, fc_dim)
self.bn = nn.BatchNorm1d(fc_dim)
self._init_params()
final_in_features = fc_dim
if use_arcface:
self.final = ArcMarginProduct(final_in_features,
n_classes,
s=scale,
m=margin)
else:
self.final = CurricularFace(final_in_features,
n_classes,
s=scale,
m=margin)
def _init_params(self):
nn.init.xavier_normal_(self.fc.weight)
nn.init.constant_(self.fc.bias, 0)
nn.init.constant_(self.bn.weight, 1)
nn.init.constant_(self.bn.bias, 0)
def forward(self, image, label):
feature = self.extract_feat(image)
logits = self.final(feature,label)
return logits
def extract_feat(self, x):
batch_size = x.shape[0]
x = self.backbone(x)
x = self.pooling(x).view(batch_size, -1)
if self.use_fc:
x = self.dropout(x)
x = self.fc(x)
x = self.bn(x)
return x | 0.909544 | 0.168446 |
from typing import List, Optional
from sharpy.interfaces import IZoneManager
from sharpy.managers.extensions import BuildDetector, ChatManager
from sharpy.plans.acts import *
from sharpy.plans.acts.terran import *
from sharpy.plans.require import *
from sharpy.plans.require.supply import SupplyType
from sharpy.plans.tactics import *
from sharpy.plans.tactics.terran import *
from sharpy.plans import BuildOrder, Step, SequentialList, StepBuildGas
from sc2 import BotAI, UnitTypeId, AbilityId, Race
from sc2.ids.upgrade_id import UpgradeId
from sharpy.knowledges import Knowledge, KnowledgeBot
from sc2.position import Point2
class BuildBio(BuildOrder):
zone_manager: IZoneManager
def __init__(self):
self.worker_rushed = False
self.rush_bunker = BuildPosition(UnitTypeId.BUNKER, Point2((0, 0)), exact=True)
viking_counters = [
UnitTypeId.COLOSSUS,
UnitTypeId.MEDIVAC,
UnitTypeId.RAVEN,
UnitTypeId.VOIDRAY,
UnitTypeId.CARRIER,
UnitTypeId.TEMPEST,
UnitTypeId.BROODLORD,
]
warn = WarnBuildMacro(
[
(UnitTypeId.SUPPLYDEPOT, 1, 18),
(UnitTypeId.BARRACKS, 1, 42),
(UnitTypeId.REFINERY, 1, 44),
(UnitTypeId.COMMANDCENTER, 2, 60 + 44),
(UnitTypeId.BARRACKSREACTOR, 1, 120),
(UnitTypeId.FACTORY, 1, 120 + 21),
],
[],
)
scv = [
Step(None, TerranUnit(UnitTypeId.MARINE, 2, priority=True), skip_until=lambda k: self.worker_rushed),
Step(None, MorphOrbitals(), skip_until=UnitReady(UnitTypeId.BARRACKS, 1)),
Step(
None,
ActUnit(UnitTypeId.SCV, UnitTypeId.COMMANDCENTER, 16 + 6),
skip=UnitExists(UnitTypeId.COMMANDCENTER, 2),
),
Step(None, ActUnit(UnitTypeId.SCV, UnitTypeId.COMMANDCENTER, 32 + 12)),
]
dt_counter = [
Step(
Any(
[
EnemyBuildingExists(UnitTypeId.DARKSHRINE),
EnemyUnitExistsAfter(UnitTypeId.DARKTEMPLAR),
EnemyUnitExistsAfter(UnitTypeId.BANSHEE),
]
),
None,
),
Step(None, GridBuilding(UnitTypeId.ENGINEERINGBAY, 1)),
Step(None, DefensiveBuilding(UnitTypeId.MISSILETURRET, DefensePosition.Entrance, 2)),
Step(None, DefensiveBuilding(UnitTypeId.MISSILETURRET, DefensePosition.CenterMineralLine, None)),
]
dt_counter2 = [
Step(
Any(
[
EnemyBuildingExists(UnitTypeId.DARKSHRINE),
EnemyUnitExistsAfter(UnitTypeId.DARKTEMPLAR),
EnemyUnitExistsAfter(UnitTypeId.BANSHEE),
]
),
None,
),
Step(None, GridBuilding(UnitTypeId.STARPORT, 2)),
Step(None, BuildAddon(UnitTypeId.STARPORTTECHLAB, UnitTypeId.STARPORT, 1)),
Step(UnitReady(UnitTypeId.STARPORT, 1), ActUnit(UnitTypeId.RAVEN, UnitTypeId.STARPORT, 2)),
]
opener = [
Step(Supply(13), GridBuilding(UnitTypeId.SUPPLYDEPOT, 1, priority=True)),
GridBuilding(UnitTypeId.BARRACKS, 1, priority=True),
StepBuildGas(1, Supply(15)),
TerranUnit(UnitTypeId.REAPER, 1, only_once=True, priority=True),
Step(
None,
Expand(2),
skip_until=Any(
[
RequireCustom(lambda k: not self.rush_detected),
UnitExists(UnitTypeId.SIEGETANK, 2, include_killed=True),
]
),
),
Step(
None,
CancelBuilding(UnitTypeId.COMMANDCENTER, 1),
skip=Any(
[
RequireCustom(lambda k: not self.rush_detected),
UnitExists(UnitTypeId.SIEGETANK, 2, include_killed=True),
]
),
),
Step(None, self.rush_bunker, skip_until=lambda k: self.rush_detected),
Step(None, GridBuilding(UnitTypeId.BARRACKS, 2), skip_until=lambda k: self.rush_detected),
GridBuilding(UnitTypeId.SUPPLYDEPOT, 2, priority=True),
BuildAddon(UnitTypeId.BARRACKSREACTOR, UnitTypeId.BARRACKS, 1),
GridBuilding(UnitTypeId.FACTORY, 1),
BuildAddon(UnitTypeId.FACTORYTECHLAB, UnitTypeId.FACTORY, 1),
AutoDepot(),
]
buildings = [
Step(None, GridBuilding(UnitTypeId.BARRACKS, 2)),
Step(UnitReady(UnitTypeId.FACTORYTECHLAB), TerranUnit(UnitTypeId.SIEGETANK, 1)),
BuildGas(2),
# BuildStep(None, GridBuilding(UnitTypeId.ARMORY, 1)),
Step(None, BuildAddon(UnitTypeId.BARRACKSTECHLAB, UnitTypeId.BARRACKS, 1)),
Step(None, GridBuilding(UnitTypeId.STARPORT, 1)),
Step(None, GridBuilding(UnitTypeId.BARRACKS, 3)),
Step(None, BuildAddon(UnitTypeId.BARRACKSTECHLAB, UnitTypeId.BARRACKS, 2)),
Step(Supply(40, SupplyType.Workers), Expand(3)),
Step(None, GridBuilding(UnitTypeId.BARRACKS, 5)),
Step(None, BuildAddon(UnitTypeId.BARRACKSREACTOR, UnitTypeId.BARRACKS, 3)),
Step(None, BuildAddon(UnitTypeId.STARPORTREACTOR, UnitTypeId.STARPORT, 1)),
BuildGas(4),
]
tech = [
Step(None, Tech(UpgradeId.PUNISHERGRENADES)),
Step(None, Tech(UpgradeId.STIMPACK)),
Step(None, Tech(UpgradeId.SHIELDWALL)),
]
mech = [TerranUnit(UnitTypeId.SIEGETANK, 2, priority=True)]
air = [
Step(UnitReady(UnitTypeId.STARPORT, 1), TerranUnit(UnitTypeId.MEDIVAC, 2, priority=True)),
Step(None, TerranUnit(UnitTypeId.VIKINGFIGHTER, 1, priority=True)),
Step(
None,
TerranUnit(UnitTypeId.VIKINGFIGHTER, 3, priority=True),
skip_until=self.RequireAnyEnemyUnits(viking_counters, 1),
),
Step(UnitReady(UnitTypeId.STARPORT, 1), TerranUnit(UnitTypeId.MEDIVAC, 4, priority=True)),
Step(
None,
TerranUnit(UnitTypeId.VIKINGFIGHTER, 10, priority=True),
skip_until=self.RequireAnyEnemyUnits(viking_counters, 4),
),
Step(UnitReady(UnitTypeId.STARPORT, 1), TerranUnit(UnitTypeId.MEDIVAC, 6, priority=True)),
]
marines = [
Step(UnitExists(UnitTypeId.REAPER, 1, include_killed=True), TerranUnit(UnitTypeId.MARINE, 2)),
BuildOrder(
[
TerranUnit(UnitTypeId.MARAUDER, 20, priority=True),
TerranUnit(UnitTypeId.MARINE, 20),
Step(Minerals(250), TerranUnit(UnitTypeId.MARINE, 100)),
]
),
]
use_money = BuildOrder(
[
Step(Minerals(400), GridBuilding(UnitTypeId.BARRACKS, 8)),
Step(Minerals(500), BuildAddon(UnitTypeId.BARRACKSREACTOR, UnitTypeId.BARRACKS, 6)),
]
)
super().__init__([warn, scv, opener, buildings, dt_counter, dt_counter2, tech, mech, air, marines, use_money])
async def start(self, knowledge: "Knowledge"):
await super().start(knowledge)
self.zone_manager = knowledge.get_required_manager(IZoneManager)
self.build_detector = knowledge.get_required_manager(BuildDetector)
self.rush_bunker.position = self.zone_manager.expansion_zones[0].ramp.ramp.barracks_in_middle
@property
def rush_detected(self) -> bool:
return self.build_detector.rush_detected
async def execute(self) -> bool:
if not self.worker_rushed and self.ai.time < 120:
self.worker_rushed = self.cache.enemy_workers.filter(
lambda u: u.distance_to(self.ai.start_location) < u.distance_to(self.zone_manager.enemy_start_location)
)
return await super().execute()
class BioBot(KnowledgeBot):
def __init__(self):
super().__init__("Rusty Infantry")
self.attack = PlanZoneAttack(26)
def configure_managers(self) -> Optional[List["ManagerBase"]]:
return [BuildDetector(), ChatManager()]
async def create_plan(self) -> BuildOrder:
self.knowledge.data_manager.set_build("bio")
worker_scout = Step(None, WorkerScout(), skip_until=UnitExists(UnitTypeId.SUPPLYDEPOT, 1))
tactics = [
PlanCancelBuilding(),
LowerDepots(),
PlanZoneDefense(),
worker_scout,
Step(None, CallMule(50), skip=Time(5 * 60)),
Step(None, CallMule(100), skip_until=Time(5 * 60)),
Step(None, ScanEnemy(), skip_until=Time(5 * 60)),
DistributeWorkers(),
Step(None, SpeedMining(), lambda ai: ai.client.game_step > 5),
ManTheBunkers(),
Repair(),
ContinueBuilding(),
PlanZoneGatherTerran(),
self.attack,
PlanFinishEnemy(),
]
return BuildOrder([BuildBio(), tactics])
class LadderBot(BioBot):
@property
def my_race(self):
return Race.Terran | dummies/terran/bio.py | from typing import List, Optional
from sharpy.interfaces import IZoneManager
from sharpy.managers.extensions import BuildDetector, ChatManager
from sharpy.plans.acts import *
from sharpy.plans.acts.terran import *
from sharpy.plans.require import *
from sharpy.plans.require.supply import SupplyType
from sharpy.plans.tactics import *
from sharpy.plans.tactics.terran import *
from sharpy.plans import BuildOrder, Step, SequentialList, StepBuildGas
from sc2 import BotAI, UnitTypeId, AbilityId, Race
from sc2.ids.upgrade_id import UpgradeId
from sharpy.knowledges import Knowledge, KnowledgeBot
from sc2.position import Point2
class BuildBio(BuildOrder):
zone_manager: IZoneManager
def __init__(self):
self.worker_rushed = False
self.rush_bunker = BuildPosition(UnitTypeId.BUNKER, Point2((0, 0)), exact=True)
viking_counters = [
UnitTypeId.COLOSSUS,
UnitTypeId.MEDIVAC,
UnitTypeId.RAVEN,
UnitTypeId.VOIDRAY,
UnitTypeId.CARRIER,
UnitTypeId.TEMPEST,
UnitTypeId.BROODLORD,
]
warn = WarnBuildMacro(
[
(UnitTypeId.SUPPLYDEPOT, 1, 18),
(UnitTypeId.BARRACKS, 1, 42),
(UnitTypeId.REFINERY, 1, 44),
(UnitTypeId.COMMANDCENTER, 2, 60 + 44),
(UnitTypeId.BARRACKSREACTOR, 1, 120),
(UnitTypeId.FACTORY, 1, 120 + 21),
],
[],
)
scv = [
Step(None, TerranUnit(UnitTypeId.MARINE, 2, priority=True), skip_until=lambda k: self.worker_rushed),
Step(None, MorphOrbitals(), skip_until=UnitReady(UnitTypeId.BARRACKS, 1)),
Step(
None,
ActUnit(UnitTypeId.SCV, UnitTypeId.COMMANDCENTER, 16 + 6),
skip=UnitExists(UnitTypeId.COMMANDCENTER, 2),
),
Step(None, ActUnit(UnitTypeId.SCV, UnitTypeId.COMMANDCENTER, 32 + 12)),
]
dt_counter = [
Step(
Any(
[
EnemyBuildingExists(UnitTypeId.DARKSHRINE),
EnemyUnitExistsAfter(UnitTypeId.DARKTEMPLAR),
EnemyUnitExistsAfter(UnitTypeId.BANSHEE),
]
),
None,
),
Step(None, GridBuilding(UnitTypeId.ENGINEERINGBAY, 1)),
Step(None, DefensiveBuilding(UnitTypeId.MISSILETURRET, DefensePosition.Entrance, 2)),
Step(None, DefensiveBuilding(UnitTypeId.MISSILETURRET, DefensePosition.CenterMineralLine, None)),
]
dt_counter2 = [
Step(
Any(
[
EnemyBuildingExists(UnitTypeId.DARKSHRINE),
EnemyUnitExistsAfter(UnitTypeId.DARKTEMPLAR),
EnemyUnitExistsAfter(UnitTypeId.BANSHEE),
]
),
None,
),
Step(None, GridBuilding(UnitTypeId.STARPORT, 2)),
Step(None, BuildAddon(UnitTypeId.STARPORTTECHLAB, UnitTypeId.STARPORT, 1)),
Step(UnitReady(UnitTypeId.STARPORT, 1), ActUnit(UnitTypeId.RAVEN, UnitTypeId.STARPORT, 2)),
]
opener = [
Step(Supply(13), GridBuilding(UnitTypeId.SUPPLYDEPOT, 1, priority=True)),
GridBuilding(UnitTypeId.BARRACKS, 1, priority=True),
StepBuildGas(1, Supply(15)),
TerranUnit(UnitTypeId.REAPER, 1, only_once=True, priority=True),
Step(
None,
Expand(2),
skip_until=Any(
[
RequireCustom(lambda k: not self.rush_detected),
UnitExists(UnitTypeId.SIEGETANK, 2, include_killed=True),
]
),
),
Step(
None,
CancelBuilding(UnitTypeId.COMMANDCENTER, 1),
skip=Any(
[
RequireCustom(lambda k: not self.rush_detected),
UnitExists(UnitTypeId.SIEGETANK, 2, include_killed=True),
]
),
),
Step(None, self.rush_bunker, skip_until=lambda k: self.rush_detected),
Step(None, GridBuilding(UnitTypeId.BARRACKS, 2), skip_until=lambda k: self.rush_detected),
GridBuilding(UnitTypeId.SUPPLYDEPOT, 2, priority=True),
BuildAddon(UnitTypeId.BARRACKSREACTOR, UnitTypeId.BARRACKS, 1),
GridBuilding(UnitTypeId.FACTORY, 1),
BuildAddon(UnitTypeId.FACTORYTECHLAB, UnitTypeId.FACTORY, 1),
AutoDepot(),
]
buildings = [
Step(None, GridBuilding(UnitTypeId.BARRACKS, 2)),
Step(UnitReady(UnitTypeId.FACTORYTECHLAB), TerranUnit(UnitTypeId.SIEGETANK, 1)),
BuildGas(2),
# BuildStep(None, GridBuilding(UnitTypeId.ARMORY, 1)),
Step(None, BuildAddon(UnitTypeId.BARRACKSTECHLAB, UnitTypeId.BARRACKS, 1)),
Step(None, GridBuilding(UnitTypeId.STARPORT, 1)),
Step(None, GridBuilding(UnitTypeId.BARRACKS, 3)),
Step(None, BuildAddon(UnitTypeId.BARRACKSTECHLAB, UnitTypeId.BARRACKS, 2)),
Step(Supply(40, SupplyType.Workers), Expand(3)),
Step(None, GridBuilding(UnitTypeId.BARRACKS, 5)),
Step(None, BuildAddon(UnitTypeId.BARRACKSREACTOR, UnitTypeId.BARRACKS, 3)),
Step(None, BuildAddon(UnitTypeId.STARPORTREACTOR, UnitTypeId.STARPORT, 1)),
BuildGas(4),
]
tech = [
Step(None, Tech(UpgradeId.PUNISHERGRENADES)),
Step(None, Tech(UpgradeId.STIMPACK)),
Step(None, Tech(UpgradeId.SHIELDWALL)),
]
mech = [TerranUnit(UnitTypeId.SIEGETANK, 2, priority=True)]
air = [
Step(UnitReady(UnitTypeId.STARPORT, 1), TerranUnit(UnitTypeId.MEDIVAC, 2, priority=True)),
Step(None, TerranUnit(UnitTypeId.VIKINGFIGHTER, 1, priority=True)),
Step(
None,
TerranUnit(UnitTypeId.VIKINGFIGHTER, 3, priority=True),
skip_until=self.RequireAnyEnemyUnits(viking_counters, 1),
),
Step(UnitReady(UnitTypeId.STARPORT, 1), TerranUnit(UnitTypeId.MEDIVAC, 4, priority=True)),
Step(
None,
TerranUnit(UnitTypeId.VIKINGFIGHTER, 10, priority=True),
skip_until=self.RequireAnyEnemyUnits(viking_counters, 4),
),
Step(UnitReady(UnitTypeId.STARPORT, 1), TerranUnit(UnitTypeId.MEDIVAC, 6, priority=True)),
]
marines = [
Step(UnitExists(UnitTypeId.REAPER, 1, include_killed=True), TerranUnit(UnitTypeId.MARINE, 2)),
BuildOrder(
[
TerranUnit(UnitTypeId.MARAUDER, 20, priority=True),
TerranUnit(UnitTypeId.MARINE, 20),
Step(Minerals(250), TerranUnit(UnitTypeId.MARINE, 100)),
]
),
]
use_money = BuildOrder(
[
Step(Minerals(400), GridBuilding(UnitTypeId.BARRACKS, 8)),
Step(Minerals(500), BuildAddon(UnitTypeId.BARRACKSREACTOR, UnitTypeId.BARRACKS, 6)),
]
)
super().__init__([warn, scv, opener, buildings, dt_counter, dt_counter2, tech, mech, air, marines, use_money])
async def start(self, knowledge: "Knowledge"):
await super().start(knowledge)
self.zone_manager = knowledge.get_required_manager(IZoneManager)
self.build_detector = knowledge.get_required_manager(BuildDetector)
self.rush_bunker.position = self.zone_manager.expansion_zones[0].ramp.ramp.barracks_in_middle
@property
def rush_detected(self) -> bool:
return self.build_detector.rush_detected
async def execute(self) -> bool:
if not self.worker_rushed and self.ai.time < 120:
self.worker_rushed = self.cache.enemy_workers.filter(
lambda u: u.distance_to(self.ai.start_location) < u.distance_to(self.zone_manager.enemy_start_location)
)
return await super().execute()
class BioBot(KnowledgeBot):
def __init__(self):
super().__init__("Rusty Infantry")
self.attack = PlanZoneAttack(26)
def configure_managers(self) -> Optional[List["ManagerBase"]]:
return [BuildDetector(), ChatManager()]
async def create_plan(self) -> BuildOrder:
self.knowledge.data_manager.set_build("bio")
worker_scout = Step(None, WorkerScout(), skip_until=UnitExists(UnitTypeId.SUPPLYDEPOT, 1))
tactics = [
PlanCancelBuilding(),
LowerDepots(),
PlanZoneDefense(),
worker_scout,
Step(None, CallMule(50), skip=Time(5 * 60)),
Step(None, CallMule(100), skip_until=Time(5 * 60)),
Step(None, ScanEnemy(), skip_until=Time(5 * 60)),
DistributeWorkers(),
Step(None, SpeedMining(), lambda ai: ai.client.game_step > 5),
ManTheBunkers(),
Repair(),
ContinueBuilding(),
PlanZoneGatherTerran(),
self.attack,
PlanFinishEnemy(),
]
return BuildOrder([BuildBio(), tactics])
class LadderBot(BioBot):
@property
def my_race(self):
return Race.Terran | 0.750736 | 0.417093 |
import cv2
import time
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (127, 127, 127)
class ImageFilter:
"""
Responsible for applying filtering algorithms on the images.
"""
def __init__(self):
"""
A simple constructor that initializes variables used to crudely
time algorithms.
"""
self.currentFrame = 0
self.timeStart = None
def computeOtsuAlgorithm(self, img, *args):
"""
Wrapper function that simply runs the OpenCV Otsu's thresholding.
:param img: The image to perform the algorithm on.
:return: The outputs of the OpenCV thresholding function.
"""
return cv2.threshold(img, *args)
def computeDifferenceAlgorithm(self, img1, img2):
"""
Computes the absolute difference between two frames.
:param img1: The first image to be used in the difference.
:param img2: The second image to be used in the difference.
:return: The difference of two images in OpenCV format.
"""
return cv2.absdiff(img1, img2)
def computeWormTrackingAlgorithm(self, img):
"""
Converts the image to grayscale, applies a binary threshold, dilates
the image, then finds contours. Afterwards, draws contours with
sufficient area size onto the image.
:param img: An image.
:return: An image resulting from applying the algorithm on the input.
"""
# Magic Parameters
dilationIter = 3
# worm ~150x15 = 2250 pixels^2
contourMinArea = 500
contourMaxArea = 3000
# Converts the image to grayscale
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Applies global thresholding to binary
_, thresh = cv2.threshold(img, 30, 255, cv2.THRESH_BINARY)
# Erodes the image to improve quality of contours
# Note: Erodes instead of Dilate because binary image is 'reversed'
erode = cv2.erode(thresh, None, iterations=dilationIter)
_, contours, _ = cv2.findContours(erode,
cv2.RETR_TREE,
cv2.CHAIN_APPROX_NONE)
# Draws all contours
# track = cv2.drawContours(img, contours, -1, GRAY)
# Extracting only sufficiently large contours and drawing a
# rectangle around them (idea is to track the worm)
for c in contours:
if contourMaxArea > cv2.contourArea(c) > contourMinArea:
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(img, (x, y), (x+w, y+h), WHITE, 2)
# print("Contours Rectangle at: (%d %d) (%d %d)" % (x, y, w, h))
# print("Contours Area: %d " % cv2.contourArea(c))
return img
def _updatePerformanceMeasuring(self):
"""
Updates the last frame called in the animation and prints the time
elapsed, and average FPS since the last call to _beginTiming function.
"""
print("--- PERFORMANCE MEASUREMENTS UPDATING ---")
self.currentFrame += 1
dt = time.time() - self.timeStart
fps = (self.currentFrame / dt)
print("Time Elapsed: %d seconds" % dt)
print("Current Frame: %d" % self.currentFrame)
print("Overall FPS: %.2f" % fps)
def _startPerformanceMeasuring(self):
"""
Starts the measuring of time and current frame.
To be used in conjunction with it's update method.
"""
print("--- PERFORMANCE MEASUREMENTS STARTING NOW ---")
self.timeStart = time.time()
self.currentFrame = 0
class AnimationPreRenderer:
"""
Responsible for pre-rendering the output of the image filtering
algorithms (otherwise real-time rendering is too slow).
"""
def __init__(self, imageHandler):
"""
A simple constructor.
:param imageHandler: An instantiated ImageHandler object that is
responsible for reading and writing to the correct directories.
"""
self.imageHandler = imageHandler
self.imageFilter = ImageFilter()
def generateWormTrackingImages(self, fStart, fEnd, fDiff):
"""
:param fStart: The number of first frame.
:param fEnd: The number of the last frame.
:param fDiff: The difference range between two consecutive frames.
Generates and saves the images that show worm tracking algorithm.
"""
print(">>> PRE-RENDERING WORM TRACKING IMAGES STARTING <<<")
for f in range(fStart, fEnd+1):
print("Worm tracking rendering progress: %d/%d frames" % (f, fEnd))
img1 = self.imageHandler.readFrame(f, "raw")
img2 = self.imageHandler.readFrame(f + fDiff, "raw")
track = self.imageFilter.computeWormTrackingAlgorithm(img1)
self.imageHandler.writeImage(f, "track", track)
print(">>> PRE-RENDERING WORM TRACKING IMAGES COMPLETE <<<")
def generateDifferenceImages(self, fStart, fEnd, fDiff):
"""
:param fStart: The number of first frame.
:param fEnd: The number of the last frame.
:param fDiff: The difference range between two consecutive frames.
Generates and saves the images that show the absolute difference
between consecutive images.
"""
print(">>> PRE-RENDERING DIFFERENCE IMAGES STARTING <<<")
for f in range(fStart, fEnd+1):
print("Difference rendering progress: %d/%d frames" % (f, fEnd))
img1 = self.imageHandler.readFrame(f, "raw")
img2 = self.imageHandler.readFrame(f + fDiff, "raw")
diff = self.imageFilter.computeDifferenceAlgorithm(img1, img2)
self.imageHandler.writeImage(f, "difference", diff)
print(">>> PRE-RENDERING DIFFERENCE IMAGES COMPLETE <<<")
def generateOtsuImages(self, fStart, fEnd):
"""
Generates and saves the images that show Otsu's thresholding.
:param fStart: The number of first f.
:param fEnd: The number of the last f.
"""
print(">>> PRE-RENDERING OTSU IMAGES STARTING <<<")
for f in range(fStart, fEnd+1):
print("Otsu rendering progress: %d/%d frames" % (f, fEnd))
img = self.imageHandler.readFrame(f, "raw")
args = (img, 127, 255, cv2.THRESH_BINARY)
_, thresh = self.imageFilter.computeOtsuAlgorithm(*args)
self.imageHandler.writeImage(f, "otsu", thresh)
print(">>> PRE-RENDERING OTSU IMAGES COMPLETE <<<") | elegance/filter.py | import cv2
import time
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (127, 127, 127)
class ImageFilter:
"""
Responsible for applying filtering algorithms on the images.
"""
def __init__(self):
"""
A simple constructor that initializes variables used to crudely
time algorithms.
"""
self.currentFrame = 0
self.timeStart = None
def computeOtsuAlgorithm(self, img, *args):
"""
Wrapper function that simply runs the OpenCV Otsu's thresholding.
:param img: The image to perform the algorithm on.
:return: The outputs of the OpenCV thresholding function.
"""
return cv2.threshold(img, *args)
def computeDifferenceAlgorithm(self, img1, img2):
"""
Computes the absolute difference between two frames.
:param img1: The first image to be used in the difference.
:param img2: The second image to be used in the difference.
:return: The difference of two images in OpenCV format.
"""
return cv2.absdiff(img1, img2)
def computeWormTrackingAlgorithm(self, img):
"""
Converts the image to grayscale, applies a binary threshold, dilates
the image, then finds contours. Afterwards, draws contours with
sufficient area size onto the image.
:param img: An image.
:return: An image resulting from applying the algorithm on the input.
"""
# Magic Parameters
dilationIter = 3
# worm ~150x15 = 2250 pixels^2
contourMinArea = 500
contourMaxArea = 3000
# Converts the image to grayscale
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Applies global thresholding to binary
_, thresh = cv2.threshold(img, 30, 255, cv2.THRESH_BINARY)
# Erodes the image to improve quality of contours
# Note: Erodes instead of Dilate because binary image is 'reversed'
erode = cv2.erode(thresh, None, iterations=dilationIter)
_, contours, _ = cv2.findContours(erode,
cv2.RETR_TREE,
cv2.CHAIN_APPROX_NONE)
# Draws all contours
# track = cv2.drawContours(img, contours, -1, GRAY)
# Extracting only sufficiently large contours and drawing a
# rectangle around them (idea is to track the worm)
for c in contours:
if contourMaxArea > cv2.contourArea(c) > contourMinArea:
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(img, (x, y), (x+w, y+h), WHITE, 2)
# print("Contours Rectangle at: (%d %d) (%d %d)" % (x, y, w, h))
# print("Contours Area: %d " % cv2.contourArea(c))
return img
def _updatePerformanceMeasuring(self):
"""
Updates the last frame called in the animation and prints the time
elapsed, and average FPS since the last call to _beginTiming function.
"""
print("--- PERFORMANCE MEASUREMENTS UPDATING ---")
self.currentFrame += 1
dt = time.time() - self.timeStart
fps = (self.currentFrame / dt)
print("Time Elapsed: %d seconds" % dt)
print("Current Frame: %d" % self.currentFrame)
print("Overall FPS: %.2f" % fps)
def _startPerformanceMeasuring(self):
"""
Starts the measuring of time and current frame.
To be used in conjunction with it's update method.
"""
print("--- PERFORMANCE MEASUREMENTS STARTING NOW ---")
self.timeStart = time.time()
self.currentFrame = 0
class AnimationPreRenderer:
"""
Responsible for pre-rendering the output of the image filtering
algorithms (otherwise real-time rendering is too slow).
"""
def __init__(self, imageHandler):
"""
A simple constructor.
:param imageHandler: An instantiated ImageHandler object that is
responsible for reading and writing to the correct directories.
"""
self.imageHandler = imageHandler
self.imageFilter = ImageFilter()
def generateWormTrackingImages(self, fStart, fEnd, fDiff):
"""
:param fStart: The number of first frame.
:param fEnd: The number of the last frame.
:param fDiff: The difference range between two consecutive frames.
Generates and saves the images that show worm tracking algorithm.
"""
print(">>> PRE-RENDERING WORM TRACKING IMAGES STARTING <<<")
for f in range(fStart, fEnd+1):
print("Worm tracking rendering progress: %d/%d frames" % (f, fEnd))
img1 = self.imageHandler.readFrame(f, "raw")
img2 = self.imageHandler.readFrame(f + fDiff, "raw")
track = self.imageFilter.computeWormTrackingAlgorithm(img1)
self.imageHandler.writeImage(f, "track", track)
print(">>> PRE-RENDERING WORM TRACKING IMAGES COMPLETE <<<")
def generateDifferenceImages(self, fStart, fEnd, fDiff):
"""
:param fStart: The number of first frame.
:param fEnd: The number of the last frame.
:param fDiff: The difference range between two consecutive frames.
Generates and saves the images that show the absolute difference
between consecutive images.
"""
print(">>> PRE-RENDERING DIFFERENCE IMAGES STARTING <<<")
for f in range(fStart, fEnd+1):
print("Difference rendering progress: %d/%d frames" % (f, fEnd))
img1 = self.imageHandler.readFrame(f, "raw")
img2 = self.imageHandler.readFrame(f + fDiff, "raw")
diff = self.imageFilter.computeDifferenceAlgorithm(img1, img2)
self.imageHandler.writeImage(f, "difference", diff)
print(">>> PRE-RENDERING DIFFERENCE IMAGES COMPLETE <<<")
def generateOtsuImages(self, fStart, fEnd):
"""
Generates and saves the images that show Otsu's thresholding.
:param fStart: The number of first f.
:param fEnd: The number of the last f.
"""
print(">>> PRE-RENDERING OTSU IMAGES STARTING <<<")
for f in range(fStart, fEnd+1):
print("Otsu rendering progress: %d/%d frames" % (f, fEnd))
img = self.imageHandler.readFrame(f, "raw")
args = (img, 127, 255, cv2.THRESH_BINARY)
_, thresh = self.imageFilter.computeOtsuAlgorithm(*args)
self.imageHandler.writeImage(f, "otsu", thresh)
print(">>> PRE-RENDERING OTSU IMAGES COMPLETE <<<") | 0.770249 | 0.560373 |
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class Quotation(Document):
pass
def auto_create_supplier_quotation(doc,method):
supplier=frappe.db.get_value('Supplier',{'is_internal_supplier':1,'represents_company':doc.company},'supplier_name')
company=frappe.db.get_value('Customer',{'is_internal_Customer':1,'customer_name':doc.customer_name},'represents_company')
contact_person=frappe.db.get_value('Dynamic Link',{'parenttype':'Contact','link_doctype':'Supplier',"link_name":supplier},'parent')
qu_name=frappe.db.get_list('Document Specific Naming Series',filters={'parent':company,'parenttype':'Company'},fields={'*'})
warehouse=frappe.db.get_value('Company',{'company_name':company},'default_warehouse')
quotation_name="null"
for tup in qu_name:
if tup.reference_document=="Supplier Quotation":
quotation_name=tup.series
if quotation_name!="null":
if company:
if supplier:
tax_template=frappe.db.get_value('Purchase Taxes and Charges Template',{'company':doc.customer_name},'name')
tax_list=frappe.db.get_list("Purchase Taxes and Charges",filters={'parent':tax_template,'parenttype':'Purchase Taxes and Charges Template'},fields={'*'})
sq_doc=frappe.get_doc(dict(doctype = 'Supplier Quotation',
supplier=supplier,
naming_series=quotation_name,
company=company,
valid_till=doc.valid_till,
supplier_address=frappe.db.get_value("Dynamic Link",{"parenttype":"Address","link_doctype":"Supplier","link_name":supplier},"parent"),
contact_person=contact_person,
contact_email=frappe.db.get_value('Contact Email', {'parenttype':'Contact','parent':contact_person},'email_id'),
conversion_rate=1,
quotation_no=doc.name,
tc_name=doc.tc_name,
taxes_and_charges=tax_template,
terms=doc.terms,
total=doc.total,
total_taxes_and_charges=doc.total_taxes_and_charges,
grand_total=doc.grand_total,
base_grand_total=doc.base_grand_total,
rounded_total=doc.rounded_total,
base_rounded_total=doc.base_rounded_total,
quotation_type=doc.quotation_type,
opening_date=doc.opening_date,
rfq_no=frappe.db.get_value('Opportunity',doc.opportunity,'reference_no')
)).insert(ignore_mandatory=True)
for val in doc.items:
sq_doc.append('items', {
'item_code':val.item_code,
'qty':val.qty,
'uom':val.uom,
'stock_uom':val.stock_uom,
'rate':val.rate,
'amount':val.amount,
'base_rate':val.base_rate,
'base_amount':val.base_amount,
'description':val.description,
'conversion_factor':val.conversion_factor,
'warehouse':warehouse
})
for tax in tax_list:
sq_doc.append('taxes',{
'account_head':tax.account_head,
'charge_type':tax.charge_type,
'add_deduct_tax':'Add',
'category':'Total',
'description':tax.description,
'rate':frappe.db.get_value("Sales Taxes and Charges",{'parent':doc.name,'parenttype':'Quotation'},'rate'),
'tax_amount':frappe.db.get_value("Sales Taxes and Charges",{'parent':doc.name,'parenttype':'Quotation'},'tax_amount'),
'total':frappe.db.get_value("Sales Taxes and Charges",{'parent':doc.name,'parenttype':'Quotation'},'total'),
'tax_amount_after_discount_amount':frappe.db.get_value("Sales Taxes and Charges",{'parent':doc.name,'parenttype':'Quotation'},'tax_amount_after_discount_amount'),
'base_tax_amount':frappe.db.get_value("Sales Taxes and Charges",{'parent':doc.name,'parenttype':'Quotation'},'base_tax_amount'),
'base_total':frappe.db.get_value("Sales Taxes and Charges",{'parent':doc.name,'parenttype':'Quotation'},'base_total')
})
sq_doc.add_comment('Comment',' System created '+sq_doc.name)
sq_doc.save()
doc.add_comment('Comment',' Supplier Quotation: '+sq_doc.name)
else:
frappe.msgprint("Unable to create Supplier Quotation as customer: "+doc.customer_name +" is not associated with any company. Register the Company and submit the document: "+doc.name+ ". As Customer is not associated with any company, don't let Vendor submit the Quotation document.")
raise frappe.ValidationError("Unable to create Supplier Quotation as customer: "+doc.customer_name +" is not associated with any company. Register the Company and submit the document: "+doc.name+ ". As Customer is not associated with any company, don't let Vendor submit the Quotation document.")
else:
frappe.throw("Unable to save the Supplier Quotation as the naming series are unavailable . Please provide the naming series at the Company: "+company+" to save the document"); | seabridge_app/seabridge_app/doctype/quotation/quotation.py |
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class Quotation(Document):
pass
def auto_create_supplier_quotation(doc,method):
supplier=frappe.db.get_value('Supplier',{'is_internal_supplier':1,'represents_company':doc.company},'supplier_name')
company=frappe.db.get_value('Customer',{'is_internal_Customer':1,'customer_name':doc.customer_name},'represents_company')
contact_person=frappe.db.get_value('Dynamic Link',{'parenttype':'Contact','link_doctype':'Supplier',"link_name":supplier},'parent')
qu_name=frappe.db.get_list('Document Specific Naming Series',filters={'parent':company,'parenttype':'Company'},fields={'*'})
warehouse=frappe.db.get_value('Company',{'company_name':company},'default_warehouse')
quotation_name="null"
for tup in qu_name:
if tup.reference_document=="Supplier Quotation":
quotation_name=tup.series
if quotation_name!="null":
if company:
if supplier:
tax_template=frappe.db.get_value('Purchase Taxes and Charges Template',{'company':doc.customer_name},'name')
tax_list=frappe.db.get_list("Purchase Taxes and Charges",filters={'parent':tax_template,'parenttype':'Purchase Taxes and Charges Template'},fields={'*'})
sq_doc=frappe.get_doc(dict(doctype = 'Supplier Quotation',
supplier=supplier,
naming_series=quotation_name,
company=company,
valid_till=doc.valid_till,
supplier_address=frappe.db.get_value("Dynamic Link",{"parenttype":"Address","link_doctype":"Supplier","link_name":supplier},"parent"),
contact_person=contact_person,
contact_email=frappe.db.get_value('Contact Email', {'parenttype':'Contact','parent':contact_person},'email_id'),
conversion_rate=1,
quotation_no=doc.name,
tc_name=doc.tc_name,
taxes_and_charges=tax_template,
terms=doc.terms,
total=doc.total,
total_taxes_and_charges=doc.total_taxes_and_charges,
grand_total=doc.grand_total,
base_grand_total=doc.base_grand_total,
rounded_total=doc.rounded_total,
base_rounded_total=doc.base_rounded_total,
quotation_type=doc.quotation_type,
opening_date=doc.opening_date,
rfq_no=frappe.db.get_value('Opportunity',doc.opportunity,'reference_no')
)).insert(ignore_mandatory=True)
for val in doc.items:
sq_doc.append('items', {
'item_code':val.item_code,
'qty':val.qty,
'uom':val.uom,
'stock_uom':val.stock_uom,
'rate':val.rate,
'amount':val.amount,
'base_rate':val.base_rate,
'base_amount':val.base_amount,
'description':val.description,
'conversion_factor':val.conversion_factor,
'warehouse':warehouse
})
for tax in tax_list:
sq_doc.append('taxes',{
'account_head':tax.account_head,
'charge_type':tax.charge_type,
'add_deduct_tax':'Add',
'category':'Total',
'description':tax.description,
'rate':frappe.db.get_value("Sales Taxes and Charges",{'parent':doc.name,'parenttype':'Quotation'},'rate'),
'tax_amount':frappe.db.get_value("Sales Taxes and Charges",{'parent':doc.name,'parenttype':'Quotation'},'tax_amount'),
'total':frappe.db.get_value("Sales Taxes and Charges",{'parent':doc.name,'parenttype':'Quotation'},'total'),
'tax_amount_after_discount_amount':frappe.db.get_value("Sales Taxes and Charges",{'parent':doc.name,'parenttype':'Quotation'},'tax_amount_after_discount_amount'),
'base_tax_amount':frappe.db.get_value("Sales Taxes and Charges",{'parent':doc.name,'parenttype':'Quotation'},'base_tax_amount'),
'base_total':frappe.db.get_value("Sales Taxes and Charges",{'parent':doc.name,'parenttype':'Quotation'},'base_total')
})
sq_doc.add_comment('Comment',' System created '+sq_doc.name)
sq_doc.save()
doc.add_comment('Comment',' Supplier Quotation: '+sq_doc.name)
else:
frappe.msgprint("Unable to create Supplier Quotation as customer: "+doc.customer_name +" is not associated with any company. Register the Company and submit the document: "+doc.name+ ". As Customer is not associated with any company, don't let Vendor submit the Quotation document.")
raise frappe.ValidationError("Unable to create Supplier Quotation as customer: "+doc.customer_name +" is not associated with any company. Register the Company and submit the document: "+doc.name+ ". As Customer is not associated with any company, don't let Vendor submit the Quotation document.")
else:
frappe.throw("Unable to save the Supplier Quotation as the naming series are unavailable . Please provide the naming series at the Company: "+company+" to save the document"); | 0.300027 | 0.148201 |
import aiohttp
import argparse
import asyncio
import functools
import json
import hmac
import logging
import pytz
import raftos
import time
from configparser import ConfigParser, NoSectionError, NoOptionError
from datetime import datetime, timedelta
from logging.handlers import SysLogHandler
from crontab import CronTab
logging.basicConfig(
filename='/var/log/beatle/beatle.log',
format="[%(asctime)s] %(levelname)s %(message)s",
level=logging.INFO
)
logger = logging.getLogger('beatle')
DEFAULT_CONFIGURATION = {
'LOOP_TIMEOUT': 10,
'UPDATE_EVERY': 600,
'TIMEOUT': 5,
'TIME_ZONE': 'Europe/Moscow'
}
class Beatle:
def __init__(self, config_path, beatle_id):
self.id = beatle_id
self.read_config(config_path)
self.init_logger()
def config_get(self, section, option, default=None):
try:
return self.config.get(section, option)
except (NoSectionError, NoOptionError):
return default
def read_config(self, config_path):
self.config = ConfigParser()
self.config.read(config_path)
self.loop_timeout = int(self.config_get('beatle', 'LOOP_TIMEOUT', 10))
self.projects = []
for section in self.config.sections():
if section != 'beatle':
configuration = DEFAULT_CONFIGURATION.copy()
configuration.update({
'NAME': section,
'KEY': self.config_get(section, 'KEY'),
'URL': self.config_get(section, 'URL'),
'UPDATE_EVERY': self.config_get('beatle', 'UPDATE_EVERY', 600),
'TIMEOUT': self.config_get('beatle', 'TIMEOUT', 5),
'TIME_ZONE': self.config_get('beatle', 'TIME_ZONE', 'Europe/Moscow'),
'LOOP_TIMEOUT': self.loop_timeout
})
self.projects.append(Project(self, configuration))
def init_logger(self):
logger.setLevel(logging.DEBUG)
facility = self.config_get('logging', 'facility', 'LOG_USER')
handler = SysLogHandler(facility=getattr(SysLogHandler, facility))
logger.addHandler(handler)
def on_leader(self):
logger.info('{} is leader'.format(self.id))
async def run(self):
"""Run event loop"""
loop = asyncio.get_event_loop()
while True:
await raftos.wait_until_leader(self.id)
for project in self.projects:
asyncio.ensure_future(project.call())
await asyncio.sleep(self.loop_timeout)
class Project:
def __init__(self, beatle, configuration):
self.beatle = beatle
self.name = configuration.get('NAME')
self.key = configuration.get('KEY')
self.url = configuration.get('URL')
self.timezone = configuration.get('TIME_ZOME')
self.update_every = int(configuration.get('UPDATE_EVERY'))
self.timeout = int(configuration.get('TIMEOUT'))
self.loop_timeout = int(configuration.get('LOOP_TIMEOUT'))
self.last_update = None
self.config = {}
self.tasks = {}
async def get_config(self):
"""Return config from projects' HTTP endpoint"""
if self.config_have_to_be_updated:
self.config = await self._request('get') or self.config or {}
self.tasks = {
task: CronTab(cron_string)
for task, cron_string in self.config.get('TASKS', {}).items()
}
self.timezone = self.config.get('TIME_ZONE') or self.timezone
self.timeout = self.config.get('TIMEOUT') or self.timeout
self.update_every = self.config.get('UPDATE_EVERY') or self.update_every
self.last_update = datetime.now()
@property
def timezone_aware_now(self):
try:
return datetime.now(pytz.timezone(self.timezone))
except pytz.exceptions.UnknownTimeZoneError:
logger.exception('Wrong timezone provided for {}'.format(self.name))
finally:
return datetime.now()
@property
def config_have_to_be_updated(self):
if self.last_update is None:
return True
return self.last_update < datetime.now() - timedelta(self.update_every)
async def call(self):
"""POST to HTTP endpoint if needed"""
await self.get_config()
for task_name, cron in self.tasks.items():
time_left = cron.next(now=self.timezone_aware_now)
if time_left < self.loop_timeout:
asyncio.ensure_future(
self._call_later(
time_left,
self._request('post', data={'TASK': task_name})
)
)
@staticmethod
async def _call_later(time_left, coroutine):
await asyncio.sleep(time_left)
await coroutine
async def _request(self, method, data=None, params=None):
if params is None:
params = {}
params.update({'SIGNATURE': self._get_signature(data)})
start = time.time()
result = None
async with aiohttp.ClientSession() as session:
request = getattr(session, method)
async with request(self.url, data=data, params=params, timeout=self.timeout) as r:
if r.status == 200:
result = await r.json()
log_map = {
'URL': self.url,
'Data': json.dumps(data),
'Time': str(time.time() - start),
'Status': str(r.status),
'Response': json.dumps(result)
}
message = '\n'.join([': '.join([key, value]) for key, value in log_map.items()])
logger.info('\n' + message + '\n')
return result
def _get_signature(self, params=None):
if params is None:
params = {}
msg = ''.join(map(str, sorted(params.values()))).encode()
return hmac.new(self.key.encode(), msg=msg).hexdigest()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--conf')
parser.add_argument('--node')
parser.add_argument('--cluster')
args = parser.parse_args()
cluster = ['127.0.0.1:{}'.format(port) for port in args.cluster.split()]
node = '127.0.0.1:{}'.format(args.node)
beatle = Beatle(config_path=args.conf, beatle_id=node)
logger.info('Starting beatle node: {}'.format(node))
loop = asyncio.get_event_loop()
loop.create_task(raftos.register(node, cluster=cluster))
raftos.configure({
'log_path': '/var/log/beatle/',
'serializer': raftos.serializers.JSONSerializer,
'on_leader': beatle.on_leader
})
loop.run_until_complete(beatle.run()) | beatle.py | import aiohttp
import argparse
import asyncio
import functools
import json
import hmac
import logging
import pytz
import raftos
import time
from configparser import ConfigParser, NoSectionError, NoOptionError
from datetime import datetime, timedelta
from logging.handlers import SysLogHandler
from crontab import CronTab
logging.basicConfig(
filename='/var/log/beatle/beatle.log',
format="[%(asctime)s] %(levelname)s %(message)s",
level=logging.INFO
)
logger = logging.getLogger('beatle')
DEFAULT_CONFIGURATION = {
'LOOP_TIMEOUT': 10,
'UPDATE_EVERY': 600,
'TIMEOUT': 5,
'TIME_ZONE': 'Europe/Moscow'
}
class Beatle:
def __init__(self, config_path, beatle_id):
self.id = beatle_id
self.read_config(config_path)
self.init_logger()
def config_get(self, section, option, default=None):
try:
return self.config.get(section, option)
except (NoSectionError, NoOptionError):
return default
def read_config(self, config_path):
self.config = ConfigParser()
self.config.read(config_path)
self.loop_timeout = int(self.config_get('beatle', 'LOOP_TIMEOUT', 10))
self.projects = []
for section in self.config.sections():
if section != 'beatle':
configuration = DEFAULT_CONFIGURATION.copy()
configuration.update({
'NAME': section,
'KEY': self.config_get(section, 'KEY'),
'URL': self.config_get(section, 'URL'),
'UPDATE_EVERY': self.config_get('beatle', 'UPDATE_EVERY', 600),
'TIMEOUT': self.config_get('beatle', 'TIMEOUT', 5),
'TIME_ZONE': self.config_get('beatle', 'TIME_ZONE', 'Europe/Moscow'),
'LOOP_TIMEOUT': self.loop_timeout
})
self.projects.append(Project(self, configuration))
def init_logger(self):
logger.setLevel(logging.DEBUG)
facility = self.config_get('logging', 'facility', 'LOG_USER')
handler = SysLogHandler(facility=getattr(SysLogHandler, facility))
logger.addHandler(handler)
def on_leader(self):
logger.info('{} is leader'.format(self.id))
async def run(self):
"""Run event loop"""
loop = asyncio.get_event_loop()
while True:
await raftos.wait_until_leader(self.id)
for project in self.projects:
asyncio.ensure_future(project.call())
await asyncio.sleep(self.loop_timeout)
class Project:
def __init__(self, beatle, configuration):
self.beatle = beatle
self.name = configuration.get('NAME')
self.key = configuration.get('KEY')
self.url = configuration.get('URL')
self.timezone = configuration.get('TIME_ZOME')
self.update_every = int(configuration.get('UPDATE_EVERY'))
self.timeout = int(configuration.get('TIMEOUT'))
self.loop_timeout = int(configuration.get('LOOP_TIMEOUT'))
self.last_update = None
self.config = {}
self.tasks = {}
async def get_config(self):
"""Return config from projects' HTTP endpoint"""
if self.config_have_to_be_updated:
self.config = await self._request('get') or self.config or {}
self.tasks = {
task: CronTab(cron_string)
for task, cron_string in self.config.get('TASKS', {}).items()
}
self.timezone = self.config.get('TIME_ZONE') or self.timezone
self.timeout = self.config.get('TIMEOUT') or self.timeout
self.update_every = self.config.get('UPDATE_EVERY') or self.update_every
self.last_update = datetime.now()
@property
def timezone_aware_now(self):
try:
return datetime.now(pytz.timezone(self.timezone))
except pytz.exceptions.UnknownTimeZoneError:
logger.exception('Wrong timezone provided for {}'.format(self.name))
finally:
return datetime.now()
@property
def config_have_to_be_updated(self):
if self.last_update is None:
return True
return self.last_update < datetime.now() - timedelta(self.update_every)
async def call(self):
"""POST to HTTP endpoint if needed"""
await self.get_config()
for task_name, cron in self.tasks.items():
time_left = cron.next(now=self.timezone_aware_now)
if time_left < self.loop_timeout:
asyncio.ensure_future(
self._call_later(
time_left,
self._request('post', data={'TASK': task_name})
)
)
@staticmethod
async def _call_later(time_left, coroutine):
await asyncio.sleep(time_left)
await coroutine
async def _request(self, method, data=None, params=None):
if params is None:
params = {}
params.update({'SIGNATURE': self._get_signature(data)})
start = time.time()
result = None
async with aiohttp.ClientSession() as session:
request = getattr(session, method)
async with request(self.url, data=data, params=params, timeout=self.timeout) as r:
if r.status == 200:
result = await r.json()
log_map = {
'URL': self.url,
'Data': json.dumps(data),
'Time': str(time.time() - start),
'Status': str(r.status),
'Response': json.dumps(result)
}
message = '\n'.join([': '.join([key, value]) for key, value in log_map.items()])
logger.info('\n' + message + '\n')
return result
def _get_signature(self, params=None):
if params is None:
params = {}
msg = ''.join(map(str, sorted(params.values()))).encode()
return hmac.new(self.key.encode(), msg=msg).hexdigest()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--conf')
parser.add_argument('--node')
parser.add_argument('--cluster')
args = parser.parse_args()
cluster = ['127.0.0.1:{}'.format(port) for port in args.cluster.split()]
node = '127.0.0.1:{}'.format(args.node)
beatle = Beatle(config_path=args.conf, beatle_id=node)
logger.info('Starting beatle node: {}'.format(node))
loop = asyncio.get_event_loop()
loop.create_task(raftos.register(node, cluster=cluster))
raftos.configure({
'log_path': '/var/log/beatle/',
'serializer': raftos.serializers.JSONSerializer,
'on_leader': beatle.on_leader
})
loop.run_until_complete(beatle.run()) | 0.420124 | 0.063453 |
import pyfos.pyfos_auth as pyfos_auth
import getpass
import getopt
import sys
import atexit
session = None
def exit_handler():
global session
if session is not None:
pyfos_auth.logout(session)
def exit_register(local_session):
global session
session = local_session
atexit.register(exit_handler)
def generic_input(argv, usage):
if len(argv) == 0:
usage()
sys.exit()
ret_dict = dict()
try:
opts, args = getopt.getopt(
argv, "hn:i:m:f:p:a:d:u:e:s:c:L:P:",
["name=", "ipaddr=", "members=", "vf=", "pmembers=",
"allaccess=", "device=", "username=", "enabled=",
"speed=", "compare=", "hostname=", "hostport=",
"targetname=", "targetport=", "login=", "password="
])
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
usage()
sys.exit()
elif opt in ("-i", "--ipaddr"):
ret_dict["ipaddr"] = arg
elif opt in ("-a", "--allaccess"):
ret_dict["allaccess"] = int(arg)
elif opt in ("-c", "--compare"):
ret_dict["compare"] = arg
elif opt in ("-d", "--device"):
ret_dict["device"] = arg
elif opt in ("-e", "--enabled"):
ret_dict["enabled"] = int(arg)
elif opt in ("-f", "--vf"):
ret_dict["vfid"] = int(arg)
elif opt in ("-m", "--members"):
ret_dict["members"] = arg.split(";")
elif opt in ("-n", "--name"):
ret_dict["name"] = arg
elif opt in ("-p", "--pmembers"):
ret_dict["pmembers"] = arg.split(";")
elif opt in ("-s", "--speed"):
ret_dict["speed"] = int(arg)
elif opt in ("-u", "--username"):
ret_dict["username"] = arg
elif opt in ("--hostname"):
ret_dict["hostname"] = arg
elif opt in ("--hostport"):
ret_dict["hostport"] = arg
elif opt in ("--targetname"):
ret_dict["targetname"] = arg
elif opt in ("--targetport"):
ret_dict["targetport"] = arg
elif opt in ("-L", "--login"):
ret_dict["login"] = arg
elif opt in ("-P", "--password"):
ret_dict["password"] = arg
if "login" not in ret_dict.keys():
login = input("Login:")
ret_dict["login"] = login
if "password" not in ret_dict.keys():
password = <PASSWORD>()
ret_dict["password"] = password
return ret_dict | pyfos/utils/brcd_util.py | import pyfos.pyfos_auth as pyfos_auth
import getpass
import getopt
import sys
import atexit
session = None
def exit_handler():
global session
if session is not None:
pyfos_auth.logout(session)
def exit_register(local_session):
global session
session = local_session
atexit.register(exit_handler)
def generic_input(argv, usage):
if len(argv) == 0:
usage()
sys.exit()
ret_dict = dict()
try:
opts, args = getopt.getopt(
argv, "hn:i:m:f:p:a:d:u:e:s:c:L:P:",
["name=", "ipaddr=", "members=", "vf=", "pmembers=",
"allaccess=", "device=", "username=", "enabled=",
"speed=", "compare=", "hostname=", "hostport=",
"targetname=", "targetport=", "login=", "password="
])
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
usage()
sys.exit()
elif opt in ("-i", "--ipaddr"):
ret_dict["ipaddr"] = arg
elif opt in ("-a", "--allaccess"):
ret_dict["allaccess"] = int(arg)
elif opt in ("-c", "--compare"):
ret_dict["compare"] = arg
elif opt in ("-d", "--device"):
ret_dict["device"] = arg
elif opt in ("-e", "--enabled"):
ret_dict["enabled"] = int(arg)
elif opt in ("-f", "--vf"):
ret_dict["vfid"] = int(arg)
elif opt in ("-m", "--members"):
ret_dict["members"] = arg.split(";")
elif opt in ("-n", "--name"):
ret_dict["name"] = arg
elif opt in ("-p", "--pmembers"):
ret_dict["pmembers"] = arg.split(";")
elif opt in ("-s", "--speed"):
ret_dict["speed"] = int(arg)
elif opt in ("-u", "--username"):
ret_dict["username"] = arg
elif opt in ("--hostname"):
ret_dict["hostname"] = arg
elif opt in ("--hostport"):
ret_dict["hostport"] = arg
elif opt in ("--targetname"):
ret_dict["targetname"] = arg
elif opt in ("--targetport"):
ret_dict["targetport"] = arg
elif opt in ("-L", "--login"):
ret_dict["login"] = arg
elif opt in ("-P", "--password"):
ret_dict["password"] = arg
if "login" not in ret_dict.keys():
login = input("Login:")
ret_dict["login"] = login
if "password" not in ret_dict.keys():
password = <PASSWORD>()
ret_dict["password"] = password
return ret_dict | 0.082805 | 0.064565 |
import gdb
import config
import midas_utils
from execution_context import ExecutionContext
def response(success,
message,
result,
type=None,
variableReference=0,
namedVariables=None,
indexedVariables=None,
memoryReference=None):
return {
"body": {
"result": result,
"type": type,
"variablesReference": variableReference,
"namedVariables": namedVariables,
"indexedVariables": indexedVariables,
"memoryReference": memoryReference
},
"success": success,
"message": message
}
def find_variable(frame, name):
""" Find variable by scanning from current block to global returning first found. """
it = midas_utils.get_closest(frame, name)
if it is not None:
return it
it = midas_utils.get_static(frame, name)
if it is not None:
return it
it = midas_utils.get_global(frame, name)
return it
class WatchVariable(gdb.Command):
"""Not to be confused with watch point."""
def __init__(self, executionContexts):
super(WatchVariable, self).__init__("gdbjs-watch-variable", gdb.COMMAND_USER)
self.name = "watch-variable"
self.executionContexts: ExecutionContext = executionContexts
@config.timeInvocation
def invoke(self, args, from_tty):
try:
[expr, frameId, begin, end, scope] = midas_utils.parse_command_args(args, str, int, int, int, str)
refId = config.variableReferences.get_context(frameId)
if refId is None:
raise gdb.GdbError("No variable reference mapping for frame id {} exists".format(frameId))
ec = self.executionContexts.get(refId.threadId)
if ec is None:
raise gdb.GdbError("Execution context does not exist")
var = ec.free_floating_watchvariable(expr)
if var is not None:
res = var.to_vs()
result = response(success=True,
message=None,
result=res["value"],
type="{}".format(var.get_type()),
variableReference=var.get_variable_reference())
midas_utils.send_response(self.name, result, midas_utils.prepare_command_response)
return
frame = ec.set_known_context(frameId)
components = expr.split(".")
foundFrameId = None
it = find_variable(frame, components[0])
if scope == "first" and it is None:
for sf in ec.stack:
it = find_variable(sf.frame, components[0])
if it is not None:
for comp in components[1:]:
it = it[comp]
if it is None:
break
foundFrameId = sf.frame_id()
if foundFrameId is not None:
# when this stack frame goes out of scope, it removes `expr` free floating variable from ec
if begin != -1 and end != -1:
it = it[begin]
bound = max((end - begin) - 1, 0)
it = it.cast(it.type.array(bound))
expr = "{}[{}:{}]".format(expr, begin, end)
sf = ec.get_stackframe(foundFrameId)
var = sf.add_watched_variable(expr, it)
ec.set_free_floating(expr, var)
sf.set_free_floating(expr)
res = var.to_vs()
result = response(success=True,
message=None,
result=res["value"],
type="{}".format(var.get_type()),
variableReference=var.get_variable_reference())
midas_utils.send_response(self.name, result, midas_utils.prepare_command_response)
return
for comp in components[1:]:
it = it[comp]
if it is None:
break
if it is None:
midas_utils.send_response(
self.name,
response(result="no symbol with that name in context",
success=False,
message="could not evaluate"), midas_utils.prepare_command_response)
else:
if begin != -1 and end != -1:
it = it[begin]
bound = max((end - begin) - 1, 0)
it = it.cast(it.type.array(bound))
expr = "{}[{}:{}]".format(expr, begin, end)
sf = ec.get_stackframe(frameId)
v = sf.add_watched_variable(expr, it)
res = v.to_vs()
result = response(success=True,
message=None,
result=res["value"],
type="{}".format(v.get_type()),
variableReference=v.get_variable_reference())
midas_utils.send_response(self.name, result, midas_utils.prepare_command_response)
except Exception as e:
config.log_exception(config.error_logger(), "{} failed: {}".format(self.name, e), e)
midas_utils.send_response(self.name,
response(success=False, message="Could not be evaluated", result=None),
midas_utils.prepare_command_response) | modules/python/watch_variable.py | import gdb
import config
import midas_utils
from execution_context import ExecutionContext
def response(success,
message,
result,
type=None,
variableReference=0,
namedVariables=None,
indexedVariables=None,
memoryReference=None):
return {
"body": {
"result": result,
"type": type,
"variablesReference": variableReference,
"namedVariables": namedVariables,
"indexedVariables": indexedVariables,
"memoryReference": memoryReference
},
"success": success,
"message": message
}
def find_variable(frame, name):
""" Find variable by scanning from current block to global returning first found. """
it = midas_utils.get_closest(frame, name)
if it is not None:
return it
it = midas_utils.get_static(frame, name)
if it is not None:
return it
it = midas_utils.get_global(frame, name)
return it
class WatchVariable(gdb.Command):
"""Not to be confused with watch point."""
def __init__(self, executionContexts):
super(WatchVariable, self).__init__("gdbjs-watch-variable", gdb.COMMAND_USER)
self.name = "watch-variable"
self.executionContexts: ExecutionContext = executionContexts
@config.timeInvocation
def invoke(self, args, from_tty):
try:
[expr, frameId, begin, end, scope] = midas_utils.parse_command_args(args, str, int, int, int, str)
refId = config.variableReferences.get_context(frameId)
if refId is None:
raise gdb.GdbError("No variable reference mapping for frame id {} exists".format(frameId))
ec = self.executionContexts.get(refId.threadId)
if ec is None:
raise gdb.GdbError("Execution context does not exist")
var = ec.free_floating_watchvariable(expr)
if var is not None:
res = var.to_vs()
result = response(success=True,
message=None,
result=res["value"],
type="{}".format(var.get_type()),
variableReference=var.get_variable_reference())
midas_utils.send_response(self.name, result, midas_utils.prepare_command_response)
return
frame = ec.set_known_context(frameId)
components = expr.split(".")
foundFrameId = None
it = find_variable(frame, components[0])
if scope == "first" and it is None:
for sf in ec.stack:
it = find_variable(sf.frame, components[0])
if it is not None:
for comp in components[1:]:
it = it[comp]
if it is None:
break
foundFrameId = sf.frame_id()
if foundFrameId is not None:
# when this stack frame goes out of scope, it removes `expr` free floating variable from ec
if begin != -1 and end != -1:
it = it[begin]
bound = max((end - begin) - 1, 0)
it = it.cast(it.type.array(bound))
expr = "{}[{}:{}]".format(expr, begin, end)
sf = ec.get_stackframe(foundFrameId)
var = sf.add_watched_variable(expr, it)
ec.set_free_floating(expr, var)
sf.set_free_floating(expr)
res = var.to_vs()
result = response(success=True,
message=None,
result=res["value"],
type="{}".format(var.get_type()),
variableReference=var.get_variable_reference())
midas_utils.send_response(self.name, result, midas_utils.prepare_command_response)
return
for comp in components[1:]:
it = it[comp]
if it is None:
break
if it is None:
midas_utils.send_response(
self.name,
response(result="no symbol with that name in context",
success=False,
message="could not evaluate"), midas_utils.prepare_command_response)
else:
if begin != -1 and end != -1:
it = it[begin]
bound = max((end - begin) - 1, 0)
it = it.cast(it.type.array(bound))
expr = "{}[{}:{}]".format(expr, begin, end)
sf = ec.get_stackframe(frameId)
v = sf.add_watched_variable(expr, it)
res = v.to_vs()
result = response(success=True,
message=None,
result=res["value"],
type="{}".format(v.get_type()),
variableReference=v.get_variable_reference())
midas_utils.send_response(self.name, result, midas_utils.prepare_command_response)
except Exception as e:
config.log_exception(config.error_logger(), "{} failed: {}".format(self.name, e), e)
midas_utils.send_response(self.name,
response(success=False, message="Could not be evaluated", result=None),
midas_utils.prepare_command_response) | 0.558568 | 0.101723 |
from world import world, setup_module, teardown_module
import create_source_steps as source_create
import create_dataset_steps as dataset_create
import create_ensemble_steps as ensemble_create
import create_prediction_steps as prediction_create
class TestEnsemblePrediction(object):
def setup(self):
"""
Debug information
"""
print "\n-------------------\nTests in: %s\n" % __name__
def teardown(self):
"""
Debug information
"""
print "\nEnd of tests in: %s\n-------------------\n" % __name__
def test_scenario1(self):
"""
Scenario: Successfully creating a prediction from an ensemble:
Given I create a data source uploading a "<data>" file
And I wait until the source is ready less than <time_1> secs
And I create a dataset
And I wait until the dataset is ready less than <time_2> secs
And I create an ensemble of <number_of_models> models and <tlp> tlp
And I wait until the ensemble is ready less than <time_3> secs
When I create an ensemble prediction for "<data_input>"
And I wait until the prediction is ready less than <time_4> secs
Then the prediction for "<objective>" is "<prediction>"
Examples:
| data | time_1 | time_2 | time_3 | time_4 | number_of_models | tlp | data_input | objective | prediction |
| ../data/iris.csv | 10 | 10 | 50 | 20 | 5 | 1 | {"petal width": 0.5} | 000004 | Iris-versicolor |
| ../data/iris_sp_chars.csv | 10 | 10 | 50 | 20 | 5 | 1 | {"pétal&width\u0000": 0.5} | 000004 | Iris-versicolor |
| ../data/grades.csv | 10 | 10 | 150 | 20 | 10 | 1 | {"Assignment": 81.22, "Tutorial": 91.95, "Midterm": 79.38, "TakeHome": 105.93} | 000005 | 88.205575 |
| ../data/grades.csv | 10 | 10 | 150 | 20 | 10 | 1 | {"Assignment": 97.33, "Tutorial": 106.74, "Midterm": 76.88, "TakeHome": 108.89} | 000005 | 84.29401 |
"""
print self.test_scenario1.__doc__
examples = [
['data/iris.csv', '30', '30', '50', '20', '5', '1', '{"petal width": 0.5}', '000004', 'Iris-versicolor'],
['data/iris_sp_chars.csv', '30', '30', '50', '20', '5', '1', '{"pétal&width\u0000": 0.5}', '000004', 'Iris-versicolor'],
['data/grades.csv', '30', '30', '150', '20', '10', '1', '{"Assignment": 81.22, "Tutorial": 91.95, "Midterm": 79.38, "TakeHome": 105.93}', '000005', '84.556'],
['data/grades.csv', '30', '30', '150', '20', '10', '1', '{"Assignment": 97.33, "Tutorial": 106.74, "Midterm": 76.88, "TakeHome": 108.89}', '000005', '73.13558']]
for example in examples:
print "\nTesting with:\n", example
source_create.i_upload_a_file(self, example[0])
source_create.the_source_is_finished(self, example[1])
dataset_create.i_create_a_dataset(self)
dataset_create.the_dataset_is_finished_in_less_than(self, example[2])
ensemble_create.i_create_an_ensemble(self, example[5], example[6])
ensemble_create.the_ensemble_is_finished_in_less_than(self, example[3])
prediction_create.i_create_an_ensemble_prediction(self, example[7])
prediction_create.the_prediction_is_finished_in_less_than(self, example[4])
prediction_create.the_prediction_is(self, example[8], example[9]) | bigml/tests/test_09_ensemble_prediction.py | from world import world, setup_module, teardown_module
import create_source_steps as source_create
import create_dataset_steps as dataset_create
import create_ensemble_steps as ensemble_create
import create_prediction_steps as prediction_create
class TestEnsemblePrediction(object):
def setup(self):
"""
Debug information
"""
print "\n-------------------\nTests in: %s\n" % __name__
def teardown(self):
"""
Debug information
"""
print "\nEnd of tests in: %s\n-------------------\n" % __name__
def test_scenario1(self):
"""
Scenario: Successfully creating a prediction from an ensemble:
Given I create a data source uploading a "<data>" file
And I wait until the source is ready less than <time_1> secs
And I create a dataset
And I wait until the dataset is ready less than <time_2> secs
And I create an ensemble of <number_of_models> models and <tlp> tlp
And I wait until the ensemble is ready less than <time_3> secs
When I create an ensemble prediction for "<data_input>"
And I wait until the prediction is ready less than <time_4> secs
Then the prediction for "<objective>" is "<prediction>"
Examples:
| data | time_1 | time_2 | time_3 | time_4 | number_of_models | tlp | data_input | objective | prediction |
| ../data/iris.csv | 10 | 10 | 50 | 20 | 5 | 1 | {"petal width": 0.5} | 000004 | Iris-versicolor |
| ../data/iris_sp_chars.csv | 10 | 10 | 50 | 20 | 5 | 1 | {"pétal&width\u0000": 0.5} | 000004 | Iris-versicolor |
| ../data/grades.csv | 10 | 10 | 150 | 20 | 10 | 1 | {"Assignment": 81.22, "Tutorial": 91.95, "Midterm": 79.38, "TakeHome": 105.93} | 000005 | 88.205575 |
| ../data/grades.csv | 10 | 10 | 150 | 20 | 10 | 1 | {"Assignment": 97.33, "Tutorial": 106.74, "Midterm": 76.88, "TakeHome": 108.89} | 000005 | 84.29401 |
"""
print self.test_scenario1.__doc__
examples = [
['data/iris.csv', '30', '30', '50', '20', '5', '1', '{"petal width": 0.5}', '000004', 'Iris-versicolor'],
['data/iris_sp_chars.csv', '30', '30', '50', '20', '5', '1', '{"pétal&width\u0000": 0.5}', '000004', 'Iris-versicolor'],
['data/grades.csv', '30', '30', '150', '20', '10', '1', '{"Assignment": 81.22, "Tutorial": 91.95, "Midterm": 79.38, "TakeHome": 105.93}', '000005', '84.556'],
['data/grades.csv', '30', '30', '150', '20', '10', '1', '{"Assignment": 97.33, "Tutorial": 106.74, "Midterm": 76.88, "TakeHome": 108.89}', '000005', '73.13558']]
for example in examples:
print "\nTesting with:\n", example
source_create.i_upload_a_file(self, example[0])
source_create.the_source_is_finished(self, example[1])
dataset_create.i_create_a_dataset(self)
dataset_create.the_dataset_is_finished_in_less_than(self, example[2])
ensemble_create.i_create_an_ensemble(self, example[5], example[6])
ensemble_create.the_ensemble_is_finished_in_less_than(self, example[3])
prediction_create.i_create_an_ensemble_prediction(self, example[7])
prediction_create.the_prediction_is_finished_in_less_than(self, example[4])
prediction_create.the_prediction_is(self, example[8], example[9]) | 0.49048 | 0.555194 |
import sys
import os.path
import pickle
from datetime import datetime
from adytum.util.sourceforge.base import login
# do a date check
filename, sfID, minDays, pickleFile = sys.argv[1:]
now = datetime.now()
minDays = int(minDays)
if os.path.exists(pickleFile):
fh = open(pickleFile)
lastSync = pickle.load(fh)
fh.close()
if (now - lastSync).days < minDays:
print("A migration was performed less than %s day(s) ago." % minDays)
print("Aborting ... ")
sys.exit()
# define some URLs
host = 'https://sourceforge.net'
loginURL = '%s/account/login.php' % host
formURL = '%s/project/admin/svn_migration.php?group_id=%s' % (host, sfID)
# login and go to the migration page
#browser = login(loginURL, credFile='sourceforge_creds_test')
browser = login(loginURL, credFile='sourceforge_creds')
browser.open(formURL)
form = browser.getForm(name='migration')
# check to see if the page is a report page (in which case a migration has
# already occured, and we need to request another migration)
if form.getControl(name='action').value == 'migration_start':
# this is the one we want; continue
pass
elif form.getControl(name='action').value == 'migration_form':
form.getControl(name='button').click()
# we've submitted that form, now we need to get the "real" form
form = browser.getForm(name='migration')
elif form.getControl(name='action').value == 'migration_progress':
# still waiting ...
print("Migration still in progress; please try later.")
print("Aborting ... ")
sys.exit()
else:
# wtf?
print("Got unexpected form!")
print("\taction: %s" % form.getControl(name='action').value)
print("Aborting ... ")
sys.exit()
# submit the uploaded svn dump file
form.getControl(name='src_path_type3').value = filename
form.getControl(name='replace_type3').value = True
form.getControl(name='button').click()
# record the time this transaction was made
fh = open(pickleFile, 'w+')
pickle.dump(now, fh)
fh.close()
# last words
print("To view the results, visit the following URL:")
print("\t%s\n" % formURL)
print("\n") | admin/syncSFRepo.py | import sys
import os.path
import pickle
from datetime import datetime
from adytum.util.sourceforge.base import login
# do a date check
filename, sfID, minDays, pickleFile = sys.argv[1:]
now = datetime.now()
minDays = int(minDays)
if os.path.exists(pickleFile):
fh = open(pickleFile)
lastSync = pickle.load(fh)
fh.close()
if (now - lastSync).days < minDays:
print("A migration was performed less than %s day(s) ago." % minDays)
print("Aborting ... ")
sys.exit()
# define some URLs
host = 'https://sourceforge.net'
loginURL = '%s/account/login.php' % host
formURL = '%s/project/admin/svn_migration.php?group_id=%s' % (host, sfID)
# login and go to the migration page
#browser = login(loginURL, credFile='sourceforge_creds_test')
browser = login(loginURL, credFile='sourceforge_creds')
browser.open(formURL)
form = browser.getForm(name='migration')
# check to see if the page is a report page (in which case a migration has
# already occured, and we need to request another migration)
if form.getControl(name='action').value == 'migration_start':
# this is the one we want; continue
pass
elif form.getControl(name='action').value == 'migration_form':
form.getControl(name='button').click()
# we've submitted that form, now we need to get the "real" form
form = browser.getForm(name='migration')
elif form.getControl(name='action').value == 'migration_progress':
# still waiting ...
print("Migration still in progress; please try later.")
print("Aborting ... ")
sys.exit()
else:
# wtf?
print("Got unexpected form!")
print("\taction: %s" % form.getControl(name='action').value)
print("Aborting ... ")
sys.exit()
# submit the uploaded svn dump file
form.getControl(name='src_path_type3').value = filename
form.getControl(name='replace_type3').value = True
form.getControl(name='button').click()
# record the time this transaction was made
fh = open(pickleFile, 'w+')
pickle.dump(now, fh)
fh.close()
# last words
print("To view the results, visit the following URL:")
print("\t%s\n" % formURL)
print("\n") | 0.093017 | 0.05375 |
import json
from monasca_notification import notification
def test_json():
"""Test the to_json method to verify it behaves as expected.
"""
ts = 1429029121239
alarm = {'alarmId': 'alarmId',
'alarmName': 'alarmName',
'timestamp': ts,
'stateChangeReason': 'stateChangeReason',
'newState': 'newState',
'severity': 'LOW',
"link": "some-link",
"lifecycleState": "OPEN",
'tenantId': 'tenantId',
'metrics': 'cpu_util'}
test_notification = notification.Notification(1, 'ntype', 'name',
'address', 0, 0, alarm)
expected_dict = {u'id': 1,
u'name': u'name',
u'type': u'ntype',
u'notification_timestamp': None,
u'tenant_id': u'tenantId',
u'alarm_name': u'alarmName',
u'alarm_id': u'alarmId',
u'state': u'newState',
u'severity': u'LOW',
u'link': u'some-link',
u'lifecycle_state': u'OPEN',
u'alarm_timestamp': ts / 1000,
u'address': u'address',
u'message': u'stateChangeReason',
u'period': 0,
u'retry_count': 0,
u'raw_alarm': {
u'alarmId': u'alarmId',
u'alarmName': u'alarmName',
u'timestamp': ts,
u'stateChangeReason': u'stateChangeReason',
u'newState': u'newState',
u'severity': u'LOW',
u'link': u'some-link',
u'lifecycleState': u'OPEN',
u'tenantId': u'tenantId',
u'metrics': u'cpu_util'}}
# Compare as dicts so ordering is not an issue
assert json.loads(test_notification.to_json()) == expected_dict
def test_json_non_zero_period():
"""Test the to_json method to verify it behaves as expected.
"""
ts = 1429029121239
alarm = {'alarmId': 'alarmId',
'alarmName': 'alarmName',
'timestamp': ts,
'stateChangeReason': 'stateChangeReason',
'newState': 'newState',
'severity': 'LOW',
"link": "some-link",
"lifecycleState": "OPEN",
'tenantId': 'tenantId',
'metrics': 'cpu_util'}
test_notification = notification.Notification(1, 'ntype', 'name',
'address', 60, 0, alarm)
expected_dict = {u'id': 1,
u'name': u'name',
u'type': u'ntype',
u'notification_timestamp': None,
u'tenant_id': u'tenantId',
u'alarm_name': u'alarmName',
u'alarm_id': u'alarmId',
u'state': u'newState',
u'severity': u'LOW',
u'link': u'some-link',
u'lifecycle_state': u'OPEN',
u'alarm_timestamp': ts / 1000,
u'address': u'address',
u'message': u'stateChangeReason',
u'period': 60,
u'retry_count': 0,
u'raw_alarm': {
u'alarmId': u'alarmId',
u'alarmName': u'alarmName',
u'timestamp': ts,
u'stateChangeReason': u'stateChangeReason',
u'newState': u'newState',
u'severity': u'LOW',
u'link': u'some-link',
u'lifecycleState': u'OPEN',
u'tenantId': u'tenantId',
u'metrics': u'cpu_util'}}
# Compare as dicts so ordering is not an issue
assert json.loads(test_notification.to_json()) == expected_dict
def test_equal():
alarm = {'alarmId': 'alarmId',
'alarmName': 'alarmName',
'timestamp': 1429029121239,
'stateChangeReason': 'stateChangeReason',
'newState': 'newState',
'severity': 'LOW',
"link": "some-link",
"lifecycleState": "OPEN",
'tenantId': 'tenantId',
'metrics': 'cpu_util'}
test_notification = notification.Notification(0, 'ntype', 'name',
'address', 0, 0, alarm)
test_notification2 = notification.Notification(0, 'ntype', 'name',
'address', 0, 0, alarm)
assert(test_notification == test_notification2)
def test_unequal():
alarm = {'alarmId': 'alarmId',
'alarmName': 'alarmName',
'timestamp': 1429029121239,
'stateChangeReason': 'stateChangeReason',
'newState': 'newState',
'severity': 'LOW',
"link": "some-link",
"lifecycleState": "OPEN",
'tenantId': 'tenantId',
'metrics': 'cpu_util'}
test_notification = notification.Notification(0, 'ntype', 'name',
'address', 0, 0, alarm)
test_notification2 = notification.Notification(1, 'ntype', 'name',
'address', 0, 0, alarm)
test_notification2.alarm_id = None
assert(test_notification != test_notification2) | tests/test_notification.py | import json
from monasca_notification import notification
def test_json():
"""Test the to_json method to verify it behaves as expected.
"""
ts = 1429029121239
alarm = {'alarmId': 'alarmId',
'alarmName': 'alarmName',
'timestamp': ts,
'stateChangeReason': 'stateChangeReason',
'newState': 'newState',
'severity': 'LOW',
"link": "some-link",
"lifecycleState": "OPEN",
'tenantId': 'tenantId',
'metrics': 'cpu_util'}
test_notification = notification.Notification(1, 'ntype', 'name',
'address', 0, 0, alarm)
expected_dict = {u'id': 1,
u'name': u'name',
u'type': u'ntype',
u'notification_timestamp': None,
u'tenant_id': u'tenantId',
u'alarm_name': u'alarmName',
u'alarm_id': u'alarmId',
u'state': u'newState',
u'severity': u'LOW',
u'link': u'some-link',
u'lifecycle_state': u'OPEN',
u'alarm_timestamp': ts / 1000,
u'address': u'address',
u'message': u'stateChangeReason',
u'period': 0,
u'retry_count': 0,
u'raw_alarm': {
u'alarmId': u'alarmId',
u'alarmName': u'alarmName',
u'timestamp': ts,
u'stateChangeReason': u'stateChangeReason',
u'newState': u'newState',
u'severity': u'LOW',
u'link': u'some-link',
u'lifecycleState': u'OPEN',
u'tenantId': u'tenantId',
u'metrics': u'cpu_util'}}
# Compare as dicts so ordering is not an issue
assert json.loads(test_notification.to_json()) == expected_dict
def test_json_non_zero_period():
"""Test the to_json method to verify it behaves as expected.
"""
ts = 1429029121239
alarm = {'alarmId': 'alarmId',
'alarmName': 'alarmName',
'timestamp': ts,
'stateChangeReason': 'stateChangeReason',
'newState': 'newState',
'severity': 'LOW',
"link": "some-link",
"lifecycleState": "OPEN",
'tenantId': 'tenantId',
'metrics': 'cpu_util'}
test_notification = notification.Notification(1, 'ntype', 'name',
'address', 60, 0, alarm)
expected_dict = {u'id': 1,
u'name': u'name',
u'type': u'ntype',
u'notification_timestamp': None,
u'tenant_id': u'tenantId',
u'alarm_name': u'alarmName',
u'alarm_id': u'alarmId',
u'state': u'newState',
u'severity': u'LOW',
u'link': u'some-link',
u'lifecycle_state': u'OPEN',
u'alarm_timestamp': ts / 1000,
u'address': u'address',
u'message': u'stateChangeReason',
u'period': 60,
u'retry_count': 0,
u'raw_alarm': {
u'alarmId': u'alarmId',
u'alarmName': u'alarmName',
u'timestamp': ts,
u'stateChangeReason': u'stateChangeReason',
u'newState': u'newState',
u'severity': u'LOW',
u'link': u'some-link',
u'lifecycleState': u'OPEN',
u'tenantId': u'tenantId',
u'metrics': u'cpu_util'}}
# Compare as dicts so ordering is not an issue
assert json.loads(test_notification.to_json()) == expected_dict
def test_equal():
alarm = {'alarmId': 'alarmId',
'alarmName': 'alarmName',
'timestamp': 1429029121239,
'stateChangeReason': 'stateChangeReason',
'newState': 'newState',
'severity': 'LOW',
"link": "some-link",
"lifecycleState": "OPEN",
'tenantId': 'tenantId',
'metrics': 'cpu_util'}
test_notification = notification.Notification(0, 'ntype', 'name',
'address', 0, 0, alarm)
test_notification2 = notification.Notification(0, 'ntype', 'name',
'address', 0, 0, alarm)
assert(test_notification == test_notification2)
def test_unequal():
alarm = {'alarmId': 'alarmId',
'alarmName': 'alarmName',
'timestamp': 1429029121239,
'stateChangeReason': 'stateChangeReason',
'newState': 'newState',
'severity': 'LOW',
"link": "some-link",
"lifecycleState": "OPEN",
'tenantId': 'tenantId',
'metrics': 'cpu_util'}
test_notification = notification.Notification(0, 'ntype', 'name',
'address', 0, 0, alarm)
test_notification2 = notification.Notification(1, 'ntype', 'name',
'address', 0, 0, alarm)
test_notification2.alarm_id = None
assert(test_notification != test_notification2) | 0.440469 | 0.161089 |
import os
from os import SEEK_CUR
from struct import unpack
import time
import numpy as np
from scipy import linalg
from ..pick import pick_types
from ...coreg import (read_elp, fit_matched_points, _decimate_points,
get_ras_to_neuromag_trans)
from ...utils import verbose, logger
from ...transforms import apply_trans, als_ras_trans, als_ras_trans_mm
from ..base import _BaseRaw
from ..constants import FIFF
from ..meas_info import Info
from ..tag import _loc_to_trans
from .constants import KIT, KIT_NY, KIT_AD
from .coreg import read_hsp, read_mrk
from ...externals.six import string_types
class RawKIT(_BaseRaw):
"""Raw object from KIT SQD file adapted from bti/raw.py
Parameters
----------
input_fname : str
Path to the sqd file.
mrk : None | str | array_like, shape = (5, 3) | list of str or array_like
Marker points representing the location of the marker coils with
respect to the MEG Sensors, or path to a marker file.
If list, all of the markers will be averaged together.
elp : None | str | array_like, shape = (8, 3)
Digitizer points representing the location of the fiducials and the
marker coils with respect to the digitized head shape, or path to a
file containing these points.
hsp : None | str | array, shape = (n_points, 3)
Digitizer head shape points, or path to head shape file. If more than
10`000 points are in the head shape, they are automatically decimated.
stim : list of int | '<' | '>'
Channel-value correspondence when converting KIT trigger channels to a
Neuromag-style stim channel. For '<', the largest values are assigned
to the first channel (default). For '>', the largest values are
assigned to the last channel. Can also be specified as a list of
trigger channel indexes.
slope : '+' | '-'
How to interpret values on KIT trigger channels when synthesizing a
Neuromag-style stim channel. With '+', a positive slope (low-to-high)
is interpreted as an event. With '-', a negative slope (high-to-low)
is interpreted as an event.
stimthresh : float
The threshold level for accepting voltage changes in KIT trigger
channels as a trigger event.
preload : bool
If True, all data are loaded at initialization.
If False, data are not read until save.
verbose : bool, str, int, or None
If not None, override default verbose level (see mne.verbose).
See Also
--------
mne.io.Raw : Documentation of attribute and methods.
"""
@verbose
def __init__(self, input_fname, mrk=None, elp=None, hsp=None, stim='>',
slope='-', stimthresh=1, preload=False, verbose=None):
logger.info('Extracting SQD Parameters from %s...' % input_fname)
input_fname = os.path.abspath(input_fname)
self._sqd_params = get_sqd_params(input_fname)
self._sqd_params['stimthresh'] = stimthresh
self._sqd_params['fname'] = input_fname
logger.info('Creating Raw.info structure...')
# Raw attributes
self.verbose = verbose
self.preload = False
self._projector = None
self.first_samp = 0
self.last_samp = self._sqd_params['nsamples'] - 1
self.comp = None # no compensation for KIT
self.proj = False
# Create raw.info dict for raw fif object with SQD data
self.info = Info()
self.info['meas_id'] = None
self.info['file_id'] = None
self.info['meas_date'] = int(time.time())
self.info['projs'] = []
self.info['comps'] = []
self.info['lowpass'] = self._sqd_params['lowpass']
self.info['highpass'] = self._sqd_params['highpass']
self.info['sfreq'] = float(self._sqd_params['sfreq'])
# meg channels plus synthetic channel
self.info['nchan'] = self._sqd_params['nchan'] + 1
self.info['bads'] = []
self.info['acq_pars'], self.info['acq_stim'] = None, None
self.info['filename'] = None
self.info['ctf_head_t'] = None
self.info['dev_ctf_t'] = []
self._filenames = []
self.info['dig'] = None
self.info['dev_head_t'] = None
if isinstance(mrk, list):
mrk = [read_mrk(marker) if isinstance(marker, string_types)
else marker for marker in mrk]
mrk = np.mean(mrk, axis=0)
if (mrk is not None and elp is not None and hsp is not None):
self._set_dig_kit(mrk, elp, hsp)
elif (mrk is not None or elp is not None or hsp is not None):
err = ("mrk, elp and hsp need to be provided as a group (all or "
"none)")
raise ValueError(err)
# Creates a list of dicts of meg channels for raw.info
logger.info('Setting channel info structure...')
ch_names = {}
ch_names['MEG'] = ['MEG %03d' % ch for ch
in range(1, self._sqd_params['n_sens'] + 1)]
ch_names['MISC'] = ['MISC %03d' % ch for ch
in range(1, self._sqd_params['nmiscchan'] + 1)]
ch_names['STIM'] = ['STI 014']
locs = self._sqd_params['sensor_locs']
chan_locs = apply_trans(als_ras_trans, locs[:, :3])
chan_angles = locs[:, 3:]
self.info['chs'] = []
for idx, ch_info in enumerate(zip(ch_names['MEG'], chan_locs,
chan_angles), 1):
ch_name, ch_loc, ch_angles = ch_info
chan_info = {}
chan_info['cal'] = KIT.CALIB_FACTOR
chan_info['logno'] = idx
chan_info['scanno'] = idx
chan_info['range'] = KIT.RANGE
chan_info['unit_mul'] = KIT.UNIT_MUL
chan_info['ch_name'] = ch_name
chan_info['unit'] = FIFF.FIFF_UNIT_T
chan_info['coord_frame'] = FIFF.FIFFV_COORD_DEVICE
if idx <= self._sqd_params['nmegchan']:
chan_info['coil_type'] = FIFF.FIFFV_COIL_KIT_GRAD
chan_info['kind'] = FIFF.FIFFV_MEG_CH
else:
chan_info['coil_type'] = FIFF.FIFFV_COIL_KIT_REF_MAG
chan_info['kind'] = FIFF.FIFFV_REF_MEG_CH
chan_info['eeg_loc'] = None
# create three orthogonal vector
# ch_angles[0]: theta, ch_angles[1]: phi
ch_angles = np.radians(ch_angles)
x = np.sin(ch_angles[0]) * np.cos(ch_angles[1])
y = np.sin(ch_angles[0]) * np.sin(ch_angles[1])
z = np.cos(ch_angles[0])
vec_z = np.array([x, y, z])
length = linalg.norm(vec_z)
vec_z /= length
vec_x = np.zeros(vec_z.size, dtype=np.float)
if vec_z[1] < vec_z[2]:
if vec_z[0] < vec_z[1]:
vec_x[0] = 1.0
else:
vec_x[1] = 1.0
elif vec_z[0] < vec_z[2]:
vec_x[0] = 1.0
else:
vec_x[2] = 1.0
vec_x -= np.sum(vec_x * vec_z) * vec_z
length = linalg.norm(vec_x)
vec_x /= length
vec_y = np.cross(vec_z, vec_x)
# transform to Neuromag like coordinate space
vecs = np.vstack((vec_x, vec_y, vec_z))
vecs = apply_trans(als_ras_trans, vecs)
chan_info['loc'] = np.vstack((ch_loc, vecs)).ravel()
chan_info['coil_trans'] = _loc_to_trans(chan_info['loc'])
self.info['chs'].append(chan_info)
# label trigger and misc channels
for idy, ch_name in enumerate(ch_names['MISC'] + ch_names['STIM'],
self._sqd_params['n_sens']):
chan_info = {}
chan_info['cal'] = KIT.CALIB_FACTOR
chan_info['logno'] = idy
chan_info['scanno'] = idy
chan_info['range'] = 1.0
chan_info['unit'] = FIFF.FIFF_UNIT_V
chan_info['unit_mul'] = 0 # default is 0 mne_manual p.273
chan_info['ch_name'] = ch_name
chan_info['coil_type'] = FIFF.FIFFV_COIL_NONE
chan_info['loc'] = np.zeros(12)
if ch_name.startswith('STI'):
chan_info['unit'] = FIFF.FIFF_UNIT_NONE
chan_info['kind'] = FIFF.FIFFV_STIM_CH
else:
chan_info['kind'] = FIFF.FIFFV_MISC_CH
self.info['chs'].append(chan_info)
self.info['ch_names'] = (ch_names['MEG'] + ch_names['MISC'] +
ch_names['STIM'])
self._set_stimchannels(stim, slope)
if preload:
self.preload = preload
logger.info('Reading raw data from %s...' % input_fname)
self._data, _ = self._read_segment()
assert len(self._data) == self.info['nchan']
# Create a synthetic channel
stim = self._sqd_params['stim']
trig_chs = self._data[stim, :]
if slope == '+':
trig_chs = trig_chs > stimthresh
elif slope == '-':
trig_chs = trig_chs < stimthresh
else:
raise ValueError("slope needs to be '+' or '-'")
trig_vals = np.array(2 ** np.arange(len(stim)), ndmin=2).T
trig_chs = trig_chs * trig_vals
stim_ch = trig_chs.sum(axis=0)
self._data[-1, :] = stim_ch
# Add time info
self.first_samp, self.last_samp = 0, self._data.shape[1] - 1
self._times = np.arange(self.first_samp, self.last_samp + 1,
dtype=np.float64)
self._times /= self.info['sfreq']
logger.info(' Range : %d ... %d = %9.3f ... %9.3f secs'
% (self.first_samp, self.last_samp,
float(self.first_samp) / self.info['sfreq'],
float(self.last_samp) / self.info['sfreq']))
logger.info('Ready.')
def __repr__(self):
s = ('%r' % os.path.basename(self._sqd_params['fname']),
"n_channels x n_times : %s x %s" % (len(self.info['ch_names']),
self.last_samp -
self.first_samp + 1))
return "<RawKIT | %s>" % ', '.join(s)
def read_stim_ch(self, buffer_size=1e5):
"""Read events from data
Parameter
---------
buffer_size : int
The size of chunk to by which the data are scanned.
Returns
-------
events : array, [samples]
The event vector (1 x samples).
"""
buffer_size = int(buffer_size)
start = int(self.first_samp)
stop = int(self.last_samp + 1)
pick = pick_types(self.info, meg=False, ref_meg=False,
stim=True, exclude=[])
stim_ch = np.empty((1, stop), dtype=np.int)
for b_start in range(start, stop, buffer_size):
b_stop = b_start + buffer_size
x, _ = self._read_segment(start=b_start, stop=b_stop, sel=pick)
stim_ch[:, b_start:b_start + x.shape[1]] = x
return stim_ch
def _read_segment(self, start=0, stop=None, sel=None, verbose=None,
projector=None):
"""Read a chunk of raw data
Parameters
----------
start : int, (optional)
first sample to include (first is 0). If omitted, defaults to the
first sample in data.
stop : int, (optional)
First sample to not include.
If omitted, data is included to the end.
sel : array, optional
Indices of channels to select.
projector : array
SSP operator to apply to the data.
verbose : bool, str, int, or None
If not None, override default verbose level (see mne.verbose).
Returns
-------
data : array, [channels x samples]
the data matrix (channels x samples).
times : array, [samples]
returns the time values corresponding to the samples.
"""
if sel is None:
sel = list(range(self.info['nchan']))
elif len(sel) == 1 and sel[0] == 0 and start == 0 and stop == 1:
return (666, 666)
if projector is not None:
raise NotImplementedError('Currently does not handle projections.')
if stop is None:
stop = self.last_samp + 1
elif stop > self.last_samp + 1:
stop = self.last_samp + 1
# Initial checks
start = int(start)
stop = int(stop)
if start >= stop:
raise ValueError('No data in this range')
logger.info('Reading %d ... %d = %9.3f ... %9.3f secs...' %
(start, stop - 1, start / float(self.info['sfreq']),
(stop - 1) / float(self.info['sfreq'])))
with open(self._sqd_params['fname'], 'rb', buffering=0) as fid:
# extract data
fid.seek(KIT.DATA_OFFSET)
# data offset info
data_offset = unpack('i', fid.read(KIT.INT))[0]
nchan = self._sqd_params['nchan']
buffer_size = stop - start
count = buffer_size * nchan
pointer = start * nchan * KIT.SHORT
fid.seek(data_offset + pointer)
data = np.fromfile(fid, dtype='h', count=count)
data = data.reshape((buffer_size, nchan))
# amplifier applies only to the sensor channels
n_sens = self._sqd_params['n_sens']
sensor_gain = np.copy(self._sqd_params['sensor_gain'])
sensor_gain[:n_sens] = (sensor_gain[:n_sens] /
self._sqd_params['amp_gain'])
conv_factor = np.array((KIT.VOLTAGE_RANGE /
self._sqd_params['DYNAMIC_RANGE'])
* sensor_gain, ndmin=2)
data = conv_factor * data
data = data.T
# Create a synthetic channel
trig_chs = data[self._sqd_params['stim'], :]
if self._sqd_params['slope'] == '+':
trig_chs = trig_chs > self._sqd_params['stimthresh']
elif self._sqd_params['slope'] == '-':
trig_chs = trig_chs < self._sqd_params['stimthresh']
else:
raise ValueError("slope needs to be '+' or '-'")
trig_vals = np.array(2 ** np.arange(len(self._sqd_params['stim'])),
ndmin=2).T
trig_chs = trig_chs * trig_vals
stim_ch = np.array(trig_chs.sum(axis=0), ndmin=2)
data = np.vstack((data, stim_ch))
data = data[sel]
logger.info('[done]')
times = np.arange(start, stop) / self.info['sfreq']
return data, times
def _set_dig_kit(self, mrk, elp, hsp, auto_decimate=True):
"""Add landmark points and head shape data to the RawKIT instance
Digitizer data (elp and hsp) are represented in [mm] in the Polhemus
ALS coordinate system.
Parameters
----------
mrk : None | str | array_like, shape = (5, 3)
Marker points representing the location of the marker coils with
respect to the MEG Sensors, or path to a marker file.
elp : None | str | array_like, shape = (8, 3)
Digitizer points representing the location of the fiducials and the
marker coils with respect to the digitized head shape, or path to a
file containing these points.
hsp : None | str | array, shape = (n_points, 3)
Digitizer head shape points, or path to head shape file. If more
than 10`000 points are in the head shape, they are automatically
decimated.
auto_decimate : bool
Decimate hsp points for head shape files with more than 10'000
points.
"""
if isinstance(hsp, string_types):
hsp = read_hsp(hsp)
n_pts = len(hsp)
if n_pts > KIT.DIG_POINTS:
hsp = _decimate_points(hsp, 5)
n_new = len(hsp)
msg = ("The selected head shape contained {n_in} points, which is "
"more than recommended ({n_rec}), and was automatically "
"downsampled to {n_new} points. The preferred way to "
"downsample is using FastScan.")
msg = msg.format(n_in=n_pts, n_rec=KIT.DIG_POINTS, n_new=n_new)
logger.warning(msg)
if isinstance(elp, string_types):
elp_points = read_elp(elp)[:8]
if len(elp) < 8:
err = ("File %r contains fewer than 8 points; got shape "
"%s." % (elp, elp_points.shape))
raise ValueError(err)
elp = elp_points
if isinstance(mrk, string_types):
mrk = read_mrk(mrk)
hsp = apply_trans(als_ras_trans_mm, hsp)
elp = apply_trans(als_ras_trans_mm, elp)
mrk = apply_trans(als_ras_trans, mrk)
nasion, lpa, rpa = elp[:3]
nmtrans = get_ras_to_neuromag_trans(nasion, lpa, rpa)
elp = apply_trans(nmtrans, elp)
hsp = apply_trans(nmtrans, hsp)
# device head transform
trans = fit_matched_points(tgt_pts=elp[3:], src_pts=mrk, out='trans')
self._set_dig_neuromag(elp[:3], elp[3:], hsp, trans)
def _set_dig_neuromag(self, fid, elp, hsp, trans):
"""Fill in the digitizer data using points in neuromag space
Parameters
----------
fid : array, shape = (3, 3)
Digitizer fiducials.
elp : array, shape = (5, 3)
Digitizer ELP points.
hsp : array, shape = (n_points, 3)
Head shape points.
trans : None | array, shape = (4, 4)
Device head transformation.
"""
trans = np.asarray(trans)
if fid.shape != (3, 3):
raise ValueError("fid needs to be a 3 by 3 array")
if elp.shape != (5, 3):
raise ValueError("elp needs to be a 5 by 3 array")
if trans.shape != (4, 4):
raise ValueError("trans needs to be 4 by 4 array")
nasion, lpa, rpa = fid
dig = [{'r': nasion, 'ident': FIFF.FIFFV_POINT_NASION,
'kind': FIFF.FIFFV_POINT_CARDINAL,
'coord_frame': FIFF.FIFFV_COORD_HEAD},
{'r': lpa, 'ident': FIFF.FIFFV_POINT_LPA,
'kind': FIFF.FIFFV_POINT_CARDINAL,
'coord_frame': FIFF.FIFFV_COORD_HEAD},
{'r': rpa, 'ident': FIFF.FIFFV_POINT_RPA,
'kind': FIFF.FIFFV_POINT_CARDINAL,
'coord_frame': FIFF.FIFFV_COORD_HEAD}]
for idx, point in enumerate(elp):
dig.append({'r': point, 'ident': idx, 'kind': FIFF.FIFFV_POINT_HPI,
'coord_frame': FIFF.FIFFV_COORD_HEAD})
for idx, point in enumerate(hsp):
dig.append({'r': point, 'ident': idx,
'kind': FIFF.FIFFV_POINT_EXTRA,
'coord_frame': FIFF.FIFFV_COORD_HEAD})
dev_head_t = {'from': FIFF.FIFFV_COORD_DEVICE,
'to': FIFF.FIFFV_COORD_HEAD, 'trans': trans}
self.info['dig'] = dig
self.info['dev_head_t'] = dev_head_t
def _set_stimchannels(self, stim='<', slope='-'):
"""Specify how the trigger channel is synthesized form analog channels.
Has to be done before loading data. For a RawKIT instance that has been
created with preload=True, this method will raise a
NotImplementedError.
Parameters
----------
stim : list of int | '<' | '>'
Can be submitted as list of trigger channels.
If a list is not specified, the default triggers extracted from
misc channels will be used with specified directionality.
'<' means that largest values assigned to the first channel
in sequence.
'>' means the largest trigger assigned to the last channel
in sequence.
slope : '+' | '-'
'+' means a positive slope (low-to-high) on the event channel(s)
is used to trigger an event.
'-' means a negative slope (high-to-low) on the event channel(s)
is used to trigger an event.
"""
if self.preload:
err = "Can't change stim channel after preloading data"
raise NotImplementedError(err)
self._sqd_params['slope'] = slope
if isinstance(stim, str):
picks = pick_types(self.info, meg=False, ref_meg=False,
misc=True, exclude=[])[:8]
if stim == '<':
stim = picks[::-1]
elif stim == '>':
stim = picks
else:
raise ValueError("stim needs to be list of int, '>' or "
"'<', not %r" % str(stim))
elif np.max(stim) >= self._sqd_params['nchan']:
msg = ("Tried to set stim channel %i, but squid file only has %i"
" channels" % (np.max(stim), self._sqd_params['nchan']))
raise ValueError(msg)
self._sqd_params['stim'] = stim
def get_sqd_params(rawfile):
"""Extracts all the information from the sqd file.
Parameters
----------
rawfile : str
Raw sqd file to be read.
Returns
-------
sqd : dict
A dict containing all the sqd parameter settings.
"""
sqd = dict()
sqd['rawfile'] = rawfile
with open(rawfile, 'rb', buffering=0) as fid: # buffering=0 for np bug
fid.seek(KIT.BASIC_INFO)
basic_offset = unpack('i', fid.read(KIT.INT))[0]
fid.seek(basic_offset)
# skips version, revision, sysid
fid.seek(KIT.INT * 3, SEEK_CUR)
# basic info
sysname = unpack('128s', fid.read(KIT.STRING))
sysname = sysname[0].decode().split('\n')[0]
fid.seek(KIT.STRING, SEEK_CUR) # skips modelname
sqd['nchan'] = unpack('i', fid.read(KIT.INT))[0]
if sysname == 'New York University Abu Dhabi':
KIT_SYS = KIT_AD
elif sysname == 'NYU 160ch System since Jan24 2009':
KIT_SYS = KIT_NY
else:
raise NotImplementedError
# channel locations
fid.seek(KIT_SYS.CHAN_LOC_OFFSET)
chan_offset = unpack('i', fid.read(KIT.INT))[0]
chan_size = unpack('i', fid.read(KIT.INT))[0]
fid.seek(chan_offset)
sensors = []
for i in range(KIT_SYS.N_SENS):
fid.seek(chan_offset + chan_size * i)
sens_type = unpack('i', fid.read(KIT.INT))[0]
if sens_type == 1:
# magnetometer
# x,y,z,theta,phi,coilsize
sensors.append(np.fromfile(fid, dtype='d', count=6))
elif sens_type == 2:
# axialgradiometer
# x,y,z,theta,phi,baseline,coilsize
sensors.append(np.fromfile(fid, dtype='d', count=7))
elif sens_type == 3:
# planargradiometer
# x,y,z,theta,phi,btheta,bphi,baseline,coilsize
sensors.append(np.fromfile(fid, dtype='d', count=9))
elif sens_type == 257:
# reference channels
sensors.append(np.zeros(7))
sqd['i'] = sens_type
sqd['sensor_locs'] = np.array(sensors)
# amplifier gain
fid.seek(KIT_SYS.AMPLIFIER_INFO)
amp_offset = unpack('i', fid.read(KIT_SYS.INT))[0]
fid.seek(amp_offset)
amp_data = unpack('i', fid.read(KIT_SYS.INT))[0]
gain1 = KIT_SYS.GAINS[(KIT_SYS.GAIN1_MASK & amp_data)
>> KIT_SYS.GAIN1_BIT]
gain2 = KIT_SYS.GAINS[(KIT_SYS.GAIN2_MASK & amp_data)
>> KIT_SYS.GAIN2_BIT]
if KIT_SYS.GAIN3_BIT:
gain3 = KIT_SYS.GAINS[(KIT_SYS.GAIN3_MASK & amp_data)
>> KIT_SYS.GAIN3_BIT]
sqd['amp_gain'] = gain1 * gain2 * gain3
else:
sqd['amp_gain'] = gain1 * gain2
# filter settings
sqd['lowpass'] = KIT_SYS.LPFS[(KIT_SYS.LPF_MASK & amp_data)
>> KIT_SYS.LPF_BIT]
sqd['highpass'] = KIT_SYS.HPFS[(KIT_SYS.HPF_MASK & amp_data)
>> KIT_SYS.HPF_BIT]
sqd['notch'] = KIT_SYS.BEFS[(KIT_SYS.BEF_MASK & amp_data)
>> KIT_SYS.BEF_BIT]
# only sensor channels requires gain. the additional misc channels
# (trigger channels, audio and voice channels) are passed
# through unaffected
fid.seek(KIT_SYS.CHAN_SENS)
sens_offset = unpack('i', fid.read(KIT_SYS.INT))[0]
fid.seek(sens_offset)
sens = np.fromfile(fid, dtype='d', count=sqd['nchan'] * 2)
sensitivities = (np.reshape(sens, (sqd['nchan'], 2))
[:KIT_SYS.N_SENS, 1])
sqd['sensor_gain'] = np.ones(KIT_SYS.NCHAN)
sqd['sensor_gain'][:KIT_SYS.N_SENS] = sensitivities
fid.seek(KIT_SYS.SAMPLE_INFO)
acqcond_offset = unpack('i', fid.read(KIT_SYS.INT))[0]
fid.seek(acqcond_offset)
acq_type = unpack('i', fid.read(KIT_SYS.INT))[0]
if acq_type == 1:
sqd['sfreq'] = unpack('d', fid.read(KIT_SYS.DOUBLE))[0]
_ = fid.read(KIT_SYS.INT) # initialized estimate of samples
sqd['nsamples'] = unpack('i', fid.read(KIT_SYS.INT))[0]
else:
err = ("You are probably trying to load a file that is not a "
"continuous recording sqd file.")
raise ValueError(err)
sqd['n_sens'] = KIT_SYS.N_SENS
sqd['nmegchan'] = KIT_SYS.NMEGCHAN
sqd['nmiscchan'] = KIT_SYS.NMISCCHAN
sqd['DYNAMIC_RANGE'] = KIT_SYS.DYNAMIC_RANGE
return sqd
def read_raw_kit(input_fname, mrk=None, elp=None, hsp=None, stim='>',
slope='-', stimthresh=1, preload=False, verbose=None):
"""Reader function for KIT conversion to FIF
Parameters
----------
input_fname : str
Path to the sqd file.
mrk : None | str | array_like, shape = (5, 3) | list of str or array_like
Marker points representing the location of the marker coils with
respect to the MEG Sensors, or path to a marker file.
If list, all of the markers will be averaged together.
elp : None | str | array_like, shape = (8, 3)
Digitizer points representing the location of the fiducials and the
marker coils with respect to the digitized head shape, or path to a
file containing these points.
hsp : None | str | array, shape = (n_points, 3)
Digitizer head shape points, or path to head shape file. If more than
10`000 points are in the head shape, they are automatically decimated.
stim : list of int | '<' | '>'
Channel-value correspondence when converting KIT trigger channels to a
Neuromag-style stim channel. For '<', the largest values are assigned
to the first channel (default). For '>', the largest values are
assigned to the last channel. Can also be specified as a list of
trigger channel indexes.
slope : '+' | '-'
How to interpret values on KIT trigger channels when synthesizing a
Neuromag-style stim channel. With '+', a positive slope (low-to-high)
is interpreted as an event. With '-', a negative slope (high-to-low)
is interpreted as an event.
stimthresh : float
The threshold level for accepting voltage changes in KIT trigger
channels as a trigger event.
preload : bool
If True, all data are loaded at initialization.
If False, data are not read until save.
verbose : bool, str, int, or None
If not None, override default verbose level (see mne.verbose).
"""
return RawKIT(input_fname=input_fname, mrk=mrk, elp=elp, hsp=hsp,
stim=stim, slope=slope, stimthresh=stimthresh,
preload=preload, verbose=verbose) | mne/io/kit/kit.py |
import os
from os import SEEK_CUR
from struct import unpack
import time
import numpy as np
from scipy import linalg
from ..pick import pick_types
from ...coreg import (read_elp, fit_matched_points, _decimate_points,
get_ras_to_neuromag_trans)
from ...utils import verbose, logger
from ...transforms import apply_trans, als_ras_trans, als_ras_trans_mm
from ..base import _BaseRaw
from ..constants import FIFF
from ..meas_info import Info
from ..tag import _loc_to_trans
from .constants import KIT, KIT_NY, KIT_AD
from .coreg import read_hsp, read_mrk
from ...externals.six import string_types
class RawKIT(_BaseRaw):
"""Raw object from KIT SQD file adapted from bti/raw.py
Parameters
----------
input_fname : str
Path to the sqd file.
mrk : None | str | array_like, shape = (5, 3) | list of str or array_like
Marker points representing the location of the marker coils with
respect to the MEG Sensors, or path to a marker file.
If list, all of the markers will be averaged together.
elp : None | str | array_like, shape = (8, 3)
Digitizer points representing the location of the fiducials and the
marker coils with respect to the digitized head shape, or path to a
file containing these points.
hsp : None | str | array, shape = (n_points, 3)
Digitizer head shape points, or path to head shape file. If more than
10`000 points are in the head shape, they are automatically decimated.
stim : list of int | '<' | '>'
Channel-value correspondence when converting KIT trigger channels to a
Neuromag-style stim channel. For '<', the largest values are assigned
to the first channel (default). For '>', the largest values are
assigned to the last channel. Can also be specified as a list of
trigger channel indexes.
slope : '+' | '-'
How to interpret values on KIT trigger channels when synthesizing a
Neuromag-style stim channel. With '+', a positive slope (low-to-high)
is interpreted as an event. With '-', a negative slope (high-to-low)
is interpreted as an event.
stimthresh : float
The threshold level for accepting voltage changes in KIT trigger
channels as a trigger event.
preload : bool
If True, all data are loaded at initialization.
If False, data are not read until save.
verbose : bool, str, int, or None
If not None, override default verbose level (see mne.verbose).
See Also
--------
mne.io.Raw : Documentation of attribute and methods.
"""
@verbose
def __init__(self, input_fname, mrk=None, elp=None, hsp=None, stim='>',
slope='-', stimthresh=1, preload=False, verbose=None):
logger.info('Extracting SQD Parameters from %s...' % input_fname)
input_fname = os.path.abspath(input_fname)
self._sqd_params = get_sqd_params(input_fname)
self._sqd_params['stimthresh'] = stimthresh
self._sqd_params['fname'] = input_fname
logger.info('Creating Raw.info structure...')
# Raw attributes
self.verbose = verbose
self.preload = False
self._projector = None
self.first_samp = 0
self.last_samp = self._sqd_params['nsamples'] - 1
self.comp = None # no compensation for KIT
self.proj = False
# Create raw.info dict for raw fif object with SQD data
self.info = Info()
self.info['meas_id'] = None
self.info['file_id'] = None
self.info['meas_date'] = int(time.time())
self.info['projs'] = []
self.info['comps'] = []
self.info['lowpass'] = self._sqd_params['lowpass']
self.info['highpass'] = self._sqd_params['highpass']
self.info['sfreq'] = float(self._sqd_params['sfreq'])
# meg channels plus synthetic channel
self.info['nchan'] = self._sqd_params['nchan'] + 1
self.info['bads'] = []
self.info['acq_pars'], self.info['acq_stim'] = None, None
self.info['filename'] = None
self.info['ctf_head_t'] = None
self.info['dev_ctf_t'] = []
self._filenames = []
self.info['dig'] = None
self.info['dev_head_t'] = None
if isinstance(mrk, list):
mrk = [read_mrk(marker) if isinstance(marker, string_types)
else marker for marker in mrk]
mrk = np.mean(mrk, axis=0)
if (mrk is not None and elp is not None and hsp is not None):
self._set_dig_kit(mrk, elp, hsp)
elif (mrk is not None or elp is not None or hsp is not None):
err = ("mrk, elp and hsp need to be provided as a group (all or "
"none)")
raise ValueError(err)
# Creates a list of dicts of meg channels for raw.info
logger.info('Setting channel info structure...')
ch_names = {}
ch_names['MEG'] = ['MEG %03d' % ch for ch
in range(1, self._sqd_params['n_sens'] + 1)]
ch_names['MISC'] = ['MISC %03d' % ch for ch
in range(1, self._sqd_params['nmiscchan'] + 1)]
ch_names['STIM'] = ['STI 014']
locs = self._sqd_params['sensor_locs']
chan_locs = apply_trans(als_ras_trans, locs[:, :3])
chan_angles = locs[:, 3:]
self.info['chs'] = []
for idx, ch_info in enumerate(zip(ch_names['MEG'], chan_locs,
chan_angles), 1):
ch_name, ch_loc, ch_angles = ch_info
chan_info = {}
chan_info['cal'] = KIT.CALIB_FACTOR
chan_info['logno'] = idx
chan_info['scanno'] = idx
chan_info['range'] = KIT.RANGE
chan_info['unit_mul'] = KIT.UNIT_MUL
chan_info['ch_name'] = ch_name
chan_info['unit'] = FIFF.FIFF_UNIT_T
chan_info['coord_frame'] = FIFF.FIFFV_COORD_DEVICE
if idx <= self._sqd_params['nmegchan']:
chan_info['coil_type'] = FIFF.FIFFV_COIL_KIT_GRAD
chan_info['kind'] = FIFF.FIFFV_MEG_CH
else:
chan_info['coil_type'] = FIFF.FIFFV_COIL_KIT_REF_MAG
chan_info['kind'] = FIFF.FIFFV_REF_MEG_CH
chan_info['eeg_loc'] = None
# create three orthogonal vector
# ch_angles[0]: theta, ch_angles[1]: phi
ch_angles = np.radians(ch_angles)
x = np.sin(ch_angles[0]) * np.cos(ch_angles[1])
y = np.sin(ch_angles[0]) * np.sin(ch_angles[1])
z = np.cos(ch_angles[0])
vec_z = np.array([x, y, z])
length = linalg.norm(vec_z)
vec_z /= length
vec_x = np.zeros(vec_z.size, dtype=np.float)
if vec_z[1] < vec_z[2]:
if vec_z[0] < vec_z[1]:
vec_x[0] = 1.0
else:
vec_x[1] = 1.0
elif vec_z[0] < vec_z[2]:
vec_x[0] = 1.0
else:
vec_x[2] = 1.0
vec_x -= np.sum(vec_x * vec_z) * vec_z
length = linalg.norm(vec_x)
vec_x /= length
vec_y = np.cross(vec_z, vec_x)
# transform to Neuromag like coordinate space
vecs = np.vstack((vec_x, vec_y, vec_z))
vecs = apply_trans(als_ras_trans, vecs)
chan_info['loc'] = np.vstack((ch_loc, vecs)).ravel()
chan_info['coil_trans'] = _loc_to_trans(chan_info['loc'])
self.info['chs'].append(chan_info)
# label trigger and misc channels
for idy, ch_name in enumerate(ch_names['MISC'] + ch_names['STIM'],
self._sqd_params['n_sens']):
chan_info = {}
chan_info['cal'] = KIT.CALIB_FACTOR
chan_info['logno'] = idy
chan_info['scanno'] = idy
chan_info['range'] = 1.0
chan_info['unit'] = FIFF.FIFF_UNIT_V
chan_info['unit_mul'] = 0 # default is 0 mne_manual p.273
chan_info['ch_name'] = ch_name
chan_info['coil_type'] = FIFF.FIFFV_COIL_NONE
chan_info['loc'] = np.zeros(12)
if ch_name.startswith('STI'):
chan_info['unit'] = FIFF.FIFF_UNIT_NONE
chan_info['kind'] = FIFF.FIFFV_STIM_CH
else:
chan_info['kind'] = FIFF.FIFFV_MISC_CH
self.info['chs'].append(chan_info)
self.info['ch_names'] = (ch_names['MEG'] + ch_names['MISC'] +
ch_names['STIM'])
self._set_stimchannels(stim, slope)
if preload:
self.preload = preload
logger.info('Reading raw data from %s...' % input_fname)
self._data, _ = self._read_segment()
assert len(self._data) == self.info['nchan']
# Create a synthetic channel
stim = self._sqd_params['stim']
trig_chs = self._data[stim, :]
if slope == '+':
trig_chs = trig_chs > stimthresh
elif slope == '-':
trig_chs = trig_chs < stimthresh
else:
raise ValueError("slope needs to be '+' or '-'")
trig_vals = np.array(2 ** np.arange(len(stim)), ndmin=2).T
trig_chs = trig_chs * trig_vals
stim_ch = trig_chs.sum(axis=0)
self._data[-1, :] = stim_ch
# Add time info
self.first_samp, self.last_samp = 0, self._data.shape[1] - 1
self._times = np.arange(self.first_samp, self.last_samp + 1,
dtype=np.float64)
self._times /= self.info['sfreq']
logger.info(' Range : %d ... %d = %9.3f ... %9.3f secs'
% (self.first_samp, self.last_samp,
float(self.first_samp) / self.info['sfreq'],
float(self.last_samp) / self.info['sfreq']))
logger.info('Ready.')
def __repr__(self):
s = ('%r' % os.path.basename(self._sqd_params['fname']),
"n_channels x n_times : %s x %s" % (len(self.info['ch_names']),
self.last_samp -
self.first_samp + 1))
return "<RawKIT | %s>" % ', '.join(s)
def read_stim_ch(self, buffer_size=1e5):
"""Read events from data
Parameter
---------
buffer_size : int
The size of chunk to by which the data are scanned.
Returns
-------
events : array, [samples]
The event vector (1 x samples).
"""
buffer_size = int(buffer_size)
start = int(self.first_samp)
stop = int(self.last_samp + 1)
pick = pick_types(self.info, meg=False, ref_meg=False,
stim=True, exclude=[])
stim_ch = np.empty((1, stop), dtype=np.int)
for b_start in range(start, stop, buffer_size):
b_stop = b_start + buffer_size
x, _ = self._read_segment(start=b_start, stop=b_stop, sel=pick)
stim_ch[:, b_start:b_start + x.shape[1]] = x
return stim_ch
def _read_segment(self, start=0, stop=None, sel=None, verbose=None,
projector=None):
"""Read a chunk of raw data
Parameters
----------
start : int, (optional)
first sample to include (first is 0). If omitted, defaults to the
first sample in data.
stop : int, (optional)
First sample to not include.
If omitted, data is included to the end.
sel : array, optional
Indices of channels to select.
projector : array
SSP operator to apply to the data.
verbose : bool, str, int, or None
If not None, override default verbose level (see mne.verbose).
Returns
-------
data : array, [channels x samples]
the data matrix (channels x samples).
times : array, [samples]
returns the time values corresponding to the samples.
"""
if sel is None:
sel = list(range(self.info['nchan']))
elif len(sel) == 1 and sel[0] == 0 and start == 0 and stop == 1:
return (666, 666)
if projector is not None:
raise NotImplementedError('Currently does not handle projections.')
if stop is None:
stop = self.last_samp + 1
elif stop > self.last_samp + 1:
stop = self.last_samp + 1
# Initial checks
start = int(start)
stop = int(stop)
if start >= stop:
raise ValueError('No data in this range')
logger.info('Reading %d ... %d = %9.3f ... %9.3f secs...' %
(start, stop - 1, start / float(self.info['sfreq']),
(stop - 1) / float(self.info['sfreq'])))
with open(self._sqd_params['fname'], 'rb', buffering=0) as fid:
# extract data
fid.seek(KIT.DATA_OFFSET)
# data offset info
data_offset = unpack('i', fid.read(KIT.INT))[0]
nchan = self._sqd_params['nchan']
buffer_size = stop - start
count = buffer_size * nchan
pointer = start * nchan * KIT.SHORT
fid.seek(data_offset + pointer)
data = np.fromfile(fid, dtype='h', count=count)
data = data.reshape((buffer_size, nchan))
# amplifier applies only to the sensor channels
n_sens = self._sqd_params['n_sens']
sensor_gain = np.copy(self._sqd_params['sensor_gain'])
sensor_gain[:n_sens] = (sensor_gain[:n_sens] /
self._sqd_params['amp_gain'])
conv_factor = np.array((KIT.VOLTAGE_RANGE /
self._sqd_params['DYNAMIC_RANGE'])
* sensor_gain, ndmin=2)
data = conv_factor * data
data = data.T
# Create a synthetic channel
trig_chs = data[self._sqd_params['stim'], :]
if self._sqd_params['slope'] == '+':
trig_chs = trig_chs > self._sqd_params['stimthresh']
elif self._sqd_params['slope'] == '-':
trig_chs = trig_chs < self._sqd_params['stimthresh']
else:
raise ValueError("slope needs to be '+' or '-'")
trig_vals = np.array(2 ** np.arange(len(self._sqd_params['stim'])),
ndmin=2).T
trig_chs = trig_chs * trig_vals
stim_ch = np.array(trig_chs.sum(axis=0), ndmin=2)
data = np.vstack((data, stim_ch))
data = data[sel]
logger.info('[done]')
times = np.arange(start, stop) / self.info['sfreq']
return data, times
def _set_dig_kit(self, mrk, elp, hsp, auto_decimate=True):
"""Add landmark points and head shape data to the RawKIT instance
Digitizer data (elp and hsp) are represented in [mm] in the Polhemus
ALS coordinate system.
Parameters
----------
mrk : None | str | array_like, shape = (5, 3)
Marker points representing the location of the marker coils with
respect to the MEG Sensors, or path to a marker file.
elp : None | str | array_like, shape = (8, 3)
Digitizer points representing the location of the fiducials and the
marker coils with respect to the digitized head shape, or path to a
file containing these points.
hsp : None | str | array, shape = (n_points, 3)
Digitizer head shape points, or path to head shape file. If more
than 10`000 points are in the head shape, they are automatically
decimated.
auto_decimate : bool
Decimate hsp points for head shape files with more than 10'000
points.
"""
if isinstance(hsp, string_types):
hsp = read_hsp(hsp)
n_pts = len(hsp)
if n_pts > KIT.DIG_POINTS:
hsp = _decimate_points(hsp, 5)
n_new = len(hsp)
msg = ("The selected head shape contained {n_in} points, which is "
"more than recommended ({n_rec}), and was automatically "
"downsampled to {n_new} points. The preferred way to "
"downsample is using FastScan.")
msg = msg.format(n_in=n_pts, n_rec=KIT.DIG_POINTS, n_new=n_new)
logger.warning(msg)
if isinstance(elp, string_types):
elp_points = read_elp(elp)[:8]
if len(elp) < 8:
err = ("File %r contains fewer than 8 points; got shape "
"%s." % (elp, elp_points.shape))
raise ValueError(err)
elp = elp_points
if isinstance(mrk, string_types):
mrk = read_mrk(mrk)
hsp = apply_trans(als_ras_trans_mm, hsp)
elp = apply_trans(als_ras_trans_mm, elp)
mrk = apply_trans(als_ras_trans, mrk)
nasion, lpa, rpa = elp[:3]
nmtrans = get_ras_to_neuromag_trans(nasion, lpa, rpa)
elp = apply_trans(nmtrans, elp)
hsp = apply_trans(nmtrans, hsp)
# device head transform
trans = fit_matched_points(tgt_pts=elp[3:], src_pts=mrk, out='trans')
self._set_dig_neuromag(elp[:3], elp[3:], hsp, trans)
def _set_dig_neuromag(self, fid, elp, hsp, trans):
"""Fill in the digitizer data using points in neuromag space
Parameters
----------
fid : array, shape = (3, 3)
Digitizer fiducials.
elp : array, shape = (5, 3)
Digitizer ELP points.
hsp : array, shape = (n_points, 3)
Head shape points.
trans : None | array, shape = (4, 4)
Device head transformation.
"""
trans = np.asarray(trans)
if fid.shape != (3, 3):
raise ValueError("fid needs to be a 3 by 3 array")
if elp.shape != (5, 3):
raise ValueError("elp needs to be a 5 by 3 array")
if trans.shape != (4, 4):
raise ValueError("trans needs to be 4 by 4 array")
nasion, lpa, rpa = fid
dig = [{'r': nasion, 'ident': FIFF.FIFFV_POINT_NASION,
'kind': FIFF.FIFFV_POINT_CARDINAL,
'coord_frame': FIFF.FIFFV_COORD_HEAD},
{'r': lpa, 'ident': FIFF.FIFFV_POINT_LPA,
'kind': FIFF.FIFFV_POINT_CARDINAL,
'coord_frame': FIFF.FIFFV_COORD_HEAD},
{'r': rpa, 'ident': FIFF.FIFFV_POINT_RPA,
'kind': FIFF.FIFFV_POINT_CARDINAL,
'coord_frame': FIFF.FIFFV_COORD_HEAD}]
for idx, point in enumerate(elp):
dig.append({'r': point, 'ident': idx, 'kind': FIFF.FIFFV_POINT_HPI,
'coord_frame': FIFF.FIFFV_COORD_HEAD})
for idx, point in enumerate(hsp):
dig.append({'r': point, 'ident': idx,
'kind': FIFF.FIFFV_POINT_EXTRA,
'coord_frame': FIFF.FIFFV_COORD_HEAD})
dev_head_t = {'from': FIFF.FIFFV_COORD_DEVICE,
'to': FIFF.FIFFV_COORD_HEAD, 'trans': trans}
self.info['dig'] = dig
self.info['dev_head_t'] = dev_head_t
def _set_stimchannels(self, stim='<', slope='-'):
"""Specify how the trigger channel is synthesized form analog channels.
Has to be done before loading data. For a RawKIT instance that has been
created with preload=True, this method will raise a
NotImplementedError.
Parameters
----------
stim : list of int | '<' | '>'
Can be submitted as list of trigger channels.
If a list is not specified, the default triggers extracted from
misc channels will be used with specified directionality.
'<' means that largest values assigned to the first channel
in sequence.
'>' means the largest trigger assigned to the last channel
in sequence.
slope : '+' | '-'
'+' means a positive slope (low-to-high) on the event channel(s)
is used to trigger an event.
'-' means a negative slope (high-to-low) on the event channel(s)
is used to trigger an event.
"""
if self.preload:
err = "Can't change stim channel after preloading data"
raise NotImplementedError(err)
self._sqd_params['slope'] = slope
if isinstance(stim, str):
picks = pick_types(self.info, meg=False, ref_meg=False,
misc=True, exclude=[])[:8]
if stim == '<':
stim = picks[::-1]
elif stim == '>':
stim = picks
else:
raise ValueError("stim needs to be list of int, '>' or "
"'<', not %r" % str(stim))
elif np.max(stim) >= self._sqd_params['nchan']:
msg = ("Tried to set stim channel %i, but squid file only has %i"
" channels" % (np.max(stim), self._sqd_params['nchan']))
raise ValueError(msg)
self._sqd_params['stim'] = stim
def get_sqd_params(rawfile):
"""Extracts all the information from the sqd file.
Parameters
----------
rawfile : str
Raw sqd file to be read.
Returns
-------
sqd : dict
A dict containing all the sqd parameter settings.
"""
sqd = dict()
sqd['rawfile'] = rawfile
with open(rawfile, 'rb', buffering=0) as fid: # buffering=0 for np bug
fid.seek(KIT.BASIC_INFO)
basic_offset = unpack('i', fid.read(KIT.INT))[0]
fid.seek(basic_offset)
# skips version, revision, sysid
fid.seek(KIT.INT * 3, SEEK_CUR)
# basic info
sysname = unpack('128s', fid.read(KIT.STRING))
sysname = sysname[0].decode().split('\n')[0]
fid.seek(KIT.STRING, SEEK_CUR) # skips modelname
sqd['nchan'] = unpack('i', fid.read(KIT.INT))[0]
if sysname == 'New York University Abu Dhabi':
KIT_SYS = KIT_AD
elif sysname == 'NYU 160ch System since Jan24 2009':
KIT_SYS = KIT_NY
else:
raise NotImplementedError
# channel locations
fid.seek(KIT_SYS.CHAN_LOC_OFFSET)
chan_offset = unpack('i', fid.read(KIT.INT))[0]
chan_size = unpack('i', fid.read(KIT.INT))[0]
fid.seek(chan_offset)
sensors = []
for i in range(KIT_SYS.N_SENS):
fid.seek(chan_offset + chan_size * i)
sens_type = unpack('i', fid.read(KIT.INT))[0]
if sens_type == 1:
# magnetometer
# x,y,z,theta,phi,coilsize
sensors.append(np.fromfile(fid, dtype='d', count=6))
elif sens_type == 2:
# axialgradiometer
# x,y,z,theta,phi,baseline,coilsize
sensors.append(np.fromfile(fid, dtype='d', count=7))
elif sens_type == 3:
# planargradiometer
# x,y,z,theta,phi,btheta,bphi,baseline,coilsize
sensors.append(np.fromfile(fid, dtype='d', count=9))
elif sens_type == 257:
# reference channels
sensors.append(np.zeros(7))
sqd['i'] = sens_type
sqd['sensor_locs'] = np.array(sensors)
# amplifier gain
fid.seek(KIT_SYS.AMPLIFIER_INFO)
amp_offset = unpack('i', fid.read(KIT_SYS.INT))[0]
fid.seek(amp_offset)
amp_data = unpack('i', fid.read(KIT_SYS.INT))[0]
gain1 = KIT_SYS.GAINS[(KIT_SYS.GAIN1_MASK & amp_data)
>> KIT_SYS.GAIN1_BIT]
gain2 = KIT_SYS.GAINS[(KIT_SYS.GAIN2_MASK & amp_data)
>> KIT_SYS.GAIN2_BIT]
if KIT_SYS.GAIN3_BIT:
gain3 = KIT_SYS.GAINS[(KIT_SYS.GAIN3_MASK & amp_data)
>> KIT_SYS.GAIN3_BIT]
sqd['amp_gain'] = gain1 * gain2 * gain3
else:
sqd['amp_gain'] = gain1 * gain2
# filter settings
sqd['lowpass'] = KIT_SYS.LPFS[(KIT_SYS.LPF_MASK & amp_data)
>> KIT_SYS.LPF_BIT]
sqd['highpass'] = KIT_SYS.HPFS[(KIT_SYS.HPF_MASK & amp_data)
>> KIT_SYS.HPF_BIT]
sqd['notch'] = KIT_SYS.BEFS[(KIT_SYS.BEF_MASK & amp_data)
>> KIT_SYS.BEF_BIT]
# only sensor channels requires gain. the additional misc channels
# (trigger channels, audio and voice channels) are passed
# through unaffected
fid.seek(KIT_SYS.CHAN_SENS)
sens_offset = unpack('i', fid.read(KIT_SYS.INT))[0]
fid.seek(sens_offset)
sens = np.fromfile(fid, dtype='d', count=sqd['nchan'] * 2)
sensitivities = (np.reshape(sens, (sqd['nchan'], 2))
[:KIT_SYS.N_SENS, 1])
sqd['sensor_gain'] = np.ones(KIT_SYS.NCHAN)
sqd['sensor_gain'][:KIT_SYS.N_SENS] = sensitivities
fid.seek(KIT_SYS.SAMPLE_INFO)
acqcond_offset = unpack('i', fid.read(KIT_SYS.INT))[0]
fid.seek(acqcond_offset)
acq_type = unpack('i', fid.read(KIT_SYS.INT))[0]
if acq_type == 1:
sqd['sfreq'] = unpack('d', fid.read(KIT_SYS.DOUBLE))[0]
_ = fid.read(KIT_SYS.INT) # initialized estimate of samples
sqd['nsamples'] = unpack('i', fid.read(KIT_SYS.INT))[0]
else:
err = ("You are probably trying to load a file that is not a "
"continuous recording sqd file.")
raise ValueError(err)
sqd['n_sens'] = KIT_SYS.N_SENS
sqd['nmegchan'] = KIT_SYS.NMEGCHAN
sqd['nmiscchan'] = KIT_SYS.NMISCCHAN
sqd['DYNAMIC_RANGE'] = KIT_SYS.DYNAMIC_RANGE
return sqd
def read_raw_kit(input_fname, mrk=None, elp=None, hsp=None, stim='>',
slope='-', stimthresh=1, preload=False, verbose=None):
"""Reader function for KIT conversion to FIF
Parameters
----------
input_fname : str
Path to the sqd file.
mrk : None | str | array_like, shape = (5, 3) | list of str or array_like
Marker points representing the location of the marker coils with
respect to the MEG Sensors, or path to a marker file.
If list, all of the markers will be averaged together.
elp : None | str | array_like, shape = (8, 3)
Digitizer points representing the location of the fiducials and the
marker coils with respect to the digitized head shape, or path to a
file containing these points.
hsp : None | str | array, shape = (n_points, 3)
Digitizer head shape points, or path to head shape file. If more than
10`000 points are in the head shape, they are automatically decimated.
stim : list of int | '<' | '>'
Channel-value correspondence when converting KIT trigger channels to a
Neuromag-style stim channel. For '<', the largest values are assigned
to the first channel (default). For '>', the largest values are
assigned to the last channel. Can also be specified as a list of
trigger channel indexes.
slope : '+' | '-'
How to interpret values on KIT trigger channels when synthesizing a
Neuromag-style stim channel. With '+', a positive slope (low-to-high)
is interpreted as an event. With '-', a negative slope (high-to-low)
is interpreted as an event.
stimthresh : float
The threshold level for accepting voltage changes in KIT trigger
channels as a trigger event.
preload : bool
If True, all data are loaded at initialization.
If False, data are not read until save.
verbose : bool, str, int, or None
If not None, override default verbose level (see mne.verbose).
"""
return RawKIT(input_fname=input_fname, mrk=mrk, elp=elp, hsp=hsp,
stim=stim, slope=slope, stimthresh=stimthresh,
preload=preload, verbose=verbose) | 0.681091 | 0.261698 |
# Import Statements
import subprocess # Subprocess example: subprocess.run(["ls", "-l"])
import pandas as pd
import datetime
import logging
# Function to convert microSWIFT file name to datetime
def get_microSWIFT_file_time(fname):
import datetime
# Convert Month string to month num
month_str = fname[-21:-18]
# January
if month_str == 'Jan':
month_num = '01'
# February
if month_str == 'Feb':
month_num = '02'
# March
if month_str == 'Mar':
month_num = '03'
# April
if month_str == 'Apr':
month_num = '04'
# May
if month_str == 'May':
month_num = '05'
# June
if month_str == 'Jun':
month_num = '06'
# July
if month_str == 'Jul':
month_num = '07'
# August
if month_str == 'Aug':
month_num = '08'
# September
if month_str == 'Sep':
month_num = '09'
# October
if month_str == 'Oct':
month_num = '10'
# November
if month_str == 'Nov':
month_num = '11'
# December
if month_str == 'Dec':
month_num = '12'
# Compute Datetime
date_str = '{0}-{1}-{2}T{3}:{4}:{5}'.format(fname[-18:-14], month_num, fname[-23:-21], fname[-13:-11], fname[-11:-9], fname[-9:-7])
microSWIFT_file_time = datetime.datetime.fromisoformat(date_str)
return microSWIFT_file_time
# Define microSWIFT IP address and Password
IP="192.168.0."
PASSWORD="<PASSWORD>"
# Define record Window Length
record_window_length = datetime.timedelta(hours=1)
# Define project directory
project_dir = '../'
# Define Metadata Excel sheet name
metadata_name = 'DUNEXMainExp_notes.xlsx'
# Combine file name and project Directory
metadata_filename = project_dir + metadata_name
# User input for mission number
mission_num = int(input('Enter Mission Number: '))
# Create Data Directory for Mission
mission_dir_str = project_dir + "/microSWIFT_data/mission_{}".format(mission_num)
subprocess.run(["mkdir", "-p", mission_dir_str])
# Set up Data Offload Logging file
log_name = mission_dir_str + '/data_offload.log'
logging.basicConfig(filename=log_name, encoding='utf-8', level=logging.DEBUG)
logging.info('------------ Mission {} Data Offload ------------'.format(mission_num))
# Create dataframe object from DUNEX MetaData SpreadSheet
dunex_xlsx = pd.read_excel(metadata_filename)
# Read in Start Time and convert to datetime
start_time = datetime.datetime.fromisoformat(dunex_xlsx['Start Time'].iloc[mission_num])
logging.info('Mission Start Time is: {}'.format(start_time))
# Read in End Time and convert to datetime
end_time = datetime.datetime.fromisoformat(dunex_xlsx['End Time'].iloc[mission_num])
logging.info('Mission End Time is: {}'.format(end_time))
# Read in list of microSWIFTs Deployed during the mission
microSWIFTs_deployed = []
for microSWIFT in dunex_xlsx['microSWIFTs Deployed'].iloc[mission_num].split(','):
microSWIFTs_deployed.append(int(microSWIFT))
logging.info('microSWIFTs Deployed on this mission were: {}'.format(microSWIFTs_deployed))
# Get list of microSWIFTs that were retrieved
microSWIFTs_retrieved = []
for microSWIFT in dunex_xlsx['microSWIFTs Retrieved'].iloc[mission_num].split(','):
microSWIFTs_retrieved.append(int(microSWIFT))
logging.info('microSWIFTs Deployed on this mission were: {}'.format(microSWIFTs_retrieved))
# Loop through each microSWIFT on the network to offload data
time_to_offload_list = []
num_offloaded = 0
microSWIFTs_not_offloaded = []
num_not_offloaded = 0
logging.info('------------ Data Offload ------------')
for microSWIFT in microSWIFTs_retrieved:
# Offload time
start_offload_time = datetime.datetime.utcnow()
# Ping microSWIFT to see if it is on the network
microSWIFT_ip_address = IP + str(microSWIFT)
ping = subprocess.run(['ping', '-c', '2', microSWIFT_ip_address])
ping_val = ping.returncode
# If microSWIFT is on network (return code from process is zero)
if ping_val == 0:
logging.info('microSWIFT {} is online'.format(microSWIFT))
# Make Directory for this microSWIFT
microSWIFT_dir_str = mission_dir_str + '/microSWIFT_{}'.format(microSWIFT)
subprocess.run(["mkdir", "-p", microSWIFT_dir_str])
# Copy microSWIFT log into the microSWIFT directory
# To download on mac OS use the command: brew install hudochenkov/sshpass/sshpass
log_offload_process = subprocess.run(['sshpass', '-p', PASSWORD, 'scp', 'pi@{}:/home/pi/microSWIFT/logs/microSWIFT.log'.format(microSWIFT_ip_address), microSWIFT_dir_str ])
log_offload_process_rc = log_offload_process.returncode
if log_offload_process_rc == 0:
logging.info('--- microSWIFT.log offloaded')
else:
logging.info('--- microSWIFT.log could not be offloaded')
# Get list of all data files on microSWIFT
list_of_data_files = subprocess.run(['sshpass', '-p', PASSWORD, 'ssh', 'pi@{}'.format(microSWIFT_ip_address), 'ls ~/microSWIFT/data'], stdout=subprocess.PIPE, text=True).stdout.splitlines()
# Sort through each file to see if it is within the mission (within 1 record window)
for file_name in list_of_data_files:
# Get aware time object of when file was created
file_time = get_microSWIFT_file_time(file_name)
# Compare to see if it was within the mission time frame or within one burst length of the mission start time
if (file_time >= (start_time - record_window_length) and file_time <= end_time):
subprocess.run(['sshpass', '-p', PASSWORD, 'scp', 'pi@{0}:/home/pi/microSWIFT/data/{1}'.format(microSWIFT_ip_address, file_name), microSWIFT_dir_str])
logging.info('--- {0} was copied to microSWIFT {1} data directory'.format(file_name, microSWIFT))
else:
continue
# End Offload time
num_offloaded += 1
time_to_offload_datetime = datetime.datetime.utcnow() - start_offload_time
time_to_offload_float = time_to_offload_datetime.total_seconds()
time_to_offload_list.append(time_to_offload_float)
else:
logging.info('microSWIFT {} is offline'.format(microSWIFT))
microSWIFTs_not_offloaded.append(microSWIFT)
num_not_offloaded += 1
# End of Data Offloading - Log offload statistics
# microSWIFTs that were not offloaded
if num_not_offloaded == 0:
logging.info('All microSWIFTs on mission were offloaded')
else:
logging.info('{0} microSWIFTs that were not offloaded were {1}'.format(num_not_offloaded, microSWIFTs_not_offloaded))
# Offload times
time_to_offload_avg = sum(time_to_offload_list)/num_offloaded
logging.info('The average offload time was {}'.format(time_to_offload_avg)) | tools/getmicroSWIFTData.py | # Import Statements
import subprocess # Subprocess example: subprocess.run(["ls", "-l"])
import pandas as pd
import datetime
import logging
# Function to convert microSWIFT file name to datetime
def get_microSWIFT_file_time(fname):
import datetime
# Convert Month string to month num
month_str = fname[-21:-18]
# January
if month_str == 'Jan':
month_num = '01'
# February
if month_str == 'Feb':
month_num = '02'
# March
if month_str == 'Mar':
month_num = '03'
# April
if month_str == 'Apr':
month_num = '04'
# May
if month_str == 'May':
month_num = '05'
# June
if month_str == 'Jun':
month_num = '06'
# July
if month_str == 'Jul':
month_num = '07'
# August
if month_str == 'Aug':
month_num = '08'
# September
if month_str == 'Sep':
month_num = '09'
# October
if month_str == 'Oct':
month_num = '10'
# November
if month_str == 'Nov':
month_num = '11'
# December
if month_str == 'Dec':
month_num = '12'
# Compute Datetime
date_str = '{0}-{1}-{2}T{3}:{4}:{5}'.format(fname[-18:-14], month_num, fname[-23:-21], fname[-13:-11], fname[-11:-9], fname[-9:-7])
microSWIFT_file_time = datetime.datetime.fromisoformat(date_str)
return microSWIFT_file_time
# Define microSWIFT IP address and Password
IP="192.168.0."
PASSWORD="<PASSWORD>"
# Define record Window Length
record_window_length = datetime.timedelta(hours=1)
# Define project directory
project_dir = '../'
# Define Metadata Excel sheet name
metadata_name = 'DUNEXMainExp_notes.xlsx'
# Combine file name and project Directory
metadata_filename = project_dir + metadata_name
# User input for mission number
mission_num = int(input('Enter Mission Number: '))
# Create Data Directory for Mission
mission_dir_str = project_dir + "/microSWIFT_data/mission_{}".format(mission_num)
subprocess.run(["mkdir", "-p", mission_dir_str])
# Set up Data Offload Logging file
log_name = mission_dir_str + '/data_offload.log'
logging.basicConfig(filename=log_name, encoding='utf-8', level=logging.DEBUG)
logging.info('------------ Mission {} Data Offload ------------'.format(mission_num))
# Create dataframe object from DUNEX MetaData SpreadSheet
dunex_xlsx = pd.read_excel(metadata_filename)
# Read in Start Time and convert to datetime
start_time = datetime.datetime.fromisoformat(dunex_xlsx['Start Time'].iloc[mission_num])
logging.info('Mission Start Time is: {}'.format(start_time))
# Read in End Time and convert to datetime
end_time = datetime.datetime.fromisoformat(dunex_xlsx['End Time'].iloc[mission_num])
logging.info('Mission End Time is: {}'.format(end_time))
# Read in list of microSWIFTs Deployed during the mission
microSWIFTs_deployed = []
for microSWIFT in dunex_xlsx['microSWIFTs Deployed'].iloc[mission_num].split(','):
microSWIFTs_deployed.append(int(microSWIFT))
logging.info('microSWIFTs Deployed on this mission were: {}'.format(microSWIFTs_deployed))
# Get list of microSWIFTs that were retrieved
microSWIFTs_retrieved = []
for microSWIFT in dunex_xlsx['microSWIFTs Retrieved'].iloc[mission_num].split(','):
microSWIFTs_retrieved.append(int(microSWIFT))
logging.info('microSWIFTs Deployed on this mission were: {}'.format(microSWIFTs_retrieved))
# Loop through each microSWIFT on the network to offload data
time_to_offload_list = []
num_offloaded = 0
microSWIFTs_not_offloaded = []
num_not_offloaded = 0
logging.info('------------ Data Offload ------------')
for microSWIFT in microSWIFTs_retrieved:
# Offload time
start_offload_time = datetime.datetime.utcnow()
# Ping microSWIFT to see if it is on the network
microSWIFT_ip_address = IP + str(microSWIFT)
ping = subprocess.run(['ping', '-c', '2', microSWIFT_ip_address])
ping_val = ping.returncode
# If microSWIFT is on network (return code from process is zero)
if ping_val == 0:
logging.info('microSWIFT {} is online'.format(microSWIFT))
# Make Directory for this microSWIFT
microSWIFT_dir_str = mission_dir_str + '/microSWIFT_{}'.format(microSWIFT)
subprocess.run(["mkdir", "-p", microSWIFT_dir_str])
# Copy microSWIFT log into the microSWIFT directory
# To download on mac OS use the command: brew install hudochenkov/sshpass/sshpass
log_offload_process = subprocess.run(['sshpass', '-p', PASSWORD, 'scp', 'pi@{}:/home/pi/microSWIFT/logs/microSWIFT.log'.format(microSWIFT_ip_address), microSWIFT_dir_str ])
log_offload_process_rc = log_offload_process.returncode
if log_offload_process_rc == 0:
logging.info('--- microSWIFT.log offloaded')
else:
logging.info('--- microSWIFT.log could not be offloaded')
# Get list of all data files on microSWIFT
list_of_data_files = subprocess.run(['sshpass', '-p', PASSWORD, 'ssh', 'pi@{}'.format(microSWIFT_ip_address), 'ls ~/microSWIFT/data'], stdout=subprocess.PIPE, text=True).stdout.splitlines()
# Sort through each file to see if it is within the mission (within 1 record window)
for file_name in list_of_data_files:
# Get aware time object of when file was created
file_time = get_microSWIFT_file_time(file_name)
# Compare to see if it was within the mission time frame or within one burst length of the mission start time
if (file_time >= (start_time - record_window_length) and file_time <= end_time):
subprocess.run(['sshpass', '-p', PASSWORD, 'scp', 'pi@{0}:/home/pi/microSWIFT/data/{1}'.format(microSWIFT_ip_address, file_name), microSWIFT_dir_str])
logging.info('--- {0} was copied to microSWIFT {1} data directory'.format(file_name, microSWIFT))
else:
continue
# End Offload time
num_offloaded += 1
time_to_offload_datetime = datetime.datetime.utcnow() - start_offload_time
time_to_offload_float = time_to_offload_datetime.total_seconds()
time_to_offload_list.append(time_to_offload_float)
else:
logging.info('microSWIFT {} is offline'.format(microSWIFT))
microSWIFTs_not_offloaded.append(microSWIFT)
num_not_offloaded += 1
# End of Data Offloading - Log offload statistics
# microSWIFTs that were not offloaded
if num_not_offloaded == 0:
logging.info('All microSWIFTs on mission were offloaded')
else:
logging.info('{0} microSWIFTs that were not offloaded were {1}'.format(num_not_offloaded, microSWIFTs_not_offloaded))
# Offload times
time_to_offload_avg = sum(time_to_offload_list)/num_offloaded
logging.info('The average offload time was {}'.format(time_to_offload_avg)) | 0.302082 | 0.243958 |
from codegen.utils import (
remove_c_comments,
blacken,
Patcher,
to_snake_case,
to_camel_case,
)
from pytest import raises
def dedent(code):
return code.replace("\n ", "\n")
def test_to_snake_case():
assert to_snake_case("foo_bar_spam") == "foo_bar_spam"
assert to_snake_case("_foo_bar_spam") == "_foo_bar_spam"
assert to_snake_case("fooBarSpam") == "foo_bar_spam"
assert to_snake_case("_fooBarSpam") == "_foo_bar_spam"
assert to_snake_case("maxTextureDimension1D") == "max_texture_dimension1d"
def test_to_camel_case():
assert to_camel_case("foo_bar_spam") == "fooBarSpam"
assert to_camel_case("_foo_bar_spam") == "_fooBarSpam"
assert to_camel_case("fooBarSpam") == "fooBarSpam"
assert to_camel_case("_fooBarSpam") == "_fooBarSpam"
assert to_camel_case("max_texture_dimension1d") == "maxTextureDimension1D"
def test_remove_c_comments():
code1 = """
x1 hello// comment
// comment
x2 hello/* comment */
x3/* comment */ hello
x4 /* comment
comment
*/hello
"""
code3 = """
x1 hello
x2 hello
x3 hello
x4 hello
"""
code1, code3 = dedent(code1), dedent(code3)
code2 = remove_c_comments(code1)
assert code2 == code3
def test_blacken_singleline():
code1 = """
def foo():
pass
def foo(
):
pass
def foo(
a1, a2, a3
):
pass
def foo(
a1, a2, a3,
):
pass
def foo(
a1,
a2,
a3,
):
pass
"""
code2 = """
def foo():
pass
def foo():
pass
def foo(a1, a2, a3):
pass
def foo(a1, a2, a3):
pass
def foo(a1, a2, a3):
pass
"""
code1 = dedent(code1).strip()
code2 = dedent(code2).strip()
code3 = blacken(code1, True)
code3 = code3.replace("\n\n", "\n").replace("\n\n", "\n").strip()
assert code3 == code2
# Also test simply long lines
code = "foo = 1" + " + 1" * 100
assert len(code) > 300
assert code.count("\n") == 0
assert blacken(code, False).strip().count("\n") > 3
assert blacken(code, True).strip().count("\n") == 0
def test_blacken_comments():
code1 = """
def foo(): # hi
pass
def foo(
a1, # hi
a2, # ha
a3,
): # ho
pass
"""
code2 = """
def foo(): # hi
pass
def foo(a1, a2, a3): # hi ha ho
pass
"""
code1 = dedent(code1).strip()
code2 = dedent(code2).strip()
code3 = blacken(code1, True)
code3 = code3.replace("\n\n", "\n").replace("\n\n", "\n").strip()
assert code3 == code2
def test_patcher():
code = """
class Foo1:
def bar1(self):
pass
def bar2(self):
pass
@property
def bar3(self):
pass
class Foo2:
def bar1(self):
pass
@property
def bar2(self):
pass
def bar3(self):
pass
"""
code = blacken(dedent(code))
p = Patcher(code)
# Dump before doing anything, should yield original
assert p.dumps() == code
# Check iter_lines
lines = []
for line, i in p.iter_lines():
assert isinstance(line, str)
assert isinstance(i, int)
lines.append(line)
assert "\n".join(lines).strip() == code.strip()
# Check iter_properties
names = []
for classname, i1, i2 in p.iter_classes():
for funcname, j1, j2 in p.iter_properties(i1 + 1):
names.append(classname + "." + funcname)
assert names == ["Foo1.bar3", "Foo2.bar2"]
# Check iter_methods
names = []
for classname, i1, i2 in p.iter_classes():
for funcname, j1, j2 in p.iter_methods(i1 + 1):
names.append(classname + "." + funcname)
assert names == ["Foo1.bar1", "Foo1.bar2", "Foo2.bar1", "Foo2.bar3"]
# Check insert_line (can insert into same line multiple times
p = Patcher(code)
for classname, i1, i2 in p.iter_classes():
p.insert_line(i1, "# a class")
p.insert_line(i1, "# a class")
code2 = p.dumps()
assert code2.count("# a class") == 4
# Check replace_line (can only replace one time per line)
p = Patcher(code2)
for line, i in p.iter_lines():
if line.lstrip().startswith("#"):
p.replace_line(i, "# comment")
with raises(Exception):
p.replace_line(i, "# comment")
code2 = p.dumps()
assert code2.count("#") == 4
assert code2.count("# comment") == 4
# Remove comments
p = Patcher(code2)
for line, i in p.iter_lines():
if line.lstrip().startswith("#"):
p.remove_line(i)
code2 = p.dumps()
assert code2.count("#") == 0
# We should be back to where we started
assert code2 == code
def test_patcher2():
code = """
class Foo1:
def bar1(self):
pass
@property
def bar2(self):
pass
"""
p = Patcher(dedent(code))
# Check property line indices
for classname, i1, i2 in p.iter_classes():
for funcname, j1, j2 in p.iter_properties(i1 + 1):
line = p.lines[j1].lstrip()
assert line.startswith("def")
assert funcname in line
assert "pass" in p.lines[j2]
# Check method line indices
for classname, i1, i2 in p.iter_classes():
for funcname, j1, j2 in p.iter_methods(i1 + 1):
line = p.lines[j1].lstrip()
assert line.startswith("def")
assert funcname in line
assert "pass" in p.lines[j2]
if __name__ == "__main__":
for func in list(globals().values()):
if callable(func) and func.__name__.startswith("test_"):
print(f"Running {func.__name__} ...")
func()
print("Done") | codegen/tests/test_codegen_utils.py | from codegen.utils import (
remove_c_comments,
blacken,
Patcher,
to_snake_case,
to_camel_case,
)
from pytest import raises
def dedent(code):
return code.replace("\n ", "\n")
def test_to_snake_case():
assert to_snake_case("foo_bar_spam") == "foo_bar_spam"
assert to_snake_case("_foo_bar_spam") == "_foo_bar_spam"
assert to_snake_case("fooBarSpam") == "foo_bar_spam"
assert to_snake_case("_fooBarSpam") == "_foo_bar_spam"
assert to_snake_case("maxTextureDimension1D") == "max_texture_dimension1d"
def test_to_camel_case():
assert to_camel_case("foo_bar_spam") == "fooBarSpam"
assert to_camel_case("_foo_bar_spam") == "_fooBarSpam"
assert to_camel_case("fooBarSpam") == "fooBarSpam"
assert to_camel_case("_fooBarSpam") == "_fooBarSpam"
assert to_camel_case("max_texture_dimension1d") == "maxTextureDimension1D"
def test_remove_c_comments():
code1 = """
x1 hello// comment
// comment
x2 hello/* comment */
x3/* comment */ hello
x4 /* comment
comment
*/hello
"""
code3 = """
x1 hello
x2 hello
x3 hello
x4 hello
"""
code1, code3 = dedent(code1), dedent(code3)
code2 = remove_c_comments(code1)
assert code2 == code3
def test_blacken_singleline():
code1 = """
def foo():
pass
def foo(
):
pass
def foo(
a1, a2, a3
):
pass
def foo(
a1, a2, a3,
):
pass
def foo(
a1,
a2,
a3,
):
pass
"""
code2 = """
def foo():
pass
def foo():
pass
def foo(a1, a2, a3):
pass
def foo(a1, a2, a3):
pass
def foo(a1, a2, a3):
pass
"""
code1 = dedent(code1).strip()
code2 = dedent(code2).strip()
code3 = blacken(code1, True)
code3 = code3.replace("\n\n", "\n").replace("\n\n", "\n").strip()
assert code3 == code2
# Also test simply long lines
code = "foo = 1" + " + 1" * 100
assert len(code) > 300
assert code.count("\n") == 0
assert blacken(code, False).strip().count("\n") > 3
assert blacken(code, True).strip().count("\n") == 0
def test_blacken_comments():
code1 = """
def foo(): # hi
pass
def foo(
a1, # hi
a2, # ha
a3,
): # ho
pass
"""
code2 = """
def foo(): # hi
pass
def foo(a1, a2, a3): # hi ha ho
pass
"""
code1 = dedent(code1).strip()
code2 = dedent(code2).strip()
code3 = blacken(code1, True)
code3 = code3.replace("\n\n", "\n").replace("\n\n", "\n").strip()
assert code3 == code2
def test_patcher():
code = """
class Foo1:
def bar1(self):
pass
def bar2(self):
pass
@property
def bar3(self):
pass
class Foo2:
def bar1(self):
pass
@property
def bar2(self):
pass
def bar3(self):
pass
"""
code = blacken(dedent(code))
p = Patcher(code)
# Dump before doing anything, should yield original
assert p.dumps() == code
# Check iter_lines
lines = []
for line, i in p.iter_lines():
assert isinstance(line, str)
assert isinstance(i, int)
lines.append(line)
assert "\n".join(lines).strip() == code.strip()
# Check iter_properties
names = []
for classname, i1, i2 in p.iter_classes():
for funcname, j1, j2 in p.iter_properties(i1 + 1):
names.append(classname + "." + funcname)
assert names == ["Foo1.bar3", "Foo2.bar2"]
# Check iter_methods
names = []
for classname, i1, i2 in p.iter_classes():
for funcname, j1, j2 in p.iter_methods(i1 + 1):
names.append(classname + "." + funcname)
assert names == ["Foo1.bar1", "Foo1.bar2", "Foo2.bar1", "Foo2.bar3"]
# Check insert_line (can insert into same line multiple times
p = Patcher(code)
for classname, i1, i2 in p.iter_classes():
p.insert_line(i1, "# a class")
p.insert_line(i1, "# a class")
code2 = p.dumps()
assert code2.count("# a class") == 4
# Check replace_line (can only replace one time per line)
p = Patcher(code2)
for line, i in p.iter_lines():
if line.lstrip().startswith("#"):
p.replace_line(i, "# comment")
with raises(Exception):
p.replace_line(i, "# comment")
code2 = p.dumps()
assert code2.count("#") == 4
assert code2.count("# comment") == 4
# Remove comments
p = Patcher(code2)
for line, i in p.iter_lines():
if line.lstrip().startswith("#"):
p.remove_line(i)
code2 = p.dumps()
assert code2.count("#") == 0
# We should be back to where we started
assert code2 == code
def test_patcher2():
code = """
class Foo1:
def bar1(self):
pass
@property
def bar2(self):
pass
"""
p = Patcher(dedent(code))
# Check property line indices
for classname, i1, i2 in p.iter_classes():
for funcname, j1, j2 in p.iter_properties(i1 + 1):
line = p.lines[j1].lstrip()
assert line.startswith("def")
assert funcname in line
assert "pass" in p.lines[j2]
# Check method line indices
for classname, i1, i2 in p.iter_classes():
for funcname, j1, j2 in p.iter_methods(i1 + 1):
line = p.lines[j1].lstrip()
assert line.startswith("def")
assert funcname in line
assert "pass" in p.lines[j2]
if __name__ == "__main__":
for func in list(globals().values()):
if callable(func) and func.__name__.startswith("test_"):
print(f"Running {func.__name__} ...")
func()
print("Done") | 0.621541 | 0.573977 |
import os
import pandas as pd
from statapy.utils import column_corrector
class DataSet(object):
"""
Class to hold a pandas dataset under the data field.
"""
def __init__(self, name, filename="", url="", data=None):
"""
:param name: Name of the DataSet object
:param filename: path to file to be read in (supports csv and dta formats)
:param url: url of csv to read
:param data: dataFrame to serve as data value in case special loading is required
"""
self.name = name
if data is not None:
self.data = data
return
if not os.path.exists(filename) and url == "":
raise ValueError("File does not exists and url not specified")
elif os.path.exists(filename):
if len(filename) < 5:
raise ValueError(f"Filename {filename} does not have length at least 5 and "
f"hence cannot be a valid CSV/DTA")
else:
if filename[-3:] == "dta":
self.data = pd.read_stata(filename)
elif filename[-3:] == "csv":
self.data = pd.read_csv(filename)
else:
raise ValueError(f"Extension {filename[-3:]} not supported")
else:
self.data = pd.read_csv(url)
self.original_columns = self.data.columns
return
def __str__(self):
return f"Dataset {self.name}"
def __repr__(self):
return str(self)
@column_corrector
def report(self, columns=None):
"""
Reports basic statistics on columns of dataset
:param columns: List of columns to report on from dataset
:return: None
"""
df = self.data[columns]
a = df.describe()
b = df.info()
print(a)
print(b)
return
@column_corrector
def make_dummies(self, columns=None):
"""
:param columns: List of columns to be made into dummies
:return: list of new columns (dummy columns) added to the dataset in this call
"""
old_cols = set(self.data.columns)
self.data = pd.get_dummies(self.data, columns=columns)
now_cols = set(self.data.columns)
new_cols = now_cols.difference(old_cols)
return list(new_cols)
@column_corrector
def dropna(self, columns=None):
"""
Drop rows which have an NA element in columns indicated by the slice
:return:
"""
self.data.dropna(inplace=True, subset=columns) | statapy/data/dataset.py | import os
import pandas as pd
from statapy.utils import column_corrector
class DataSet(object):
"""
Class to hold a pandas dataset under the data field.
"""
def __init__(self, name, filename="", url="", data=None):
"""
:param name: Name of the DataSet object
:param filename: path to file to be read in (supports csv and dta formats)
:param url: url of csv to read
:param data: dataFrame to serve as data value in case special loading is required
"""
self.name = name
if data is not None:
self.data = data
return
if not os.path.exists(filename) and url == "":
raise ValueError("File does not exists and url not specified")
elif os.path.exists(filename):
if len(filename) < 5:
raise ValueError(f"Filename {filename} does not have length at least 5 and "
f"hence cannot be a valid CSV/DTA")
else:
if filename[-3:] == "dta":
self.data = pd.read_stata(filename)
elif filename[-3:] == "csv":
self.data = pd.read_csv(filename)
else:
raise ValueError(f"Extension {filename[-3:]} not supported")
else:
self.data = pd.read_csv(url)
self.original_columns = self.data.columns
return
def __str__(self):
return f"Dataset {self.name}"
def __repr__(self):
return str(self)
@column_corrector
def report(self, columns=None):
"""
Reports basic statistics on columns of dataset
:param columns: List of columns to report on from dataset
:return: None
"""
df = self.data[columns]
a = df.describe()
b = df.info()
print(a)
print(b)
return
@column_corrector
def make_dummies(self, columns=None):
"""
:param columns: List of columns to be made into dummies
:return: list of new columns (dummy columns) added to the dataset in this call
"""
old_cols = set(self.data.columns)
self.data = pd.get_dummies(self.data, columns=columns)
now_cols = set(self.data.columns)
new_cols = now_cols.difference(old_cols)
return list(new_cols)
@column_corrector
def dropna(self, columns=None):
"""
Drop rows which have an NA element in columns indicated by the slice
:return:
"""
self.data.dropna(inplace=True, subset=columns) | 0.567937 | 0.388328 |
from .base import Folder
from .collections import FolderCollection
from ..items import CalendarItem, Contact, Message, Task, DistributionList, MeetingRequest, MeetingResponse, \
MeetingCancellation, ITEM_CLASSES, ASSOCIATED
from ..version import EXCHANGE_2010_SP1, EXCHANGE_2013, EXCHANGE_2013_SP1
class Calendar(Folder):
"""An interface for the Exchange calendar."""
DISTINGUISHED_FOLDER_ID = 'calendar'
CONTAINER_CLASS = 'IPF.Appointment'
supported_item_models = (CalendarItem,)
LOCALIZED_NAMES = {
'da_DK': ('Kalender',),
'de_DE': ('Kalender',),
'en_US': ('Calendar',),
'es_ES': ('Calendario',),
'fr_CA': ('Calendrier',),
'nl_NL': ('Agenda',),
'ru_RU': ('Календарь',),
'sv_SE': ('Kalender',),
'zh_CN': ('日历',),
}
def view(self, *args, **kwargs):
return FolderCollection(account=self.account, folders=[self]).view(*args, **kwargs)
class DeletedItems(Folder):
DISTINGUISHED_FOLDER_ID = 'deleteditems'
CONTAINER_CLASS = 'IPF.Note'
supported_item_models = ITEM_CLASSES
LOCALIZED_NAMES = {
'da_DK': ('Slettet post',),
'de_DE': ('Gelöschte Elemente',),
'en_US': ('Deleted Items',),
'es_ES': ('Elementos eliminados',),
'fr_CA': ('Éléments supprimés',),
'nl_NL': ('Verwijderde items',),
'ru_RU': ('Удаленные',),
'sv_SE': ('Borttaget',),
'zh_CN': ('已删除邮件',),
}
class Messages(Folder):
CONTAINER_CLASS = 'IPF.Note'
supported_item_models = (Message, MeetingRequest, MeetingResponse, MeetingCancellation)
class Drafts(Messages):
DISTINGUISHED_FOLDER_ID = 'drafts'
LOCALIZED_NAMES = {
'da_DK': ('Kladder',),
'de_DE': ('Entwürfe',),
'en_US': ('Drafts',),
'es_ES': ('Borradores',),
'fr_CA': ('Brouillons',),
'nl_NL': ('Concepten',),
'ru_RU': ('Черновики',),
'sv_SE': ('Utkast',),
'zh_CN': ('草稿',),
}
class Inbox(Messages):
DISTINGUISHED_FOLDER_ID = 'inbox'
LOCALIZED_NAMES = {
'da_DK': ('Indbakke',),
'de_DE': ('Posteingang',),
'en_US': ('Inbox',),
'es_ES': ('Bandeja de entrada',),
'fr_CA': ('Boîte de réception',),
'nl_NL': ('Postvak IN',),
'ru_RU': ('Входящие',),
'sv_SE': ('Inkorgen',),
'zh_CN': ('收件箱',),
}
class Outbox(Messages):
DISTINGUISHED_FOLDER_ID = 'outbox'
LOCALIZED_NAMES = {
'da_DK': ('Udbakke',),
'de_DE': ('Postausgang',),
'en_US': ('Outbox',),
'es_ES': ('Bandeja de salida',),
'fr_CA': (u"Boîte d'envoi",),
'nl_NL': ('Postvak UIT',),
'ru_RU': ('Исходящие',),
'sv_SE': ('Utkorgen',),
'zh_CN': ('发件箱',),
}
class SentItems(Messages):
DISTINGUISHED_FOLDER_ID = 'sentitems'
LOCALIZED_NAMES = {
'da_DK': ('Sendt post',),
'de_DE': ('Gesendete Elemente',),
'en_US': ('Sent Items',),
'es_ES': ('Elementos enviados',),
'fr_CA': ('Éléments envoyés',),
'nl_NL': ('Verzonden items',),
'ru_RU': ('Отправленные',),
'sv_SE': ('Skickat',),
'zh_CN': ('已发送邮件',),
}
class JunkEmail(Messages):
DISTINGUISHED_FOLDER_ID = 'junkemail'
LOCALIZED_NAMES = {
'da_DK': ('Uønsket e-mail',),
'de_DE': ('Junk-E-Mail',),
'en_US': ('Junk E-mail',),
'es_ES': ('Correo no deseado',),
'fr_CA': ('Courrier indésirables',),
'nl_NL': ('Ongewenste e-mail',),
'ru_RU': ('Нежелательная почта',),
'sv_SE': ('Skräppost',),
'zh_CN': ('垃圾邮件',),
}
class Tasks(Folder):
DISTINGUISHED_FOLDER_ID = 'tasks'
CONTAINER_CLASS = 'IPF.Task'
supported_item_models = (Task,)
LOCALIZED_NAMES = {
'da_DK': ('Opgaver',),
'de_DE': ('Aufgaben',),
'en_US': ('Tasks',),
'es_ES': ('Tareas',),
'fr_CA': ('Tâches',),
'nl_NL': ('Taken',),
'ru_RU': ('Задачи',),
'sv_SE': ('Uppgifter',),
'zh_CN': ('任务',),
}
class Contacts(Folder):
DISTINGUISHED_FOLDER_ID = 'contacts'
CONTAINER_CLASS = 'IPF.Contact'
supported_item_models = (Contact, DistributionList)
LOCALIZED_NAMES = {
'da_DK': ('Kontaktpersoner',),
'de_DE': ('Kontakte',),
'en_US': ('Contacts',),
'es_ES': ('Contactos',),
'fr_CA': ('Contacts',),
'nl_NL': ('Contactpersonen',),
'ru_RU': ('Контакты',),
'sv_SE': ('Kontakter',),
'zh_CN': ('联系人',),
}
class WellknownFolder(Folder):
"""A base class to use until we have a more specific folder implementation for this folder."""
supported_item_models = ITEM_CLASSES
class AdminAuditLogs(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'adminauditlogs'
supported_from = EXCHANGE_2013
get_folder_allowed = False
class ArchiveDeletedItems(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'archivedeleteditems'
supported_from = EXCHANGE_2010_SP1
class ArchiveInbox(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'archiveinbox'
supported_from = EXCHANGE_2013_SP1
class ArchiveMsgFolderRoot(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'archivemsgfolderroot'
supported_from = EXCHANGE_2010_SP1
class ArchiveRecoverableItemsDeletions(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'archiverecoverableitemsdeletions'
supported_from = EXCHANGE_2010_SP1
class ArchiveRecoverableItemsPurges(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'archiverecoverableitemspurges'
supported_from = EXCHANGE_2010_SP1
class ArchiveRecoverableItemsRoot(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'archiverecoverableitemsroot'
supported_from = EXCHANGE_2010_SP1
class ArchiveRecoverableItemsVersions(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'archiverecoverableitemsversions'
supported_from = EXCHANGE_2010_SP1
class Conflicts(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'conflicts'
supported_from = EXCHANGE_2013
class ConversationHistory(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'conversationhistory'
supported_from = EXCHANGE_2013
class Directory(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'directory'
supported_from = EXCHANGE_2013_SP1
class Favorites(WellknownFolder):
CONTAINER_CLASS = 'IPF.Note'
DISTINGUISHED_FOLDER_ID = 'favorites'
supported_from = EXCHANGE_2013
class IMContactList(WellknownFolder):
CONTAINER_CLASS = 'IPF.Contact.MOC.ImContactList'
DISTINGUISHED_FOLDER_ID = 'imcontactlist'
supported_from = EXCHANGE_2013
class Journal(WellknownFolder):
CONTAINER_CLASS = 'IPF.Journal'
DISTINGUISHED_FOLDER_ID = 'journal'
class LocalFailures(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'localfailures'
supported_from = EXCHANGE_2013
class MsgFolderRoot(WellknownFolder):
"""Also known as the 'Top of Information Store' folder."""
DISTINGUISHED_FOLDER_ID = 'msgfolderroot'
LOCALIZED_NAMES = {
'zh_CN': ('信息存储顶部',),
}
class MyContacts(WellknownFolder):
CONTAINER_CLASS = 'IPF.Note'
DISTINGUISHED_FOLDER_ID = 'mycontacts'
supported_from = EXCHANGE_2013
class Notes(WellknownFolder):
CONTAINER_CLASS = 'IPF.StickyNote'
DISTINGUISHED_FOLDER_ID = 'notes'
LOCALIZED_NAMES = {
'da_DK': ('Noter',),
}
class PeopleConnect(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'peopleconnect'
supported_from = EXCHANGE_2013
class QuickContacts(WellknownFolder):
CONTAINER_CLASS = 'IPF.Contact.MOC.QuickContacts'
DISTINGUISHED_FOLDER_ID = 'quickcontacts'
supported_from = EXCHANGE_2013
class RecipientCache(Contacts):
DISTINGUISHED_FOLDER_ID = 'recipientcache'
CONTAINER_CLASS = 'IPF.Contact.RecipientCache'
supported_from = EXCHANGE_2013
LOCALIZED_NAMES = {}
class RecoverableItemsDeletions(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'recoverableitemsdeletions'
supported_from = EXCHANGE_2010_SP1
class RecoverableItemsPurges(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'recoverableitemspurges'
supported_from = EXCHANGE_2010_SP1
class RecoverableItemsRoot(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'recoverableitemsroot'
supported_from = EXCHANGE_2010_SP1
class RecoverableItemsVersions(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'recoverableitemsversions'
supported_from = EXCHANGE_2010_SP1
class SearchFolders(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'searchfolders'
class ServerFailures(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'serverfailures'
supported_from = EXCHANGE_2013
class SyncIssues(WellknownFolder):
CONTAINER_CLASS = 'IPF.Note'
DISTINGUISHED_FOLDER_ID = 'syncissues'
supported_from = EXCHANGE_2013
class ToDoSearch(WellknownFolder):
CONTAINER_CLASS = 'IPF.Task'
DISTINGUISHED_FOLDER_ID = 'todosearch'
supported_from = EXCHANGE_2013
LOCALIZED_NAMES = {
None: ('To-Do Search',),
}
class VoiceMail(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'voicemail'
CONTAINER_CLASS = 'IPF.Note.Microsoft.Voicemail'
LOCALIZED_NAMES = {
None: ('Voice Mail',),
}
class NonDeletableFolderMixin:
"""A mixin for non-wellknown folders than that are not deletable."""
@property
def is_deletable(self):
return False
class AllContacts(NonDeletableFolderMixin, Contacts):
CONTAINER_CLASS = 'IPF.Note'
LOCALIZED_NAMES = {
None: ('AllContacts',),
}
class AllItems(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPF'
LOCALIZED_NAMES = {
None: ('AllItems',),
}
class Audits(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('Audits',),
}
get_folder_allowed = False
class CalendarLogging(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('Calendar Logging',),
}
class CommonViews(NonDeletableFolderMixin, Folder):
DEFAULT_ITEM_TRAVERSAL_DEPTH = ASSOCIATED
LOCALIZED_NAMES = {
None: ('Common Views',),
}
class Companies(NonDeletableFolderMixin, Contacts):
DISTINGUISHED_FOLDER_ID = None
CONTAINTER_CLASS = 'IPF.Contact.Company'
LOCALIZED_NAMES = {
None: ('Companies',),
}
class ConversationSettings(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPF.Configuration'
LOCALIZED_NAMES = {
'da_DK': ('Indstillinger for samtalehandlinger',),
}
class DefaultFoldersChangeHistory(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPM.DefaultFolderHistoryItem'
LOCALIZED_NAMES = {
None: ('DefaultFoldersChangeHistory',),
}
class DeferredAction(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('Deferred Action',),
}
class ExchangeSyncData(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('ExchangeSyncData',),
}
class Files(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPF.Files'
LOCALIZED_NAMES = {
'da_DK': ('Filer',),
}
class FreebusyData(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('Freebusy Data',),
}
class Friends(NonDeletableFolderMixin, Contacts):
CONTAINER_CLASS = 'IPF.Note'
LOCALIZED_NAMES = {
'de_DE': ('Bekannte',),
}
class GALContacts(NonDeletableFolderMixin, Contacts):
DISTINGUISHED_FOLDER_ID = None
CONTAINER_CLASS = 'IPF.Contact.GalContacts'
LOCALIZED_NAMES = {
None: ('GAL Contacts',),
}
class GraphAnalytics(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPF.StoreItem.GraphAnalytics'
LOCALIZED_NAMES = {
None: ('GraphAnalytics',),
}
class Location(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('Location',),
}
class MailboxAssociations(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('MailboxAssociations',),
}
class MyContactsExtended(NonDeletableFolderMixin, Contacts):
CONTAINER_CLASS = 'IPF.Note'
LOCALIZED_NAMES = {
None: ('MyContactsExtended',),
}
class OrganizationalContacts(NonDeletableFolderMixin, Contacts):
DISTINGUISHED_FOLDER_ID = None
CONTAINTER_CLASS = 'IPF.Contact.OrganizationalContacts'
LOCALIZED_NAMES = {
None: ('Organizational Contacts',),
}
class ParkedMessages(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = None
LOCALIZED_NAMES = {
None: ('ParkedMessages',),
}
class PassThroughSearchResults(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPF.StoreItem.PassThroughSearchResults'
LOCALIZED_NAMES = {
None: ('Pass-Through Search Results',),
}
class PeopleCentricConversationBuddies(NonDeletableFolderMixin, Contacts):
DISTINGUISHED_FOLDER_ID = None
CONTAINTER_CLASS = 'IPF.Contact.PeopleCentricConversationBuddies'
LOCALIZED_NAMES = {
None: ('PeopleCentricConversation Buddies',),
}
class PdpProfileV2Secured(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPF.StoreItem.PdpProfileSecured'
LOCALIZED_NAMES = {
None: ('PdpProfileV2Secured',),
}
class Reminders(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'Outlook.Reminder'
LOCALIZED_NAMES = {
'da_DK': ('Påmindelser',),
}
class RSSFeeds(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPF.Note.OutlookHomepage'
LOCALIZED_NAMES = {
None: ('RSS Feeds',),
}
class Schedule(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('Schedule',),
}
class Sharing(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPF.Note'
LOCALIZED_NAMES = {
None: ('Sharing',),
}
class Shortcuts(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('Shortcuts',),
}
class Signal(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPF.StoreItem.Signal'
LOCALIZED_NAMES = {
None: ('Signal',),
}
class SmsAndChatsSync(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPF.SmsAndChatsSync'
LOCALIZED_NAMES = {
None: ('SmsAndChatsSync',),
}
class SpoolerQueue(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('Spooler Queue',),
}
class System(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('System',),
}
get_folder_allowed = False
class System1(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('System1',),
}
get_folder_allowed = False
class TemporarySaves(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('TemporarySaves',),
}
class Views(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('Views',),
}
class WorkingSet(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('Working Set',),
}
# Folders that return 'ErrorDeleteDistinguishedFolder' when we try to delete them. I can't find any official docs
# listing these folders.
NON_DELETABLE_FOLDERS = [
AllContacts,
AllItems,
Audits,
CalendarLogging,
CommonViews,
Companies,
ConversationSettings,
DefaultFoldersChangeHistory,
DeferredAction,
ExchangeSyncData,
FreebusyData,
Files,
Friends,
GALContacts,
GraphAnalytics,
Location,
MailboxAssociations,
MyContactsExtended,
OrganizationalContacts,
ParkedMessages,
PassThroughSearchResults,
PeopleCentricConversationBuddies,
PdpProfileV2Secured,
Reminders,
RSSFeeds,
Schedule,
Sharing,
Shortcuts,
Signal,
SmsAndChatsSync,
SpoolerQueue,
System,
System1,
TemporarySaves,
Views,
WorkingSet,
]
WELLKNOWN_FOLDERS_IN_ROOT = [
AdminAuditLogs,
Calendar,
Conflicts,
Contacts,
ConversationHistory,
DeletedItems,
Directory,
Drafts,
Favorites,
IMContactList,
Inbox,
Journal,
JunkEmail,
LocalFailures,
MsgFolderRoot,
MyContacts,
Notes,
Outbox,
PeopleConnect,
QuickContacts,
RecipientCache,
RecoverableItemsDeletions,
RecoverableItemsPurges,
RecoverableItemsRoot,
RecoverableItemsVersions,
SearchFolders,
SentItems,
ServerFailures,
SyncIssues,
Tasks,
ToDoSearch,
VoiceMail,
]
WELLKNOWN_FOLDERS_IN_ARCHIVE_ROOT = [
ArchiveDeletedItems,
ArchiveInbox,
ArchiveMsgFolderRoot,
ArchiveRecoverableItemsDeletions,
ArchiveRecoverableItemsPurges,
ArchiveRecoverableItemsRoot,
ArchiveRecoverableItemsVersions,
] | exchangelib/folders/known_folders.py | from .base import Folder
from .collections import FolderCollection
from ..items import CalendarItem, Contact, Message, Task, DistributionList, MeetingRequest, MeetingResponse, \
MeetingCancellation, ITEM_CLASSES, ASSOCIATED
from ..version import EXCHANGE_2010_SP1, EXCHANGE_2013, EXCHANGE_2013_SP1
class Calendar(Folder):
"""An interface for the Exchange calendar."""
DISTINGUISHED_FOLDER_ID = 'calendar'
CONTAINER_CLASS = 'IPF.Appointment'
supported_item_models = (CalendarItem,)
LOCALIZED_NAMES = {
'da_DK': ('Kalender',),
'de_DE': ('Kalender',),
'en_US': ('Calendar',),
'es_ES': ('Calendario',),
'fr_CA': ('Calendrier',),
'nl_NL': ('Agenda',),
'ru_RU': ('Календарь',),
'sv_SE': ('Kalender',),
'zh_CN': ('日历',),
}
def view(self, *args, **kwargs):
return FolderCollection(account=self.account, folders=[self]).view(*args, **kwargs)
class DeletedItems(Folder):
DISTINGUISHED_FOLDER_ID = 'deleteditems'
CONTAINER_CLASS = 'IPF.Note'
supported_item_models = ITEM_CLASSES
LOCALIZED_NAMES = {
'da_DK': ('Slettet post',),
'de_DE': ('Gelöschte Elemente',),
'en_US': ('Deleted Items',),
'es_ES': ('Elementos eliminados',),
'fr_CA': ('Éléments supprimés',),
'nl_NL': ('Verwijderde items',),
'ru_RU': ('Удаленные',),
'sv_SE': ('Borttaget',),
'zh_CN': ('已删除邮件',),
}
class Messages(Folder):
CONTAINER_CLASS = 'IPF.Note'
supported_item_models = (Message, MeetingRequest, MeetingResponse, MeetingCancellation)
class Drafts(Messages):
DISTINGUISHED_FOLDER_ID = 'drafts'
LOCALIZED_NAMES = {
'da_DK': ('Kladder',),
'de_DE': ('Entwürfe',),
'en_US': ('Drafts',),
'es_ES': ('Borradores',),
'fr_CA': ('Brouillons',),
'nl_NL': ('Concepten',),
'ru_RU': ('Черновики',),
'sv_SE': ('Utkast',),
'zh_CN': ('草稿',),
}
class Inbox(Messages):
DISTINGUISHED_FOLDER_ID = 'inbox'
LOCALIZED_NAMES = {
'da_DK': ('Indbakke',),
'de_DE': ('Posteingang',),
'en_US': ('Inbox',),
'es_ES': ('Bandeja de entrada',),
'fr_CA': ('Boîte de réception',),
'nl_NL': ('Postvak IN',),
'ru_RU': ('Входящие',),
'sv_SE': ('Inkorgen',),
'zh_CN': ('收件箱',),
}
class Outbox(Messages):
DISTINGUISHED_FOLDER_ID = 'outbox'
LOCALIZED_NAMES = {
'da_DK': ('Udbakke',),
'de_DE': ('Postausgang',),
'en_US': ('Outbox',),
'es_ES': ('Bandeja de salida',),
'fr_CA': (u"Boîte d'envoi",),
'nl_NL': ('Postvak UIT',),
'ru_RU': ('Исходящие',),
'sv_SE': ('Utkorgen',),
'zh_CN': ('发件箱',),
}
class SentItems(Messages):
DISTINGUISHED_FOLDER_ID = 'sentitems'
LOCALIZED_NAMES = {
'da_DK': ('Sendt post',),
'de_DE': ('Gesendete Elemente',),
'en_US': ('Sent Items',),
'es_ES': ('Elementos enviados',),
'fr_CA': ('Éléments envoyés',),
'nl_NL': ('Verzonden items',),
'ru_RU': ('Отправленные',),
'sv_SE': ('Skickat',),
'zh_CN': ('已发送邮件',),
}
class JunkEmail(Messages):
DISTINGUISHED_FOLDER_ID = 'junkemail'
LOCALIZED_NAMES = {
'da_DK': ('Uønsket e-mail',),
'de_DE': ('Junk-E-Mail',),
'en_US': ('Junk E-mail',),
'es_ES': ('Correo no deseado',),
'fr_CA': ('Courrier indésirables',),
'nl_NL': ('Ongewenste e-mail',),
'ru_RU': ('Нежелательная почта',),
'sv_SE': ('Skräppost',),
'zh_CN': ('垃圾邮件',),
}
class Tasks(Folder):
DISTINGUISHED_FOLDER_ID = 'tasks'
CONTAINER_CLASS = 'IPF.Task'
supported_item_models = (Task,)
LOCALIZED_NAMES = {
'da_DK': ('Opgaver',),
'de_DE': ('Aufgaben',),
'en_US': ('Tasks',),
'es_ES': ('Tareas',),
'fr_CA': ('Tâches',),
'nl_NL': ('Taken',),
'ru_RU': ('Задачи',),
'sv_SE': ('Uppgifter',),
'zh_CN': ('任务',),
}
class Contacts(Folder):
DISTINGUISHED_FOLDER_ID = 'contacts'
CONTAINER_CLASS = 'IPF.Contact'
supported_item_models = (Contact, DistributionList)
LOCALIZED_NAMES = {
'da_DK': ('Kontaktpersoner',),
'de_DE': ('Kontakte',),
'en_US': ('Contacts',),
'es_ES': ('Contactos',),
'fr_CA': ('Contacts',),
'nl_NL': ('Contactpersonen',),
'ru_RU': ('Контакты',),
'sv_SE': ('Kontakter',),
'zh_CN': ('联系人',),
}
class WellknownFolder(Folder):
"""A base class to use until we have a more specific folder implementation for this folder."""
supported_item_models = ITEM_CLASSES
class AdminAuditLogs(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'adminauditlogs'
supported_from = EXCHANGE_2013
get_folder_allowed = False
class ArchiveDeletedItems(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'archivedeleteditems'
supported_from = EXCHANGE_2010_SP1
class ArchiveInbox(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'archiveinbox'
supported_from = EXCHANGE_2013_SP1
class ArchiveMsgFolderRoot(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'archivemsgfolderroot'
supported_from = EXCHANGE_2010_SP1
class ArchiveRecoverableItemsDeletions(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'archiverecoverableitemsdeletions'
supported_from = EXCHANGE_2010_SP1
class ArchiveRecoverableItemsPurges(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'archiverecoverableitemspurges'
supported_from = EXCHANGE_2010_SP1
class ArchiveRecoverableItemsRoot(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'archiverecoverableitemsroot'
supported_from = EXCHANGE_2010_SP1
class ArchiveRecoverableItemsVersions(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'archiverecoverableitemsversions'
supported_from = EXCHANGE_2010_SP1
class Conflicts(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'conflicts'
supported_from = EXCHANGE_2013
class ConversationHistory(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'conversationhistory'
supported_from = EXCHANGE_2013
class Directory(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'directory'
supported_from = EXCHANGE_2013_SP1
class Favorites(WellknownFolder):
CONTAINER_CLASS = 'IPF.Note'
DISTINGUISHED_FOLDER_ID = 'favorites'
supported_from = EXCHANGE_2013
class IMContactList(WellknownFolder):
CONTAINER_CLASS = 'IPF.Contact.MOC.ImContactList'
DISTINGUISHED_FOLDER_ID = 'imcontactlist'
supported_from = EXCHANGE_2013
class Journal(WellknownFolder):
CONTAINER_CLASS = 'IPF.Journal'
DISTINGUISHED_FOLDER_ID = 'journal'
class LocalFailures(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'localfailures'
supported_from = EXCHANGE_2013
class MsgFolderRoot(WellknownFolder):
"""Also known as the 'Top of Information Store' folder."""
DISTINGUISHED_FOLDER_ID = 'msgfolderroot'
LOCALIZED_NAMES = {
'zh_CN': ('信息存储顶部',),
}
class MyContacts(WellknownFolder):
CONTAINER_CLASS = 'IPF.Note'
DISTINGUISHED_FOLDER_ID = 'mycontacts'
supported_from = EXCHANGE_2013
class Notes(WellknownFolder):
CONTAINER_CLASS = 'IPF.StickyNote'
DISTINGUISHED_FOLDER_ID = 'notes'
LOCALIZED_NAMES = {
'da_DK': ('Noter',),
}
class PeopleConnect(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'peopleconnect'
supported_from = EXCHANGE_2013
class QuickContacts(WellknownFolder):
CONTAINER_CLASS = 'IPF.Contact.MOC.QuickContacts'
DISTINGUISHED_FOLDER_ID = 'quickcontacts'
supported_from = EXCHANGE_2013
class RecipientCache(Contacts):
DISTINGUISHED_FOLDER_ID = 'recipientcache'
CONTAINER_CLASS = 'IPF.Contact.RecipientCache'
supported_from = EXCHANGE_2013
LOCALIZED_NAMES = {}
class RecoverableItemsDeletions(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'recoverableitemsdeletions'
supported_from = EXCHANGE_2010_SP1
class RecoverableItemsPurges(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'recoverableitemspurges'
supported_from = EXCHANGE_2010_SP1
class RecoverableItemsRoot(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'recoverableitemsroot'
supported_from = EXCHANGE_2010_SP1
class RecoverableItemsVersions(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'recoverableitemsversions'
supported_from = EXCHANGE_2010_SP1
class SearchFolders(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'searchfolders'
class ServerFailures(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'serverfailures'
supported_from = EXCHANGE_2013
class SyncIssues(WellknownFolder):
CONTAINER_CLASS = 'IPF.Note'
DISTINGUISHED_FOLDER_ID = 'syncissues'
supported_from = EXCHANGE_2013
class ToDoSearch(WellknownFolder):
CONTAINER_CLASS = 'IPF.Task'
DISTINGUISHED_FOLDER_ID = 'todosearch'
supported_from = EXCHANGE_2013
LOCALIZED_NAMES = {
None: ('To-Do Search',),
}
class VoiceMail(WellknownFolder):
DISTINGUISHED_FOLDER_ID = 'voicemail'
CONTAINER_CLASS = 'IPF.Note.Microsoft.Voicemail'
LOCALIZED_NAMES = {
None: ('Voice Mail',),
}
class NonDeletableFolderMixin:
"""A mixin for non-wellknown folders than that are not deletable."""
@property
def is_deletable(self):
return False
class AllContacts(NonDeletableFolderMixin, Contacts):
CONTAINER_CLASS = 'IPF.Note'
LOCALIZED_NAMES = {
None: ('AllContacts',),
}
class AllItems(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPF'
LOCALIZED_NAMES = {
None: ('AllItems',),
}
class Audits(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('Audits',),
}
get_folder_allowed = False
class CalendarLogging(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('Calendar Logging',),
}
class CommonViews(NonDeletableFolderMixin, Folder):
DEFAULT_ITEM_TRAVERSAL_DEPTH = ASSOCIATED
LOCALIZED_NAMES = {
None: ('Common Views',),
}
class Companies(NonDeletableFolderMixin, Contacts):
DISTINGUISHED_FOLDER_ID = None
CONTAINTER_CLASS = 'IPF.Contact.Company'
LOCALIZED_NAMES = {
None: ('Companies',),
}
class ConversationSettings(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPF.Configuration'
LOCALIZED_NAMES = {
'da_DK': ('Indstillinger for samtalehandlinger',),
}
class DefaultFoldersChangeHistory(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPM.DefaultFolderHistoryItem'
LOCALIZED_NAMES = {
None: ('DefaultFoldersChangeHistory',),
}
class DeferredAction(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('Deferred Action',),
}
class ExchangeSyncData(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('ExchangeSyncData',),
}
class Files(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPF.Files'
LOCALIZED_NAMES = {
'da_DK': ('Filer',),
}
class FreebusyData(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('Freebusy Data',),
}
class Friends(NonDeletableFolderMixin, Contacts):
CONTAINER_CLASS = 'IPF.Note'
LOCALIZED_NAMES = {
'de_DE': ('Bekannte',),
}
class GALContacts(NonDeletableFolderMixin, Contacts):
DISTINGUISHED_FOLDER_ID = None
CONTAINER_CLASS = 'IPF.Contact.GalContacts'
LOCALIZED_NAMES = {
None: ('GAL Contacts',),
}
class GraphAnalytics(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPF.StoreItem.GraphAnalytics'
LOCALIZED_NAMES = {
None: ('GraphAnalytics',),
}
class Location(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('Location',),
}
class MailboxAssociations(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('MailboxAssociations',),
}
class MyContactsExtended(NonDeletableFolderMixin, Contacts):
CONTAINER_CLASS = 'IPF.Note'
LOCALIZED_NAMES = {
None: ('MyContactsExtended',),
}
class OrganizationalContacts(NonDeletableFolderMixin, Contacts):
DISTINGUISHED_FOLDER_ID = None
CONTAINTER_CLASS = 'IPF.Contact.OrganizationalContacts'
LOCALIZED_NAMES = {
None: ('Organizational Contacts',),
}
class ParkedMessages(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = None
LOCALIZED_NAMES = {
None: ('ParkedMessages',),
}
class PassThroughSearchResults(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPF.StoreItem.PassThroughSearchResults'
LOCALIZED_NAMES = {
None: ('Pass-Through Search Results',),
}
class PeopleCentricConversationBuddies(NonDeletableFolderMixin, Contacts):
DISTINGUISHED_FOLDER_ID = None
CONTAINTER_CLASS = 'IPF.Contact.PeopleCentricConversationBuddies'
LOCALIZED_NAMES = {
None: ('PeopleCentricConversation Buddies',),
}
class PdpProfileV2Secured(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPF.StoreItem.PdpProfileSecured'
LOCALIZED_NAMES = {
None: ('PdpProfileV2Secured',),
}
class Reminders(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'Outlook.Reminder'
LOCALIZED_NAMES = {
'da_DK': ('Påmindelser',),
}
class RSSFeeds(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPF.Note.OutlookHomepage'
LOCALIZED_NAMES = {
None: ('RSS Feeds',),
}
class Schedule(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('Schedule',),
}
class Sharing(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPF.Note'
LOCALIZED_NAMES = {
None: ('Sharing',),
}
class Shortcuts(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('Shortcuts',),
}
class Signal(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPF.StoreItem.Signal'
LOCALIZED_NAMES = {
None: ('Signal',),
}
class SmsAndChatsSync(NonDeletableFolderMixin, Folder):
CONTAINER_CLASS = 'IPF.SmsAndChatsSync'
LOCALIZED_NAMES = {
None: ('SmsAndChatsSync',),
}
class SpoolerQueue(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('Spooler Queue',),
}
class System(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('System',),
}
get_folder_allowed = False
class System1(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('System1',),
}
get_folder_allowed = False
class TemporarySaves(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('TemporarySaves',),
}
class Views(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('Views',),
}
class WorkingSet(NonDeletableFolderMixin, Folder):
LOCALIZED_NAMES = {
None: ('Working Set',),
}
# Folders that return 'ErrorDeleteDistinguishedFolder' when we try to delete them. I can't find any official docs
# listing these folders.
NON_DELETABLE_FOLDERS = [
AllContacts,
AllItems,
Audits,
CalendarLogging,
CommonViews,
Companies,
ConversationSettings,
DefaultFoldersChangeHistory,
DeferredAction,
ExchangeSyncData,
FreebusyData,
Files,
Friends,
GALContacts,
GraphAnalytics,
Location,
MailboxAssociations,
MyContactsExtended,
OrganizationalContacts,
ParkedMessages,
PassThroughSearchResults,
PeopleCentricConversationBuddies,
PdpProfileV2Secured,
Reminders,
RSSFeeds,
Schedule,
Sharing,
Shortcuts,
Signal,
SmsAndChatsSync,
SpoolerQueue,
System,
System1,
TemporarySaves,
Views,
WorkingSet,
]
WELLKNOWN_FOLDERS_IN_ROOT = [
AdminAuditLogs,
Calendar,
Conflicts,
Contacts,
ConversationHistory,
DeletedItems,
Directory,
Drafts,
Favorites,
IMContactList,
Inbox,
Journal,
JunkEmail,
LocalFailures,
MsgFolderRoot,
MyContacts,
Notes,
Outbox,
PeopleConnect,
QuickContacts,
RecipientCache,
RecoverableItemsDeletions,
RecoverableItemsPurges,
RecoverableItemsRoot,
RecoverableItemsVersions,
SearchFolders,
SentItems,
ServerFailures,
SyncIssues,
Tasks,
ToDoSearch,
VoiceMail,
]
WELLKNOWN_FOLDERS_IN_ARCHIVE_ROOT = [
ArchiveDeletedItems,
ArchiveInbox,
ArchiveMsgFolderRoot,
ArchiveRecoverableItemsDeletions,
ArchiveRecoverableItemsPurges,
ArchiveRecoverableItemsRoot,
ArchiveRecoverableItemsVersions,
] | 0.566978 | 0.128662 |
from typing import Optional
from pydantic import BaseModel, Field
from enum import Enum
class MobileHandsetPriceModelInput(BaseModel):
"""Schema for input of the model's predict method."""
battery_power: Optional[int] = Field(None, title="battery_power", ge=500, le=2000,
description="Total energy a battery can store in one time measured in mAh.")
has_bluetooth: bool = Field(..., title="has_bluetooth", description="Whether the phone has bluetooth.")
clock_speed: Optional[float] = Field(None, title="clock_speed", ge=0.5, le=3.0,
description="Speed of microprocessor in gHz.")
has_dual_sim: bool = Field(..., title="has_dual_sim", description="Whether the phone has dual SIM slots.")
front_camera_megapixels: Optional[int] = Field(None, title="front_camera_megapixels", ge=0, le=20,
description="Front camera mega pixels.")
has_four_g: bool = Field(..., title="has_four_g", description="Whether the phone has 4G.")
internal_memory: Optional[int] = Field(None, title="internal_memory", ge=2, le=664,
description="Internal memory in gigabytes.")
depth: float = Field(None, title="depth", ge=0.1, le=1.0, description="Depth of mobile phone in cm.")
weight: Optional[int] = Field(None, title="weight", ge=80, le=200, description="Weight of mobile phone.")
number_of_cores: Optional[int] = Field(None, title="number_of_cores", ge=1, le=8,
description="Number of cores of processor.")
primary_camera_megapixels: Optional[int] = Field(None, title="primary_camera_megapixels", ge=0, le=20,
description="Primary camera mega pixels.")
pixel_resolution_height: Optional[int] = Field(None, title="pixel_resolution_height", ge=0, le=1960,
description="Pixel resolution height.")
pixel_resolution_width: Optional[int] = Field(None, title="pixel_resolution_width", ge=500, le=1998,
description="Pixel resolution width.")
ram: Optional[int] = Field(None, title="ram", ge=256, le=3998, description="Random access memory in megabytes.")
screen_height: Optional[int] = Field(None, title="screen_height", ge=5, le=19,
description="Screen height of mobile in cm.")
screen_width: Optional[int] = Field(None, title="screen_width", ge=0, le=18,
description="Screen width of mobile in cm.")
talk_time: Optional[int] = Field(None, title="talk_time", ge=2, le=20,
description="Longest time that a single battery charge will last when on phone "
"call.")
has_three_g: bool = Field(..., title="has_three_g", description="Whether the phone has 3G touchscreen or not.")
has_touch_screen: bool = Field(..., title="has_touch_screen", description="Whether the phone has a touchscreen or "
"not.")
has_wifi: bool = Field(..., title="has_wifi", description="Whether the phone has wifi or not.")
class PriceEnum(str, Enum):
zero = "zero"
one = "one"
two = "two"
three = "three"
class MobileHandsetPriceModelOutput(BaseModel):
"""Schema for output of the model's predict method."""
price_range: PriceEnum = Field(..., title="Price Range", description="Price range class.") | mobile_handset_price_model/prediction/schemas.py | from typing import Optional
from pydantic import BaseModel, Field
from enum import Enum
class MobileHandsetPriceModelInput(BaseModel):
"""Schema for input of the model's predict method."""
battery_power: Optional[int] = Field(None, title="battery_power", ge=500, le=2000,
description="Total energy a battery can store in one time measured in mAh.")
has_bluetooth: bool = Field(..., title="has_bluetooth", description="Whether the phone has bluetooth.")
clock_speed: Optional[float] = Field(None, title="clock_speed", ge=0.5, le=3.0,
description="Speed of microprocessor in gHz.")
has_dual_sim: bool = Field(..., title="has_dual_sim", description="Whether the phone has dual SIM slots.")
front_camera_megapixels: Optional[int] = Field(None, title="front_camera_megapixels", ge=0, le=20,
description="Front camera mega pixels.")
has_four_g: bool = Field(..., title="has_four_g", description="Whether the phone has 4G.")
internal_memory: Optional[int] = Field(None, title="internal_memory", ge=2, le=664,
description="Internal memory in gigabytes.")
depth: float = Field(None, title="depth", ge=0.1, le=1.0, description="Depth of mobile phone in cm.")
weight: Optional[int] = Field(None, title="weight", ge=80, le=200, description="Weight of mobile phone.")
number_of_cores: Optional[int] = Field(None, title="number_of_cores", ge=1, le=8,
description="Number of cores of processor.")
primary_camera_megapixels: Optional[int] = Field(None, title="primary_camera_megapixels", ge=0, le=20,
description="Primary camera mega pixels.")
pixel_resolution_height: Optional[int] = Field(None, title="pixel_resolution_height", ge=0, le=1960,
description="Pixel resolution height.")
pixel_resolution_width: Optional[int] = Field(None, title="pixel_resolution_width", ge=500, le=1998,
description="Pixel resolution width.")
ram: Optional[int] = Field(None, title="ram", ge=256, le=3998, description="Random access memory in megabytes.")
screen_height: Optional[int] = Field(None, title="screen_height", ge=5, le=19,
description="Screen height of mobile in cm.")
screen_width: Optional[int] = Field(None, title="screen_width", ge=0, le=18,
description="Screen width of mobile in cm.")
talk_time: Optional[int] = Field(None, title="talk_time", ge=2, le=20,
description="Longest time that a single battery charge will last when on phone "
"call.")
has_three_g: bool = Field(..., title="has_three_g", description="Whether the phone has 3G touchscreen or not.")
has_touch_screen: bool = Field(..., title="has_touch_screen", description="Whether the phone has a touchscreen or "
"not.")
has_wifi: bool = Field(..., title="has_wifi", description="Whether the phone has wifi or not.")
class PriceEnum(str, Enum):
zero = "zero"
one = "one"
two = "two"
three = "three"
class MobileHandsetPriceModelOutput(BaseModel):
"""Schema for output of the model's predict method."""
price_range: PriceEnum = Field(..., title="Price Range", description="Price range class.") | 0.946516 | 0.409162 |
import sys
import liqui_client
if len(sys.argv) < 2:
print("Usage: print-account-info.py <key file>")
print(" key file - Path to a file containing key/secret/nonce data")
sys.exit(1)
key_file = sys.argv[1]
with liqui_client.KeyHandler(key_file) as handler:
if not handler.keys:
print("No keys in key file.")
else:
for key in handler.keys:
print("Printing info for key {}".format(key))
with liqui_client.BTCEConnection() as connection:
t = liqui_client.TradeAPI(key, handler, connection)
try:
r = t.getInfo()
currencies = list(r.funds.keys())
currencies.sort()
for currency in currencies:
balance = r.funds[currency]
print("\t{} balance: {}".format(currency.upper(), balance))
print("\tInformation rights: {}".format(r.info_rights))
print("\tTrading rights: {}".format(r.trade_rights))
print("\tWithrawal rights: {}".format(r.withdraw_rights))
print("\tServer time: {}".format(r.server_time))
print("\tItems in transaction history: {}".format(r.transaction_count))
print("\tNumber of open orders: {}".format(r.open_orders))
print("\topen orders:")
orders = t.activeOrders()
if orders:
for o in orders:
print("\t\torder id: {}".format(o.order_id))
print("\t\t type: {}".format(o.type))
print("\t\t pair: {}".format(o.pair))
print("\t\t rate: {}".format(o.rate))
print("\t\t amount: {}".format(o.amount))
print("\t\t created: {}".format(o.timestamp_created))
print("\t\t status: {}".format(o.status))
print()
else:
print("\t\tno orders")
print("\tTrade history:")
trade_history = t.tradeHistory()
if trade_history:
for th in trade_history:
print("\t\ttransaction_id: {}".format(th.transaction_id))
print("\t\t pair: {}".format(th.pair))
print("\t\t type: {}".format(th.type))
print("\t\t amount: {}".format(th.amount))
print("\t\t rate: {}".format(th.rate))
print("\t\t order_id: {}".format(th.order_id))
print("\t\t is_your_order: {}".format(th.is_your_order))
print("\t\t timestamp: {}".format(th.timestamp))
print()
else:
print("\t\tno items in trade history")
except Exception as e:
print(" An error occurred: {}".format(e))
raise e | samples/print-account-info.py | import sys
import liqui_client
if len(sys.argv) < 2:
print("Usage: print-account-info.py <key file>")
print(" key file - Path to a file containing key/secret/nonce data")
sys.exit(1)
key_file = sys.argv[1]
with liqui_client.KeyHandler(key_file) as handler:
if not handler.keys:
print("No keys in key file.")
else:
for key in handler.keys:
print("Printing info for key {}".format(key))
with liqui_client.BTCEConnection() as connection:
t = liqui_client.TradeAPI(key, handler, connection)
try:
r = t.getInfo()
currencies = list(r.funds.keys())
currencies.sort()
for currency in currencies:
balance = r.funds[currency]
print("\t{} balance: {}".format(currency.upper(), balance))
print("\tInformation rights: {}".format(r.info_rights))
print("\tTrading rights: {}".format(r.trade_rights))
print("\tWithrawal rights: {}".format(r.withdraw_rights))
print("\tServer time: {}".format(r.server_time))
print("\tItems in transaction history: {}".format(r.transaction_count))
print("\tNumber of open orders: {}".format(r.open_orders))
print("\topen orders:")
orders = t.activeOrders()
if orders:
for o in orders:
print("\t\torder id: {}".format(o.order_id))
print("\t\t type: {}".format(o.type))
print("\t\t pair: {}".format(o.pair))
print("\t\t rate: {}".format(o.rate))
print("\t\t amount: {}".format(o.amount))
print("\t\t created: {}".format(o.timestamp_created))
print("\t\t status: {}".format(o.status))
print()
else:
print("\t\tno orders")
print("\tTrade history:")
trade_history = t.tradeHistory()
if trade_history:
for th in trade_history:
print("\t\ttransaction_id: {}".format(th.transaction_id))
print("\t\t pair: {}".format(th.pair))
print("\t\t type: {}".format(th.type))
print("\t\t amount: {}".format(th.amount))
print("\t\t rate: {}".format(th.rate))
print("\t\t order_id: {}".format(th.order_id))
print("\t\t is_your_order: {}".format(th.is_your_order))
print("\t\t timestamp: {}".format(th.timestamp))
print()
else:
print("\t\tno items in trade history")
except Exception as e:
print(" An error occurred: {}".format(e))
raise e | 0.085094 | 0.144089 |
import android
import sys
from behave import step
reload(sys)
sys.setdefaultencoding('utf-8')
# launch android app by its package name and activity name
@step(u'I launch "{app_name}" with "{apk_pkg_name}" and "{apk_activity_name}" on android')
def launch_app_by_names(context, app_name, apk_pkg_name, apk_activity_name):
android.launch_app_by_name(
context,
app_name,
apk_pkg_name,
apk_activity_name)
# select one app in android all apps and get in by click app icon
@step(u'I click app icon "{params_kw}" in all apps')
def select_app_icon(context, params_kw):
assert context.android.selectAppIconInAllApps(params_kw)
# force to run all registered watchers
@step(u'I force to run all watchers')
def force_run_watchers(context):
context.android.runAllWatchers()
# remove all registered watchers
@step(u'I remove all watchers')
def clear_all_watchers(context):
context.android.removeAllWatchers()
# When a selector can not find a match, uiautomator will run all registered watchers.
# watcher(watcher_name) ## creates a new named watcher.
# when(when_text) ## the UiSelector condition of the watcher.
# click(click_text) ## perform click action on the target UiSelector.
@step(u'I register watcher "{watcher_name}" when "{when_text}" click "{click_text}"')
def register_watcher_when(context, watcher_name, when_text, click_text):
context.android.registerWatcher(watcher_name, when_text, click_text)
# the UiSelector condition of the watcher is two conditions
@step(u'I register watcher2 "{watcher_name}" when "{when_text1}" and "{when_text2}" click "{click_text}"')
def register_watcher_when2(context, watcher_name, when_text1, when_text2, click_text):
context.android.registerWatcher(watcher_name, when_text1, click_text, when_text2)
# I should see view by its UiSelector
# e.g.
# I shoud see view "text=Clock^^^className=android.widget.TextView"
# Its UiSelector format combine key=value with ^^^, and the selector need at least one key=value
# the key should be in DEFAULT_PARAMETER_KEYS = ["text", "textContains", "textMatches", "textStartsWith",
# "description", "descriptionContains", "descriptionMatches", "descriptionStartsWith",
# "resourceId", "resourceIdMatches", "className", "packageName", "index"]
@step(u'I should see view "{params_kw}"')
def select_view_by(context, params_kw):
ob = context.android.selectObjectBy(params_kw)
assert ob.exists
# the UiSelector format is all the same
# position means 'left', 'right', 'up', 'down'
# e.g.
# B on the left side of A, means selecting B on the left side of A
@step(u'I should see relative view "{params_kw1}" on the "{position}" side of view "{params_kw2}"')
def select_relative_object(context, params_kw1, position, params_kw2):
ob = context.android.selectObjectBy(params_kw2)
assert ob.exists
assert context.android.selectRelativeObjectBy(ob, position, params_kw1).exists
@step(u'I should see view "{params_kw}" in {time_out:d} seconds')
def select_view_by_intime(context, params_kw, time_out):
ob = context.android.selectObjectBy(params_kw, time_out)
assert ob.exists
@step(u'I should see relative view "{params_kw1}" on the "{position}" side of view "{params_kw2}" in {time_out:d} seconds')
def select_relative_object_intime(context, params_kw1, position, params_kw2, time_out):
ob = context.android.selectObjectBy(params_kw2, time_out)
assert ob.exists
relative_ob = context.android.selectRelativeObjectBy(ob, position, params_kw1, time_out)
assert relative_ob.exists
@step(u'I should not see view "{params_kw}"')
def select_noneview_by(context, params_kw):
ob = context.android.selectObjectBy(params_kw)
assert not ob.exists
@step(u'I should not see relative view "{params_kw1}" on the "{position}" side of view "{params_kw2}"')
def select_relative_noneobject(context, params_kw1, position, params_kw2):
ob = context.android.selectObjectBy(params_kw2)
assert not ob.exists
assert not context.android.selectRelativeObjectBy(ob, position, params_kw1).exists
@step(u'I click view "{params_kw}"')
def click_view(context, params_kw):
ob = context.android.selectObjectBy(params_kw)
assert ob.exists
assert context.android.clickObject(ob)
# get the saved ui object from key and if exists then click it.
@step(u'I click saved object "{key}"')
def click_object(context, key):
ob = context.android.get2InfoTemp(key)
assert ob.exists
assert context.android.clickObject(ob)
# edit the ui object by its UiSelector and input the text
@step(u'I edit view "{params_kw}" to input "{text}"')
def set_edittext_object(context, params_kw, text):
ob = context.android.selectObjectBy(params_kw)
assert ob.exists
assert context.android.setEditText(ob, text)
# edit the index number EditText in current ui display and input the text
@step(u'I edit index {n:d} EditText to input "{text}"')
def set_index_edittext_object(context, n, text):
ob = context.android.selectObjectBy("className=android.widget.EditText")[n]
assert ob.exists
assert context.android.setEditText(ob, text)
# save the found ui object to temporary memory with the key
@step(u'I save view "{params_kw}" to object "{key}"')
def save_view_to_object(context, params_kw, key):
ob = context.android.selectObjectBy(params_kw)
assert ob.exists
assert context.android.save2InfoTemp(ob, key)
@step(u'I save relative view "{params_kw1}" on the "{position}" side of view "{params_kw2}" to object "{key}"')
def save_relativeview_to_object(context, params_kw1, position, params_kw2, key):
ob = context.android.selectObjectBy(params_kw2)
assert ob.exists
relative_ob = context.android.selectRelativeObjectBy(ob, position, params_kw1)
assert relative_ob.exists
assert context.android.save2InfoTemp(relative_ob, key)
# save the found ui object(get from its key) info(get from its info_name) to temporary memory with the info_key
# info_name should be in OBJECT_INFO_KEYS = ["contentDescription", "checked", "scrollable", "text",
# "packageName", "selected", "enabled", "className"]
@step(u'I save object "{key}" info "{info_name}" to temp "{info_key}"')
def save_info_temp(context, key, info_name, info_key):
ob = context.android.get2InfoTemp(key)
info = context.android.getObjectInfo(ob, info_name)
assert context.android.save2InfoTemp(info, info_key)
# directly get the ui object info by its UiSelector and info_name
# and compare with except_result
@step(u'The view "{params_kw}" info "{info_name}" should be "{except_result}"')
def compare_views(context, params_kw, info_name, except_result):
ob = context.android.selectObjectBy(params_kw)
assert ob.exists
if context.android.getObjectInfo(ob, info_name) == except_result:
assert True
else:
assert False
#Expect saved info increase given number than another
@step(u'The saved info "{key1}" increase {expected_number:d} compared with "{key2}"')
def equal_with_keys(context, key1, expected_number, key2):
info1 = context.android.get2InfoTemp(key1)
info2 = context.android.get2InfoTemp(key2)
gap = info1 - info2
if gap == expected_number:
assert True
else:
assert False
@step(u'The saved info "{key1}" is equal to "{key2}"')
def equal_with_keys(context, key1, key2):
info1 = context.android.get2InfoTemp(key1)
info2 = context.android.get2InfoTemp(key2)
if info1 == info2:
assert True
else:
assert False
@step(u'The saved info "{key1}" is unequal to "{key2}"')
def unequal_with_keys(context, key1, key2):
info1 = context.android.get2InfoTemp(key1)
info2 = context.android.get2InfoTemp(key2)
if info1 != info2:
assert True
else:
assert False
# scroll forward(default) to end vertically(default)
@step(u'I scroll to end')
def scroll_to_end(context):
assert context.android.scrollToEnd()
# fling forward(default) vertically(default)
# orientation should be in 'horiz' or 'vert'
# direction should be in 'forward' or 'backward'
@step(u'I fling "{orientation}" goto "{direction}"')
def fling_by(context, orientation, direction):
assert context.android.flingBy(orientation, direction)
# swipe from the center of the ui object to its edge
# orientation should be in 'left', 'right', 'up' or 'down'
@step(u'I swipe view "{params_kw}" to "{orientation}"')
def swipe_to(context, key, orientation):
ob = context.android.selectObjectBy(params_kw)
assert ob.exists
assert context.android.swipeTo(ob, orientation)
# swipe the saved ui object by the key to its edge
@step(u'I swipe saved object "{key}" to "{orientation}"')
def swipe_to(context, key, orientation):
ob = context.android.get2InfoTemp(key)
assert ob.exists
assert context.android.swipeTo(ob, orientation)
# save the finding ui object process with its UiSelector
@step(u'I save process of finding view "{params_kw1}" on the "{position}" side of view "{params_kw2}"')
def process_finding_relative_view(context, params_kw1="", position="", params_kw2=""):
context.android.process_args['func_name'] = process_finding_relative_view
if params_kw1 and position and params_kw2:
context.android.process_args["func_args"] = [params_kw1, position, params_kw2]
else:
params_kw1, position, params_kw2 = context.android.process_args["func_args"]
def save_process():
ob = context.android.selectObjectBy(params_kw2)
assert ob.exists
relative_ob = context.android.selectRelativeObjectBy(ob, position, params_kw1)
assert relative_ob.exists
return relative_ob
return save_process
# reload the saved process and get its result found object and save with the key
@step(u'I reload above process and save result to object "{key}"')
def reload_process(context, key):
f = context.android.process_args['func_name'](context)
ob = f()
assert ob.exists
assert context.android.save2InfoTemp(ob, key)
# wait until the ui object gone
@step(u'I wait saved object "{key}" gone in {time_out:d} seconds')
def wait_object_gone(context, key, time_out):
ob = context.android.get2InfoTemp(key)
assert ob
assert context.android.waitObjectGone(ob, time_out)
#save the element number with given text
@step(u'I count the elements with text "{element_text}" and save result to object "{key}"')
def open_notification(context, element_text, key):
elecount = context.android.d(text=element_text).count
assert context.android.save2InfoTemp(elecount, key) | tools/atip/atip/android/steps.py |
import android
import sys
from behave import step
reload(sys)
sys.setdefaultencoding('utf-8')
# launch android app by its package name and activity name
@step(u'I launch "{app_name}" with "{apk_pkg_name}" and "{apk_activity_name}" on android')
def launch_app_by_names(context, app_name, apk_pkg_name, apk_activity_name):
android.launch_app_by_name(
context,
app_name,
apk_pkg_name,
apk_activity_name)
# select one app in android all apps and get in by click app icon
@step(u'I click app icon "{params_kw}" in all apps')
def select_app_icon(context, params_kw):
assert context.android.selectAppIconInAllApps(params_kw)
# force to run all registered watchers
@step(u'I force to run all watchers')
def force_run_watchers(context):
context.android.runAllWatchers()
# remove all registered watchers
@step(u'I remove all watchers')
def clear_all_watchers(context):
context.android.removeAllWatchers()
# When a selector can not find a match, uiautomator will run all registered watchers.
# watcher(watcher_name) ## creates a new named watcher.
# when(when_text) ## the UiSelector condition of the watcher.
# click(click_text) ## perform click action on the target UiSelector.
@step(u'I register watcher "{watcher_name}" when "{when_text}" click "{click_text}"')
def register_watcher_when(context, watcher_name, when_text, click_text):
context.android.registerWatcher(watcher_name, when_text, click_text)
# the UiSelector condition of the watcher is two conditions
@step(u'I register watcher2 "{watcher_name}" when "{when_text1}" and "{when_text2}" click "{click_text}"')
def register_watcher_when2(context, watcher_name, when_text1, when_text2, click_text):
context.android.registerWatcher(watcher_name, when_text1, click_text, when_text2)
# I should see view by its UiSelector
# e.g.
# I shoud see view "text=Clock^^^className=android.widget.TextView"
# Its UiSelector format combine key=value with ^^^, and the selector need at least one key=value
# the key should be in DEFAULT_PARAMETER_KEYS = ["text", "textContains", "textMatches", "textStartsWith",
# "description", "descriptionContains", "descriptionMatches", "descriptionStartsWith",
# "resourceId", "resourceIdMatches", "className", "packageName", "index"]
@step(u'I should see view "{params_kw}"')
def select_view_by(context, params_kw):
ob = context.android.selectObjectBy(params_kw)
assert ob.exists
# the UiSelector format is all the same
# position means 'left', 'right', 'up', 'down'
# e.g.
# B on the left side of A, means selecting B on the left side of A
@step(u'I should see relative view "{params_kw1}" on the "{position}" side of view "{params_kw2}"')
def select_relative_object(context, params_kw1, position, params_kw2):
ob = context.android.selectObjectBy(params_kw2)
assert ob.exists
assert context.android.selectRelativeObjectBy(ob, position, params_kw1).exists
@step(u'I should see view "{params_kw}" in {time_out:d} seconds')
def select_view_by_intime(context, params_kw, time_out):
ob = context.android.selectObjectBy(params_kw, time_out)
assert ob.exists
@step(u'I should see relative view "{params_kw1}" on the "{position}" side of view "{params_kw2}" in {time_out:d} seconds')
def select_relative_object_intime(context, params_kw1, position, params_kw2, time_out):
ob = context.android.selectObjectBy(params_kw2, time_out)
assert ob.exists
relative_ob = context.android.selectRelativeObjectBy(ob, position, params_kw1, time_out)
assert relative_ob.exists
@step(u'I should not see view "{params_kw}"')
def select_noneview_by(context, params_kw):
ob = context.android.selectObjectBy(params_kw)
assert not ob.exists
@step(u'I should not see relative view "{params_kw1}" on the "{position}" side of view "{params_kw2}"')
def select_relative_noneobject(context, params_kw1, position, params_kw2):
ob = context.android.selectObjectBy(params_kw2)
assert not ob.exists
assert not context.android.selectRelativeObjectBy(ob, position, params_kw1).exists
@step(u'I click view "{params_kw}"')
def click_view(context, params_kw):
ob = context.android.selectObjectBy(params_kw)
assert ob.exists
assert context.android.clickObject(ob)
# get the saved ui object from key and if exists then click it.
@step(u'I click saved object "{key}"')
def click_object(context, key):
ob = context.android.get2InfoTemp(key)
assert ob.exists
assert context.android.clickObject(ob)
# edit the ui object by its UiSelector and input the text
@step(u'I edit view "{params_kw}" to input "{text}"')
def set_edittext_object(context, params_kw, text):
ob = context.android.selectObjectBy(params_kw)
assert ob.exists
assert context.android.setEditText(ob, text)
# edit the index number EditText in current ui display and input the text
@step(u'I edit index {n:d} EditText to input "{text}"')
def set_index_edittext_object(context, n, text):
ob = context.android.selectObjectBy("className=android.widget.EditText")[n]
assert ob.exists
assert context.android.setEditText(ob, text)
# save the found ui object to temporary memory with the key
@step(u'I save view "{params_kw}" to object "{key}"')
def save_view_to_object(context, params_kw, key):
ob = context.android.selectObjectBy(params_kw)
assert ob.exists
assert context.android.save2InfoTemp(ob, key)
@step(u'I save relative view "{params_kw1}" on the "{position}" side of view "{params_kw2}" to object "{key}"')
def save_relativeview_to_object(context, params_kw1, position, params_kw2, key):
ob = context.android.selectObjectBy(params_kw2)
assert ob.exists
relative_ob = context.android.selectRelativeObjectBy(ob, position, params_kw1)
assert relative_ob.exists
assert context.android.save2InfoTemp(relative_ob, key)
# save the found ui object(get from its key) info(get from its info_name) to temporary memory with the info_key
# info_name should be in OBJECT_INFO_KEYS = ["contentDescription", "checked", "scrollable", "text",
# "packageName", "selected", "enabled", "className"]
@step(u'I save object "{key}" info "{info_name}" to temp "{info_key}"')
def save_info_temp(context, key, info_name, info_key):
ob = context.android.get2InfoTemp(key)
info = context.android.getObjectInfo(ob, info_name)
assert context.android.save2InfoTemp(info, info_key)
# directly get the ui object info by its UiSelector and info_name
# and compare with except_result
@step(u'The view "{params_kw}" info "{info_name}" should be "{except_result}"')
def compare_views(context, params_kw, info_name, except_result):
ob = context.android.selectObjectBy(params_kw)
assert ob.exists
if context.android.getObjectInfo(ob, info_name) == except_result:
assert True
else:
assert False
#Expect saved info increase given number than another
@step(u'The saved info "{key1}" increase {expected_number:d} compared with "{key2}"')
def equal_with_keys(context, key1, expected_number, key2):
info1 = context.android.get2InfoTemp(key1)
info2 = context.android.get2InfoTemp(key2)
gap = info1 - info2
if gap == expected_number:
assert True
else:
assert False
@step(u'The saved info "{key1}" is equal to "{key2}"')
def equal_with_keys(context, key1, key2):
info1 = context.android.get2InfoTemp(key1)
info2 = context.android.get2InfoTemp(key2)
if info1 == info2:
assert True
else:
assert False
@step(u'The saved info "{key1}" is unequal to "{key2}"')
def unequal_with_keys(context, key1, key2):
info1 = context.android.get2InfoTemp(key1)
info2 = context.android.get2InfoTemp(key2)
if info1 != info2:
assert True
else:
assert False
# scroll forward(default) to end vertically(default)
@step(u'I scroll to end')
def scroll_to_end(context):
assert context.android.scrollToEnd()
# fling forward(default) vertically(default)
# orientation should be in 'horiz' or 'vert'
# direction should be in 'forward' or 'backward'
@step(u'I fling "{orientation}" goto "{direction}"')
def fling_by(context, orientation, direction):
assert context.android.flingBy(orientation, direction)
# swipe from the center of the ui object to its edge
# orientation should be in 'left', 'right', 'up' or 'down'
@step(u'I swipe view "{params_kw}" to "{orientation}"')
def swipe_to(context, key, orientation):
ob = context.android.selectObjectBy(params_kw)
assert ob.exists
assert context.android.swipeTo(ob, orientation)
# swipe the saved ui object by the key to its edge
@step(u'I swipe saved object "{key}" to "{orientation}"')
def swipe_to(context, key, orientation):
ob = context.android.get2InfoTemp(key)
assert ob.exists
assert context.android.swipeTo(ob, orientation)
# save the finding ui object process with its UiSelector
@step(u'I save process of finding view "{params_kw1}" on the "{position}" side of view "{params_kw2}"')
def process_finding_relative_view(context, params_kw1="", position="", params_kw2=""):
context.android.process_args['func_name'] = process_finding_relative_view
if params_kw1 and position and params_kw2:
context.android.process_args["func_args"] = [params_kw1, position, params_kw2]
else:
params_kw1, position, params_kw2 = context.android.process_args["func_args"]
def save_process():
ob = context.android.selectObjectBy(params_kw2)
assert ob.exists
relative_ob = context.android.selectRelativeObjectBy(ob, position, params_kw1)
assert relative_ob.exists
return relative_ob
return save_process
# reload the saved process and get its result found object and save with the key
@step(u'I reload above process and save result to object "{key}"')
def reload_process(context, key):
f = context.android.process_args['func_name'](context)
ob = f()
assert ob.exists
assert context.android.save2InfoTemp(ob, key)
# wait until the ui object gone
@step(u'I wait saved object "{key}" gone in {time_out:d} seconds')
def wait_object_gone(context, key, time_out):
ob = context.android.get2InfoTemp(key)
assert ob
assert context.android.waitObjectGone(ob, time_out)
#save the element number with given text
@step(u'I count the elements with text "{element_text}" and save result to object "{key}"')
def open_notification(context, element_text, key):
elecount = context.android.d(text=element_text).count
assert context.android.save2InfoTemp(elecount, key) | 0.444324 | 0.156169 |
import sys
from timeit import Timer
from random import shuffle
from bintrees import RBTree
from bintrees import FastRBTree, has_fast_tree_support
COUNT = 100
setup_RBTree = """
from __main__ import rb_build_delete, rb_build, rb_search
"""
setup_FastRBTree = """
from __main__ import crb_build_delete, crb_build, crb_search
"""
try:
fp = open('testkeys.txt')
keys = eval(fp.read())
fp.close()
bskeys = zip(keys, keys)
except IOError:
print("create 'testkeys.txt' with profile_bintree.py\n")
sys.exit()
py_searchtree = RBTree.from_keys(keys)
cy_searchtree = FastRBTree.from_keys(keys)
def rb_build_delete():
tree = RBTree.from_keys(keys)
for key in keys:
del tree[key]
def crb_build_delete():
tree = FastRBTree.from_keys(keys)
for key in keys:
del tree[key]
def rb_build():
tree = RBTree.from_keys(keys)
def crb_build():
tree = FastRBTree.from_keys(keys)
def rb_search():
for key in keys:
obj = py_searchtree[key]
def crb_search():
for key in keys:
obj = cy_searchtree[key]
def print_result(time, text):
print("Operation: %s takes %.2f seconds\n" % (text, time))
def main():
fp = open('testkeys.txt', 'w')
fp.write(repr(keys))
fp.close()
print ("Nodes: %d" % len(keys))
t = Timer("rb_build()", setup_RBTree)
print_result(t.timeit(COUNT), 'RBTree build only')
t = Timer("crb_build()", setup_FastRBTree)
print_result(t.timeit(COUNT), 'FastRBTree build only')
t = Timer("rb_build_delete()", setup_RBTree)
print_result(t.timeit(COUNT), 'RBTree build & delete')
t = Timer("crb_build_delete()", setup_FastRBTree)
print_result(t.timeit(COUNT), 'FastRBTree build & delete')
# shuffle search keys
shuffle(keys)
t = Timer("rb_search()", setup_RBTree)
print_result(t.timeit(COUNT), 'RBTree search')
t = Timer("crb_search()", setup_FastRBTree)
print_result(t.timeit(COUNT), 'FastRBTree search')
if __name__ == '__main__':
if not has_fast_tree_support():
print("Cython extension for FastRBTree is NOT working.")
else:
print("Cython extension for FastRBTree is working.")
main() | thirdparty/bintrees-2.0.7/profiling/profile_rbtree.py |
import sys
from timeit import Timer
from random import shuffle
from bintrees import RBTree
from bintrees import FastRBTree, has_fast_tree_support
COUNT = 100
setup_RBTree = """
from __main__ import rb_build_delete, rb_build, rb_search
"""
setup_FastRBTree = """
from __main__ import crb_build_delete, crb_build, crb_search
"""
try:
fp = open('testkeys.txt')
keys = eval(fp.read())
fp.close()
bskeys = zip(keys, keys)
except IOError:
print("create 'testkeys.txt' with profile_bintree.py\n")
sys.exit()
py_searchtree = RBTree.from_keys(keys)
cy_searchtree = FastRBTree.from_keys(keys)
def rb_build_delete():
tree = RBTree.from_keys(keys)
for key in keys:
del tree[key]
def crb_build_delete():
tree = FastRBTree.from_keys(keys)
for key in keys:
del tree[key]
def rb_build():
tree = RBTree.from_keys(keys)
def crb_build():
tree = FastRBTree.from_keys(keys)
def rb_search():
for key in keys:
obj = py_searchtree[key]
def crb_search():
for key in keys:
obj = cy_searchtree[key]
def print_result(time, text):
print("Operation: %s takes %.2f seconds\n" % (text, time))
def main():
fp = open('testkeys.txt', 'w')
fp.write(repr(keys))
fp.close()
print ("Nodes: %d" % len(keys))
t = Timer("rb_build()", setup_RBTree)
print_result(t.timeit(COUNT), 'RBTree build only')
t = Timer("crb_build()", setup_FastRBTree)
print_result(t.timeit(COUNT), 'FastRBTree build only')
t = Timer("rb_build_delete()", setup_RBTree)
print_result(t.timeit(COUNT), 'RBTree build & delete')
t = Timer("crb_build_delete()", setup_FastRBTree)
print_result(t.timeit(COUNT), 'FastRBTree build & delete')
# shuffle search keys
shuffle(keys)
t = Timer("rb_search()", setup_RBTree)
print_result(t.timeit(COUNT), 'RBTree search')
t = Timer("crb_search()", setup_FastRBTree)
print_result(t.timeit(COUNT), 'FastRBTree search')
if __name__ == '__main__':
if not has_fast_tree_support():
print("Cython extension for FastRBTree is NOT working.")
else:
print("Cython extension for FastRBTree is working.")
main() | 0.247896 | 0.149035 |