max_stars_repo_path
stringlengths
4
286
max_stars_repo_name
stringlengths
5
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.03M
content_cleaned
stringlengths
6
1.03M
language
stringclasses
111 values
language_score
float64
0.03
1
comments
stringlengths
0
556k
edu_score
float64
0.32
5.03
edu_int_score
int64
0
5
project_management/urls.py
wambozaAllan/Sybyl-Service-Desk-Web
1
6625751
<filename>project_management/urls.py from django.urls import path, re_path from . import views # app_name = 'project_management' urlpatterns = [ path('projects/', views.load_all_projects, name='full_project_list'), path('ongoing/', views.ProjectListView.as_view(), name='project_list'), path('ajax/load_selected_projects/', views.load_selected_projects, name='load_selected_projects'), path('projectdoc', views.model_form_upload, name='model_form_upload'), path('projectdocs/', views.load_project_documents, name='projectdocs_list'), path('<int:pk>/', views.ProjectDetailView.as_view(), name='project_details'), path('complete/', views.CompleteProjectListView.as_view(), name='complete_project_list'), path('terminated/', views.TerminatedProjectListView.as_view(), name='terminated_project_list'), path('new/', views.ProjectCreateView.as_view(), name='new_project'), path('update/<int:pk>/', views.ProjectUpdateView.as_view(), name='update_project'), path('download-project-csv/', views.projects_download, name='download_projects_csv'), path('download-project-excel/', views.export_projects_xls, name='export_projects_xls'), path('milestones/', views.project_milestones_by_user, name='milestone_list'), path('milestone/detail/<int:pk>/', views.MilestoneDetailView.as_view(), name='milestone_details'), path('listProjectMilestones/', views.list_project_milestones, name='listProjectMilestones'), path('populateMilestone/', views.populate_milestone_view, name='populateMilestone'), path('populateMilestoneStatus/', views.populate_milestone_status, name='populateMilestoneStatus'), path('saveMilestone', views.save_milestone, name='saveMilestone'), path('validateMilestoneName', views.validateMilestoneName, name='validateMilestoneName'), path('updateProjectMilestone/<int:pk>', views.UpdateProjectMilestone.as_view(), name='updateProjectMilestone'), path('updateOpenMilestone/<int:pk>', views.UpdateOpenMilestone.as_view(), name='updateOpenMilestone'), path('updateOnholdMilestone/<int:pk>', views.UpdateOnholdMilestone.as_view(), name='updateOnholdMilestone'), path('updateTerminatedMilestone/<int:pk>', views.UpdateTerminatedMilestone.as_view(), name='updateTerminatedMilestone'), path('updateCompletedMilestone/<int:pk>', views.UpdateCompletedMilestone.as_view(), name='updateCompletedMilestone'), path('detailsProjectMilestone/<int:pk>', views.DetailsProjectMilestone.as_view(), name='detailsProjectMilestone'), path('checkMilestoneStatus/', views.check_milestone_status, name='checkMilestoneStatus'), path('deleteProjectMilestone/', views.delete_project_milestone, name='deleteProjectMilestone'), path('onholdMilestones/', views.onhold_project_milestones, name='onholdMilestones'), path('openMilestones/', views.open_milestones, name='openMilestones'), path('terminatedMilestones/', views.terminated_project_milestones, name='terminatedMilestones'), path('completedMilestones/', views.completed_project_milestones, name='completedMilestones'), path('saveupdateProjectMilestone/<int:pk>', views.save_update_milestone, name='saveupdateProjectMilestone'), path('milestoneCount/', views.milestone_count, name='milestoneCount'), path('milestonesContainer/', views.milestone_container, name='milestonesContainer'), path('populateTaskView', views.populate_task_view, name='populateTaskView'), path('createTask', views.create_tasks_by_project, name="createTask"), path('tasks_list/', views.task_list_by_users, name='task_list'), path('task/<int:pk>/', views.TaskDetailView.as_view(), name='task_details'), # re_path(r'^tasks-project/(?P<project_id>\d+)/$', views.task_list_by_project, name='project_task_list'), re_path(r'^tasks-milestone/(?P<milestone_id>\d+)/$', views.task_list_by_milestone, name='milestone_task_list'), path('tasks/new/', views.TaskCreateView.as_view(), name='new_task'), path('task-update/<int:pk>/', views.TaskUpdateView.as_view(), name='update_task'), path('listProjectTasks', views.tasklist_by_project, name='listProjectTasks'), path('validateTaskName/', views.validateTaskName, name='validateTaskName'), path('saveProjectTask', views.save_project_tasks, name='saveProjectTask'), path('milestoneTasks', views.view_tasks_under_milestone, name='milestoneTasks'), path('addMilestoneTask', views.add_milestone_specific_task, name='addMilestoneTask'), path('addMilestoneTasks', views.add_milestone_tasks, name='addMilestoneTasks'), path('saveMilestoneTask', views.save_milestone_tasks, name='saveMilestoneTask'), path('updateProjectTask/<int:pk>', views.UpdateProjectTask.as_view(), name='updateProjectTask'), path('updateMilestoneTask/<int:pk>', views.UpdateMilestoneTask.as_view(), name='updateMilestoneTask'), path('detailsProjectTask/<int:pk>', views.DetailsProjectTask.as_view(), name='detailsProjectTask'), path('deleteTask/', views.delete_task, name='deleteTask'), path('openTasks/', views.open_project_tasks, name="openTasks"), path('onholdTasks/', views.onhold_tasks, name="onholdTasks"), path('terminatedTasks/', views.terminated_tasks, name="terminatedTasks"), path('completedTasks/', views.completed_tasks, name="completedTasks"), path('updateOpenTask/<int:pk>', views.UpdateOpenTask.as_view(), name='updateOpenTask'), path('updateCompletedTask/<int:pk>', views.UpdateCompletedTask.as_view(), name='updateCompletedTask'), path('updateOnholdTask/<int:pk>', views.UpdateOnholdTask.as_view(), name='updateOnholdTask'), path('updateTerminatedTask/<int:pk>', views.UpdateTerminatedTask.as_view(), name='updateTerminatedTask'), path('saveupdateProjectTask/<int:pk>', views.save_update_task, name='saveupdateProjectTask'), path('taskCount/', views.task_count, name='taskCount'), path('assignedTaskMembers/', views.assigned_task_members, name="assignedTaskMembers"), path('assignedTaskMembersMilestone/', views.assigned_task_members_milestone, name="assignedTaskMembersMilestone"), path('assignTaskMembers/', views.assign_task_members, name="assignTaskMembers"), path('deassignTaskMembers/', views.deassign_task_members, name="deassignTaskMembers"), path('deassignTaskMembersMilestone/', views.deassign_task_members_milestone, name="deassignTaskMembersMilestone"), path('checkTeamMembers/', views.check_team_members, name="checkTeamMembers"), path('checkAssignedTaskMembers/', views.check_assigned_task_members, name="checkAssignedTaskMembers"), path('saveMembersAssignedTask/', views.save_members_assigned_task, name="saveMembersAssignedTask"), path('tasks/', views.tasks_container, name="tasksContainer"), path('saveTeamTasks', views.save_team_project_tasks, name='saveTeamTasks'), path('addIncident/', views.AddIncident.as_view(), name='addIncident'), path('addProjectIncident/', views.AddProjectIncident.as_view(), name='addProjectIncident'), path('incident_list/', views.list_incidents_by_project, name='listIncidents'), path('listProjectIncidents', views.list_project_incidents, name='listProjectIncidents'), path('detailsIncident/<int:pk>/', views.DetailsIncident.as_view(), name='detailsIncident'), path('detailsProjectIncident/<int:pk>/', views.DetailsProjectIncident.as_view(), name='detailsProjectIncident'), path('updateIncident/<int:pk>/', views.UpdateIncident.as_view(), name='updateIncident'), path('updateProjectIncident/<int:pk>/', views.UpdateProjectIncident.as_view(), name='updateProjectIncident'), path('addComment/', views.add_comment, name="addComment"), path('listIncidentComments/', views.list_incident_comments, name="listIncidentComments"), path('onholdIncidents/', views.onhold_project_incidents, name="onholdIncidents"), path('terminatedIncidents/', views.terminated_project_incidents, name="terminatedIncidents"), path('completedIncidents/', views.completed_project_incidents, name="completedIncidents"), path('listIncidents/', views.incident_container, name="incidentContainer"), path('createIncident/', views.create_incident, name="createIncident"), path('saveIncident/', views.save_incident, name="saveIncident"), path('listAllPriorities/', views.ListAllPriorities.as_view(), name='listAllPriorities'), path('addPriority/', views.AddPriority.as_view(), name='addPriority'), path('updatePriority/<int:pk>/', views.UpdatePriority.as_view(), name='updatePriority'), path('deletePriority/<int:pk>', views.DeletePriority.as_view(), name="deletePriority"), path('validatePriorityName/', views.validatePriorityName, name='validatePriorityName'), path('listAllStatuses/', views.ListAllStatuses.as_view(), name='listAllStatuses'), path('addStatus/', views.AddStatus.as_view(), name='addStatus'), path('updateStatus/<int:pk>/', views.UpdateStatus.as_view(), name='updateStatus'), path('deleteStatus/<int:pk>/', views.DeleteStatus.as_view(), name="deleteStatus"), path('validateStatusName/', views.ValidateStatusName, name='validateStatusName'), path('addProject/', views.addProject, name='addProject'), # path('listProjects/', views.ListProjects.as_view(), name='listProjects'), path('listProjects/', views.list_projects, name='listProjects'), path('updateProject/<int:pk>', views.UpdateProject.as_view(), name='updateProject'), path('detailsProject/<int:pk>', views.DetailProject.as_view(), name='detailsProject'), path('validateProjectName/', views.validateProjectName, name='validateProjectName'), path('uploadDocument/', views.upload_document, name="uploadDocument" ), path('addProjectTeam/', views.add_project_team, name='addProjectTeam'), path('adminAddProjectTeam/', views.AdminAddProjectTeam.as_view(), name='adminAddProjectTeam'), path('listProjectTeams/', views.ListProjectTeams.as_view(), name='listProjectTeams'), path('updateProjectTeam/<int:pk>', views.UpdateProjectTeam.as_view(), name='updateProjectTeam'), path('deleteProjectTeam/<int:pk>', views.DeleteProjectTeam.as_view(), name='deleteProjectTeam'), path('validateProjectTeamName/', views.validateProjectTeamName, name='validateProjectTeamName'), path('validateProjectAssigned/', views.validateProjectAssigned, name='validateProjectAssigned'), path('addProjectTeamMember/', views.add_project_team_member, name='addProjectTeamMember'), path('adminAddProjectTeamMember/', views.admin_add_project_team_member, name='adminAddProjectTeamMember'), path('listProjectTeamMembers/', views.ListProjectTeamMembers.as_view(), name='listProjectTeamMembers'), path('detailProjectTeamMembers/', views.detail_team_member, name='detailProjectTeamMembers'), path('adminDetailProjectTeamMembers/', views.admin_detail_team_member, name='adminDetailProjectTeamMembers'), path('deleteProjectTeamMember/', views.remove_project_team_member, name='deleteProjectTeamMember'), path('validateProjectTeamAssigned/', views.validateProjectTeamAssigned, name='validateProjectTeamAssigned'), path('saveTeamMember/', views.save_team_member, name='saveTeamMember'), path('getTeamMembers/', views.get_team_members, name='getTeamMembers'), path('setColorCode/', views.set_priority_color_code, name='setColorCode'), path('projectForum/', views.project_forum, name='tabProjectForum'), path('createForum/', views.create_project_forum, name='createProjectForum'), path('forumReplies/', views.manage_forum_replies, name='manageForumReplies'), path('deleteChatMessage/', views.delete_forum_message, name='deleteChatMessage'), path('deleteReply/', views.delete_forum_reply, name='deleteChatReply'), path('listTeam/', views.list_project_team, name='tabListTeam'), path('viewAssignedMembers/', views.view_assigned_members, name='viewAssignedMembers'), path('auditlogs/', views.view_audit_logs, name='listauditlogs'), path('auditlogsfilter/', views.filter_audit_logs, name='auditlogsfilter'), path('auditlogsfilter2/', views.all_companies_filter_auditlogs, name='auditlogsfilterallcomp'), # TIMESHEETS path('addTimesheet/', views.add_new_timesheet, name='addNewTimesheet'), path('addTimesheetOnCalender/', views.add_new_timesheet_from_calender, name='addTimesheetOnCalender'), path('addTimesheetOnDatePaginator/', views.add_new_timesheet_from_datepaginator, name='addTimesheetOnDatePaginator'), path('projectMilestone', views.fetch_milestones_by_project, name='selectMilestonesByProject'), path('tasksMilestone', views.fetch_tasks_by_milestone, name='selectTasksByMilestone'), path('myTimesheets/', views.daily_timesheets_pane, name='myTimesheets'), path('approveTimesheets/', views.approve_timesheet_pane, name='approveTimesheets'), path('saveTimeSheet', views.save_new_timesheet, name='saveTimeSheet'), path('updateTimesheet', views.update_timesheet, name='updateTimesheet'), path('updateTimesheetPaginator', views.update_timesheet_paginator, name='updateTimesheetPaginator'), path('saveUpdateTimesheet', views.save_update_timesheet, name='saveUpdateTimesheet'), path('deleteTimesheet', views.delete_timesheet, name='deleteTimesheet'), path('deleteTimesheetPaginator', views.delete_timesheet_in_paginator, name='deleteTimesheetPaginator'), path('sendTimesheet', views.send_timesheet_for_approval, name='sendTimesheetForApproval'), path('sendPaginatorTimesheetForApproval', views.send_timesheet_for_approval_paginator, name='sendPaginatorTimesheetForApproval'), path('pendingApproval', views.timesheet_pending_approval, name='timesheetPendingApproval'), path('saveTimesheetApprovals', views.save_timesheet_approvals, name='saveTimesheetApprovals'), path('approvedTimesheetsTab', views.manage_approved_timesheets, name='approvedTimesheetsTab'), path('updateTimesheetApproval', views.update_timesheet_approval, name='updateTimesheetApproval'), path('userApprovedTimesheets', views.view_user_approved_timesheets, name='userApprovedTimesheets'), path('filterPenddingTimesheets', views.filter_pending_daily_timesheets_by_date, name='filterPendingTimesheets'), path('filterDailyProvedTimesheets', views.filter_daily_proved_timesheets, name='filterDailyProvedTimesheets'), path('filterAllUsersPendingTMs', views.filter_all_member_unapproved_timesheets, name='filterAllUsersPendingTMs'), path('filterAllUsersApprovedTMs', views.filter_all_member_approved_timesheets, name='filterAllUsersApprovedTMs'), path('analyseAllTimesheets', views.timesheets_report, name='analyseAllTimesheets'), path('userGeneralTimesheetReport', views.user_general_timesheet_report, name='userGeneralTimesheetReport'), path('viewTaskDetails/<int:pk>', views.DetailsProjectTask.as_view(), name='viewTaskDetails'), path('userRejectedTimesheets', views.manage_rejected_timesheets, name='userRejectedTimesheets'), path('resubmitTimesheet', views.resubmit_timesheet, name='resubmitTimesheet'), path('saveResentTimesheet', views.save_resent_timesheet, name='saveResentTimesheet'), path('paginatorResubmitTimesheet', views.paginator_resubmit_timesheet, name='paginatorResubmitTimesheet'), path('saveResentPaginatorTimesheet', views.save_resent_paginator_timesheet, name='saveResentPaginatorTimesheet'), path('viewTimesheetResubmissions', views.manage_timesheet_resubmissions, name='viewTimesheetResubmissions'), path('updateApproverComment', views.update_approver_comment, name='updateApproverComment'), path('savecalenderTimeSheet', views.save_calender_timesheet, name='savecalenderTimeSheet'), path('savePaginatorTimeSheet', views.save_paginator_timesheet, name='savePaginatorTimeSheet'), path('calenderTimesheetView', views.calenderTimesheetView, name='calenderTimesheetView'), path('timesheetWeeklyReport', views.timesheets_weekly_report, name='timesheetWeeklyReport'), path('filterTimesheetsByWeek', views.filter_users_timesheets_by_week, name='filterTimesheetsByWeek'), path('filterTimesheetsByDate', views.filter_timesheets_by_date, name='filterTimesheetsByDate'), path('tableTimesheetView', views.table_timesheet_view, name='tableTimesheetView'), path('listTimesheetView', views.list_timesheet_view, name='listTimesheetView'), path('saveUpdateTimesheetPaginator', views.save_update_paginator_timesheet, name='saveUpdateTimesheetPaginator'), path('timesheetProjectReport', views.timesheets_project_report, name='timesheetProjectReport'), path('filterProjectTimesheetsByWeek', views.filter_project_timesheets_by_week, name='filterProjectTimesheetsByWeek'), path('selectDailyTimesheetsByUser', views.select_daily_timesheets_by_user, name='selectDailyTimesheetsByUser'), path('selectTableTimesheetsByUser', views.select_table_timesheets_by_user, name='selectTableTimesheetsByUser'), path('timesheetMonthlyReport', views.timesheet_monthly_report, name='timesheetMonthlyReport'), path('filterMonthlyTimesheets', views.filter_monthly_timesheets, name='filterMonthlyTimesheets'), path('filterMonthlyTimesheetsByDate', views.filter_monthly_timesheets_by_date, name='filterMonthlyTimesheetsByDate'), # Schedules plans path('schedulePlan', views.timesheets_schedule_pane, name='schedulePlan'), # REPORTS path('staffUtilization/', views.staff_utilization, name="staffUtilization"), path('staffUtilizationReport/', views.staff_utilization_report, name="staffUtilizationReport"), path('exportReport/', views.export_staff_utilization, name="exportReport"), path('exportPdf/', views.export_pdf_utilization, name="exportPdf"), path('taskReport/', views.task_report_page, name="taskReport"), path('exportTaskReport/', views.export_task_report, name="exportTaskReport"), path('previewTaskReport/', views.preview_task_report, name="previewTaskReport"), # Project code path('listCodeFormat/', views.ListCodeFormat.as_view(), name='listCodeFormat'), path('addCodeFormat/', views.AddCodeFormat.as_view(), name='addCodeFormat'), path('updateCodeFormat/<int:pk>/', views.UpdateCodeFormat.as_view(), name='updateCodeFormat'), path('deleteCodeFormat/<int:pk>', views.DeleteCodeFormat.as_view(), name="deleteCodeFormat"), path('validateProjectCode/', views.validate_project_code, name='validateProjectCode'), path('checkProjectCodeExist/', views.check_project_code_exists, name='checkProjectCodeExist'), path('populateUpload/', views.populate_upload_document, name='populateUpload'), path('addMilestone/', views.load_add_milestone, name='addMilestone'), path('selectMembersByProject', views.fetch_members_by_project, name='selectMembersByProject'), path('customerRequests/', views.customer_request_home, name="customerRequests"), path('addCustomerRequest/', views.AddCustomerRequest.as_view(), name="addCustomerRequest"), path('saveCustomerRequest/', views.save_customer_request, name='saveCustomerRequest'), path('updateCustomerRequest/<int:pk>/', views.UpdateCustomerRequest.as_view(), name='updateCustomerRequest'), path('saveRequestupdate/', views.save_customer_request_update, name='saveRequestupdate'), path('viewCustomerRequest/<int:pk>/', views.ViewCustomerRequest.as_view(), name='viewCustomerRequest'), path('deleteCustomerRequest', views.delete_customer_request, name='deleteCustomerRequest'), path('fowardRequests', views.foward_customer_requests, name='fowardRequests'), path('manageCustomerViewRequests/', views.manager_view_customer_requests, name="manageCustomerViewRequests"), path('SLAsByCustomer', views.fetch_SLAs_by_customer, name='SLAsByCustomer'), path('requestsBySLA', views.fetch_requests_by_sla, name='requestsBySLA'), # CUSTOMER URLS path('listCustomerProjects/', views.list_customer_projects, name='listCustomerProjects'), path('addCustomerProjects/', views.add_customer_projects, name='addCustomerProjects'), path('returnStatus/', views.return_status, name='returnStatus'), path('saveProject/', views.save_project, name='saveProject'), path('assignedUsers/', views.assigned_users, name='assignedUsers'), path('updateCustomerProject/<int:pk>', views.UpdateCustomerProject.as_view(), name='updateCustomerProject'), path('listCustomerServiceRequests/', views.list_customer_service_requests, name='listCustomerServiceRequests'), path('listCustomerSLAs/', views.list_customer_sla, name='listCustomerSLAs'), path('checkTask/', views.check_task, name='checkTask'), path('assignRequests', views.assign_customer_request, name='assignRequests'), path('dailyTimesheetRReport', views.timesheet_daily_report, name='dailyTimesheetRReport'), path('filterDailyTimesheetRReport', views.filter_timesheet_daily_report, name='filterDailyTimesheetRReport'), path('exportDailyTMReport', views.export_daily_tm_report, name='exportDailyTMReport'), path('exportEmailDailyTMReport', views.export_and_send_email_daily_tm_report, name='exportEmailDailyTMReport'), path('detailedTaskReport', views.detailed_task_report_pane, name='detailedTaskReport'), path('filterDetailedTaskTimesheetRReport', views.filter_detailed_task_timesheet_report, name='filterDetailedTaskTimesheetRReport'), path('exportTimesheetTaskReport', views.export_timesheet_task_report, name='exportTimesheetTaskReport'), path('exportEmailTimesheetTaskReport', views.export_email_timesheet_task_report, name='exportEmailTimesheetTaskReport'), path('timesheetDefaulterList', views.timesheet_defaulter_list, name='timesheetDefaulterList'), path('sendTimesheetEmailReminder', views.send_timesheet_email_reminder, name='sendTimesheetEmailReminder'), ]
<filename>project_management/urls.py from django.urls import path, re_path from . import views # app_name = 'project_management' urlpatterns = [ path('projects/', views.load_all_projects, name='full_project_list'), path('ongoing/', views.ProjectListView.as_view(), name='project_list'), path('ajax/load_selected_projects/', views.load_selected_projects, name='load_selected_projects'), path('projectdoc', views.model_form_upload, name='model_form_upload'), path('projectdocs/', views.load_project_documents, name='projectdocs_list'), path('<int:pk>/', views.ProjectDetailView.as_view(), name='project_details'), path('complete/', views.CompleteProjectListView.as_view(), name='complete_project_list'), path('terminated/', views.TerminatedProjectListView.as_view(), name='terminated_project_list'), path('new/', views.ProjectCreateView.as_view(), name='new_project'), path('update/<int:pk>/', views.ProjectUpdateView.as_view(), name='update_project'), path('download-project-csv/', views.projects_download, name='download_projects_csv'), path('download-project-excel/', views.export_projects_xls, name='export_projects_xls'), path('milestones/', views.project_milestones_by_user, name='milestone_list'), path('milestone/detail/<int:pk>/', views.MilestoneDetailView.as_view(), name='milestone_details'), path('listProjectMilestones/', views.list_project_milestones, name='listProjectMilestones'), path('populateMilestone/', views.populate_milestone_view, name='populateMilestone'), path('populateMilestoneStatus/', views.populate_milestone_status, name='populateMilestoneStatus'), path('saveMilestone', views.save_milestone, name='saveMilestone'), path('validateMilestoneName', views.validateMilestoneName, name='validateMilestoneName'), path('updateProjectMilestone/<int:pk>', views.UpdateProjectMilestone.as_view(), name='updateProjectMilestone'), path('updateOpenMilestone/<int:pk>', views.UpdateOpenMilestone.as_view(), name='updateOpenMilestone'), path('updateOnholdMilestone/<int:pk>', views.UpdateOnholdMilestone.as_view(), name='updateOnholdMilestone'), path('updateTerminatedMilestone/<int:pk>', views.UpdateTerminatedMilestone.as_view(), name='updateTerminatedMilestone'), path('updateCompletedMilestone/<int:pk>', views.UpdateCompletedMilestone.as_view(), name='updateCompletedMilestone'), path('detailsProjectMilestone/<int:pk>', views.DetailsProjectMilestone.as_view(), name='detailsProjectMilestone'), path('checkMilestoneStatus/', views.check_milestone_status, name='checkMilestoneStatus'), path('deleteProjectMilestone/', views.delete_project_milestone, name='deleteProjectMilestone'), path('onholdMilestones/', views.onhold_project_milestones, name='onholdMilestones'), path('openMilestones/', views.open_milestones, name='openMilestones'), path('terminatedMilestones/', views.terminated_project_milestones, name='terminatedMilestones'), path('completedMilestones/', views.completed_project_milestones, name='completedMilestones'), path('saveupdateProjectMilestone/<int:pk>', views.save_update_milestone, name='saveupdateProjectMilestone'), path('milestoneCount/', views.milestone_count, name='milestoneCount'), path('milestonesContainer/', views.milestone_container, name='milestonesContainer'), path('populateTaskView', views.populate_task_view, name='populateTaskView'), path('createTask', views.create_tasks_by_project, name="createTask"), path('tasks_list/', views.task_list_by_users, name='task_list'), path('task/<int:pk>/', views.TaskDetailView.as_view(), name='task_details'), # re_path(r'^tasks-project/(?P<project_id>\d+)/$', views.task_list_by_project, name='project_task_list'), re_path(r'^tasks-milestone/(?P<milestone_id>\d+)/$', views.task_list_by_milestone, name='milestone_task_list'), path('tasks/new/', views.TaskCreateView.as_view(), name='new_task'), path('task-update/<int:pk>/', views.TaskUpdateView.as_view(), name='update_task'), path('listProjectTasks', views.tasklist_by_project, name='listProjectTasks'), path('validateTaskName/', views.validateTaskName, name='validateTaskName'), path('saveProjectTask', views.save_project_tasks, name='saveProjectTask'), path('milestoneTasks', views.view_tasks_under_milestone, name='milestoneTasks'), path('addMilestoneTask', views.add_milestone_specific_task, name='addMilestoneTask'), path('addMilestoneTasks', views.add_milestone_tasks, name='addMilestoneTasks'), path('saveMilestoneTask', views.save_milestone_tasks, name='saveMilestoneTask'), path('updateProjectTask/<int:pk>', views.UpdateProjectTask.as_view(), name='updateProjectTask'), path('updateMilestoneTask/<int:pk>', views.UpdateMilestoneTask.as_view(), name='updateMilestoneTask'), path('detailsProjectTask/<int:pk>', views.DetailsProjectTask.as_view(), name='detailsProjectTask'), path('deleteTask/', views.delete_task, name='deleteTask'), path('openTasks/', views.open_project_tasks, name="openTasks"), path('onholdTasks/', views.onhold_tasks, name="onholdTasks"), path('terminatedTasks/', views.terminated_tasks, name="terminatedTasks"), path('completedTasks/', views.completed_tasks, name="completedTasks"), path('updateOpenTask/<int:pk>', views.UpdateOpenTask.as_view(), name='updateOpenTask'), path('updateCompletedTask/<int:pk>', views.UpdateCompletedTask.as_view(), name='updateCompletedTask'), path('updateOnholdTask/<int:pk>', views.UpdateOnholdTask.as_view(), name='updateOnholdTask'), path('updateTerminatedTask/<int:pk>', views.UpdateTerminatedTask.as_view(), name='updateTerminatedTask'), path('saveupdateProjectTask/<int:pk>', views.save_update_task, name='saveupdateProjectTask'), path('taskCount/', views.task_count, name='taskCount'), path('assignedTaskMembers/', views.assigned_task_members, name="assignedTaskMembers"), path('assignedTaskMembersMilestone/', views.assigned_task_members_milestone, name="assignedTaskMembersMilestone"), path('assignTaskMembers/', views.assign_task_members, name="assignTaskMembers"), path('deassignTaskMembers/', views.deassign_task_members, name="deassignTaskMembers"), path('deassignTaskMembersMilestone/', views.deassign_task_members_milestone, name="deassignTaskMembersMilestone"), path('checkTeamMembers/', views.check_team_members, name="checkTeamMembers"), path('checkAssignedTaskMembers/', views.check_assigned_task_members, name="checkAssignedTaskMembers"), path('saveMembersAssignedTask/', views.save_members_assigned_task, name="saveMembersAssignedTask"), path('tasks/', views.tasks_container, name="tasksContainer"), path('saveTeamTasks', views.save_team_project_tasks, name='saveTeamTasks'), path('addIncident/', views.AddIncident.as_view(), name='addIncident'), path('addProjectIncident/', views.AddProjectIncident.as_view(), name='addProjectIncident'), path('incident_list/', views.list_incidents_by_project, name='listIncidents'), path('listProjectIncidents', views.list_project_incidents, name='listProjectIncidents'), path('detailsIncident/<int:pk>/', views.DetailsIncident.as_view(), name='detailsIncident'), path('detailsProjectIncident/<int:pk>/', views.DetailsProjectIncident.as_view(), name='detailsProjectIncident'), path('updateIncident/<int:pk>/', views.UpdateIncident.as_view(), name='updateIncident'), path('updateProjectIncident/<int:pk>/', views.UpdateProjectIncident.as_view(), name='updateProjectIncident'), path('addComment/', views.add_comment, name="addComment"), path('listIncidentComments/', views.list_incident_comments, name="listIncidentComments"), path('onholdIncidents/', views.onhold_project_incidents, name="onholdIncidents"), path('terminatedIncidents/', views.terminated_project_incidents, name="terminatedIncidents"), path('completedIncidents/', views.completed_project_incidents, name="completedIncidents"), path('listIncidents/', views.incident_container, name="incidentContainer"), path('createIncident/', views.create_incident, name="createIncident"), path('saveIncident/', views.save_incident, name="saveIncident"), path('listAllPriorities/', views.ListAllPriorities.as_view(), name='listAllPriorities'), path('addPriority/', views.AddPriority.as_view(), name='addPriority'), path('updatePriority/<int:pk>/', views.UpdatePriority.as_view(), name='updatePriority'), path('deletePriority/<int:pk>', views.DeletePriority.as_view(), name="deletePriority"), path('validatePriorityName/', views.validatePriorityName, name='validatePriorityName'), path('listAllStatuses/', views.ListAllStatuses.as_view(), name='listAllStatuses'), path('addStatus/', views.AddStatus.as_view(), name='addStatus'), path('updateStatus/<int:pk>/', views.UpdateStatus.as_view(), name='updateStatus'), path('deleteStatus/<int:pk>/', views.DeleteStatus.as_view(), name="deleteStatus"), path('validateStatusName/', views.ValidateStatusName, name='validateStatusName'), path('addProject/', views.addProject, name='addProject'), # path('listProjects/', views.ListProjects.as_view(), name='listProjects'), path('listProjects/', views.list_projects, name='listProjects'), path('updateProject/<int:pk>', views.UpdateProject.as_view(), name='updateProject'), path('detailsProject/<int:pk>', views.DetailProject.as_view(), name='detailsProject'), path('validateProjectName/', views.validateProjectName, name='validateProjectName'), path('uploadDocument/', views.upload_document, name="uploadDocument" ), path('addProjectTeam/', views.add_project_team, name='addProjectTeam'), path('adminAddProjectTeam/', views.AdminAddProjectTeam.as_view(), name='adminAddProjectTeam'), path('listProjectTeams/', views.ListProjectTeams.as_view(), name='listProjectTeams'), path('updateProjectTeam/<int:pk>', views.UpdateProjectTeam.as_view(), name='updateProjectTeam'), path('deleteProjectTeam/<int:pk>', views.DeleteProjectTeam.as_view(), name='deleteProjectTeam'), path('validateProjectTeamName/', views.validateProjectTeamName, name='validateProjectTeamName'), path('validateProjectAssigned/', views.validateProjectAssigned, name='validateProjectAssigned'), path('addProjectTeamMember/', views.add_project_team_member, name='addProjectTeamMember'), path('adminAddProjectTeamMember/', views.admin_add_project_team_member, name='adminAddProjectTeamMember'), path('listProjectTeamMembers/', views.ListProjectTeamMembers.as_view(), name='listProjectTeamMembers'), path('detailProjectTeamMembers/', views.detail_team_member, name='detailProjectTeamMembers'), path('adminDetailProjectTeamMembers/', views.admin_detail_team_member, name='adminDetailProjectTeamMembers'), path('deleteProjectTeamMember/', views.remove_project_team_member, name='deleteProjectTeamMember'), path('validateProjectTeamAssigned/', views.validateProjectTeamAssigned, name='validateProjectTeamAssigned'), path('saveTeamMember/', views.save_team_member, name='saveTeamMember'), path('getTeamMembers/', views.get_team_members, name='getTeamMembers'), path('setColorCode/', views.set_priority_color_code, name='setColorCode'), path('projectForum/', views.project_forum, name='tabProjectForum'), path('createForum/', views.create_project_forum, name='createProjectForum'), path('forumReplies/', views.manage_forum_replies, name='manageForumReplies'), path('deleteChatMessage/', views.delete_forum_message, name='deleteChatMessage'), path('deleteReply/', views.delete_forum_reply, name='deleteChatReply'), path('listTeam/', views.list_project_team, name='tabListTeam'), path('viewAssignedMembers/', views.view_assigned_members, name='viewAssignedMembers'), path('auditlogs/', views.view_audit_logs, name='listauditlogs'), path('auditlogsfilter/', views.filter_audit_logs, name='auditlogsfilter'), path('auditlogsfilter2/', views.all_companies_filter_auditlogs, name='auditlogsfilterallcomp'), # TIMESHEETS path('addTimesheet/', views.add_new_timesheet, name='addNewTimesheet'), path('addTimesheetOnCalender/', views.add_new_timesheet_from_calender, name='addTimesheetOnCalender'), path('addTimesheetOnDatePaginator/', views.add_new_timesheet_from_datepaginator, name='addTimesheetOnDatePaginator'), path('projectMilestone', views.fetch_milestones_by_project, name='selectMilestonesByProject'), path('tasksMilestone', views.fetch_tasks_by_milestone, name='selectTasksByMilestone'), path('myTimesheets/', views.daily_timesheets_pane, name='myTimesheets'), path('approveTimesheets/', views.approve_timesheet_pane, name='approveTimesheets'), path('saveTimeSheet', views.save_new_timesheet, name='saveTimeSheet'), path('updateTimesheet', views.update_timesheet, name='updateTimesheet'), path('updateTimesheetPaginator', views.update_timesheet_paginator, name='updateTimesheetPaginator'), path('saveUpdateTimesheet', views.save_update_timesheet, name='saveUpdateTimesheet'), path('deleteTimesheet', views.delete_timesheet, name='deleteTimesheet'), path('deleteTimesheetPaginator', views.delete_timesheet_in_paginator, name='deleteTimesheetPaginator'), path('sendTimesheet', views.send_timesheet_for_approval, name='sendTimesheetForApproval'), path('sendPaginatorTimesheetForApproval', views.send_timesheet_for_approval_paginator, name='sendPaginatorTimesheetForApproval'), path('pendingApproval', views.timesheet_pending_approval, name='timesheetPendingApproval'), path('saveTimesheetApprovals', views.save_timesheet_approvals, name='saveTimesheetApprovals'), path('approvedTimesheetsTab', views.manage_approved_timesheets, name='approvedTimesheetsTab'), path('updateTimesheetApproval', views.update_timesheet_approval, name='updateTimesheetApproval'), path('userApprovedTimesheets', views.view_user_approved_timesheets, name='userApprovedTimesheets'), path('filterPenddingTimesheets', views.filter_pending_daily_timesheets_by_date, name='filterPendingTimesheets'), path('filterDailyProvedTimesheets', views.filter_daily_proved_timesheets, name='filterDailyProvedTimesheets'), path('filterAllUsersPendingTMs', views.filter_all_member_unapproved_timesheets, name='filterAllUsersPendingTMs'), path('filterAllUsersApprovedTMs', views.filter_all_member_approved_timesheets, name='filterAllUsersApprovedTMs'), path('analyseAllTimesheets', views.timesheets_report, name='analyseAllTimesheets'), path('userGeneralTimesheetReport', views.user_general_timesheet_report, name='userGeneralTimesheetReport'), path('viewTaskDetails/<int:pk>', views.DetailsProjectTask.as_view(), name='viewTaskDetails'), path('userRejectedTimesheets', views.manage_rejected_timesheets, name='userRejectedTimesheets'), path('resubmitTimesheet', views.resubmit_timesheet, name='resubmitTimesheet'), path('saveResentTimesheet', views.save_resent_timesheet, name='saveResentTimesheet'), path('paginatorResubmitTimesheet', views.paginator_resubmit_timesheet, name='paginatorResubmitTimesheet'), path('saveResentPaginatorTimesheet', views.save_resent_paginator_timesheet, name='saveResentPaginatorTimesheet'), path('viewTimesheetResubmissions', views.manage_timesheet_resubmissions, name='viewTimesheetResubmissions'), path('updateApproverComment', views.update_approver_comment, name='updateApproverComment'), path('savecalenderTimeSheet', views.save_calender_timesheet, name='savecalenderTimeSheet'), path('savePaginatorTimeSheet', views.save_paginator_timesheet, name='savePaginatorTimeSheet'), path('calenderTimesheetView', views.calenderTimesheetView, name='calenderTimesheetView'), path('timesheetWeeklyReport', views.timesheets_weekly_report, name='timesheetWeeklyReport'), path('filterTimesheetsByWeek', views.filter_users_timesheets_by_week, name='filterTimesheetsByWeek'), path('filterTimesheetsByDate', views.filter_timesheets_by_date, name='filterTimesheetsByDate'), path('tableTimesheetView', views.table_timesheet_view, name='tableTimesheetView'), path('listTimesheetView', views.list_timesheet_view, name='listTimesheetView'), path('saveUpdateTimesheetPaginator', views.save_update_paginator_timesheet, name='saveUpdateTimesheetPaginator'), path('timesheetProjectReport', views.timesheets_project_report, name='timesheetProjectReport'), path('filterProjectTimesheetsByWeek', views.filter_project_timesheets_by_week, name='filterProjectTimesheetsByWeek'), path('selectDailyTimesheetsByUser', views.select_daily_timesheets_by_user, name='selectDailyTimesheetsByUser'), path('selectTableTimesheetsByUser', views.select_table_timesheets_by_user, name='selectTableTimesheetsByUser'), path('timesheetMonthlyReport', views.timesheet_monthly_report, name='timesheetMonthlyReport'), path('filterMonthlyTimesheets', views.filter_monthly_timesheets, name='filterMonthlyTimesheets'), path('filterMonthlyTimesheetsByDate', views.filter_monthly_timesheets_by_date, name='filterMonthlyTimesheetsByDate'), # Schedules plans path('schedulePlan', views.timesheets_schedule_pane, name='schedulePlan'), # REPORTS path('staffUtilization/', views.staff_utilization, name="staffUtilization"), path('staffUtilizationReport/', views.staff_utilization_report, name="staffUtilizationReport"), path('exportReport/', views.export_staff_utilization, name="exportReport"), path('exportPdf/', views.export_pdf_utilization, name="exportPdf"), path('taskReport/', views.task_report_page, name="taskReport"), path('exportTaskReport/', views.export_task_report, name="exportTaskReport"), path('previewTaskReport/', views.preview_task_report, name="previewTaskReport"), # Project code path('listCodeFormat/', views.ListCodeFormat.as_view(), name='listCodeFormat'), path('addCodeFormat/', views.AddCodeFormat.as_view(), name='addCodeFormat'), path('updateCodeFormat/<int:pk>/', views.UpdateCodeFormat.as_view(), name='updateCodeFormat'), path('deleteCodeFormat/<int:pk>', views.DeleteCodeFormat.as_view(), name="deleteCodeFormat"), path('validateProjectCode/', views.validate_project_code, name='validateProjectCode'), path('checkProjectCodeExist/', views.check_project_code_exists, name='checkProjectCodeExist'), path('populateUpload/', views.populate_upload_document, name='populateUpload'), path('addMilestone/', views.load_add_milestone, name='addMilestone'), path('selectMembersByProject', views.fetch_members_by_project, name='selectMembersByProject'), path('customerRequests/', views.customer_request_home, name="customerRequests"), path('addCustomerRequest/', views.AddCustomerRequest.as_view(), name="addCustomerRequest"), path('saveCustomerRequest/', views.save_customer_request, name='saveCustomerRequest'), path('updateCustomerRequest/<int:pk>/', views.UpdateCustomerRequest.as_view(), name='updateCustomerRequest'), path('saveRequestupdate/', views.save_customer_request_update, name='saveRequestupdate'), path('viewCustomerRequest/<int:pk>/', views.ViewCustomerRequest.as_view(), name='viewCustomerRequest'), path('deleteCustomerRequest', views.delete_customer_request, name='deleteCustomerRequest'), path('fowardRequests', views.foward_customer_requests, name='fowardRequests'), path('manageCustomerViewRequests/', views.manager_view_customer_requests, name="manageCustomerViewRequests"), path('SLAsByCustomer', views.fetch_SLAs_by_customer, name='SLAsByCustomer'), path('requestsBySLA', views.fetch_requests_by_sla, name='requestsBySLA'), # CUSTOMER URLS path('listCustomerProjects/', views.list_customer_projects, name='listCustomerProjects'), path('addCustomerProjects/', views.add_customer_projects, name='addCustomerProjects'), path('returnStatus/', views.return_status, name='returnStatus'), path('saveProject/', views.save_project, name='saveProject'), path('assignedUsers/', views.assigned_users, name='assignedUsers'), path('updateCustomerProject/<int:pk>', views.UpdateCustomerProject.as_view(), name='updateCustomerProject'), path('listCustomerServiceRequests/', views.list_customer_service_requests, name='listCustomerServiceRequests'), path('listCustomerSLAs/', views.list_customer_sla, name='listCustomerSLAs'), path('checkTask/', views.check_task, name='checkTask'), path('assignRequests', views.assign_customer_request, name='assignRequests'), path('dailyTimesheetRReport', views.timesheet_daily_report, name='dailyTimesheetRReport'), path('filterDailyTimesheetRReport', views.filter_timesheet_daily_report, name='filterDailyTimesheetRReport'), path('exportDailyTMReport', views.export_daily_tm_report, name='exportDailyTMReport'), path('exportEmailDailyTMReport', views.export_and_send_email_daily_tm_report, name='exportEmailDailyTMReport'), path('detailedTaskReport', views.detailed_task_report_pane, name='detailedTaskReport'), path('filterDetailedTaskTimesheetRReport', views.filter_detailed_task_timesheet_report, name='filterDetailedTaskTimesheetRReport'), path('exportTimesheetTaskReport', views.export_timesheet_task_report, name='exportTimesheetTaskReport'), path('exportEmailTimesheetTaskReport', views.export_email_timesheet_task_report, name='exportEmailTimesheetTaskReport'), path('timesheetDefaulterList', views.timesheet_defaulter_list, name='timesheetDefaulterList'), path('sendTimesheetEmailReminder', views.send_timesheet_email_reminder, name='sendTimesheetEmailReminder'), ]
en
0.462898
# app_name = 'project_management' # re_path(r'^tasks-project/(?P<project_id>\d+)/$', views.task_list_by_project, name='project_task_list'), # path('listProjects/', views.ListProjects.as_view(), name='listProjects'), # TIMESHEETS # Schedules plans # REPORTS # Project code # CUSTOMER URLS
2.001275
2
detection/scrfd/mmdet/models/detectors/base.py
qaz734913414/insightface
12,377
6625752
from abc import ABCMeta, abstractmethod from collections import OrderedDict import mmcv import numpy as np import torch import torch.distributed as dist import torch.nn as nn from mmcv.runner import auto_fp16 from mmcv.utils import print_log from mmdet.utils import get_root_logger class BaseDetector(nn.Module, metaclass=ABCMeta): """Base class for detectors.""" def __init__(self): super(BaseDetector, self).__init__() self.fp16_enabled = False @property def with_neck(self): """bool: whether the detector has a neck""" return hasattr(self, 'neck') and self.neck is not None # TODO: these properties need to be carefully handled # for both single stage & two stage detectors @property def with_shared_head(self): """bool: whether the detector has a shared head in the RoI Head""" return hasattr(self, 'roi_head') and self.roi_head.with_shared_head @property def with_bbox(self): """bool: whether the detector has a bbox head""" return ((hasattr(self, 'roi_head') and self.roi_head.with_bbox) or (hasattr(self, 'bbox_head') and self.bbox_head is not None)) @property def with_mask(self): """bool: whether the detector has a mask head""" return ((hasattr(self, 'roi_head') and self.roi_head.with_mask) or (hasattr(self, 'mask_head') and self.mask_head is not None)) @abstractmethod def extract_feat(self, imgs): """Extract features from images.""" pass def extract_feats(self, imgs): """Extract features from multiple images. Args: imgs (list[torch.Tensor]): A list of images. The images are augmented from the same image but in different ways. Returns: list[torch.Tensor]: Features of different images """ assert isinstance(imgs, list) return [self.extract_feat(img) for img in imgs] def forward_train(self, imgs, img_metas, **kwargs): """ Args: img (list[Tensor]): List of tensors of shape (1, C, H, W). Typically these should be mean centered and std scaled. img_metas (list[dict]): List of image info dict where each dict has: 'img_shape', 'scale_factor', 'flip', and may also contain 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'. For details on the values of these keys, see :class:`mmdet.datasets.pipelines.Collect`. kwargs (keyword arguments): Specific to concrete implementation. """ # NOTE the batched image size information may be useful, e.g. # in DETR, this is needed for the construction of masks, which is # then used for the transformer_head. batch_input_shape = tuple(imgs[0].size()[-2:]) for img_meta in img_metas: img_meta['batch_input_shape'] = batch_input_shape async def async_simple_test(self, img, img_metas, **kwargs): raise NotImplementedError @abstractmethod def simple_test(self, img, img_metas, **kwargs): pass @abstractmethod def aug_test(self, imgs, img_metas, **kwargs): """Test function with test time augmentation.""" pass def init_weights(self, pretrained=None): """Initialize the weights in detector. Args: pretrained (str, optional): Path to pre-trained weights. Defaults to None. """ if pretrained is not None: logger = get_root_logger() print_log(f'load model from: {pretrained}', logger=logger) async def aforward_test(self, *, img, img_metas, **kwargs): for var, name in [(img, 'img'), (img_metas, 'img_metas')]: if not isinstance(var, list): raise TypeError(f'{name} must be a list, but got {type(var)}') num_augs = len(img) if num_augs != len(img_metas): raise ValueError(f'num of augmentations ({len(img)}) ' f'!= num of image metas ({len(img_metas)})') # TODO: remove the restriction of samples_per_gpu == 1 when prepared samples_per_gpu = img[0].size(0) assert samples_per_gpu == 1 if num_augs == 1: return await self.async_simple_test(img[0], img_metas[0], **kwargs) else: raise NotImplementedError def forward_test(self, imgs, img_metas, **kwargs): """ Args: imgs (List[Tensor]): the outer list indicates test-time augmentations and inner Tensor should have a shape NxCxHxW, which contains all images in the batch. img_metas (List[List[dict]]): the outer list indicates test-time augs (multiscale, flip, etc.) and the inner list indicates images in a batch. """ for var, name in [(imgs, 'imgs'), (img_metas, 'img_metas')]: if not isinstance(var, list): raise TypeError(f'{name} must be a list, but got {type(var)}') num_augs = len(imgs) if num_augs != len(img_metas): raise ValueError(f'num of augmentations ({len(imgs)}) ' f'!= num of image meta ({len(img_metas)})') # NOTE the batched image size information may be useful, e.g. # in DETR, this is needed for the construction of masks, which is # then used for the transformer_head. for img, img_meta in zip(imgs, img_metas): batch_size = len(img_meta) for img_id in range(batch_size): img_meta[img_id]['batch_input_shape'] = tuple(img.size()[-2:]) if num_augs == 1: # proposals (List[List[Tensor]]): the outer list indicates # test-time augs (multiscale, flip, etc.) and the inner list # indicates images in a batch. # The Tensor should have a shape Px4, where P is the number of # proposals. if 'proposals' in kwargs: kwargs['proposals'] = kwargs['proposals'][0] return self.simple_test(imgs[0], img_metas[0], **kwargs) else: assert imgs[0].size(0) == 1, 'aug test does not support ' \ 'inference with batch size ' \ f'{imgs[0].size(0)}' # TODO: support test augmentation for predefined proposals assert 'proposals' not in kwargs return self.aug_test(imgs, img_metas, **kwargs) @auto_fp16(apply_to=('img', )) def forward(self, img, img_metas, return_loss=True, **kwargs): """Calls either :func:`forward_train` or :func:`forward_test` depending on whether ``return_loss`` is ``True``. Note this setting will change the expected inputs. When ``return_loss=True``, img and img_meta are single-nested (i.e. Tensor and List[dict]), and when ``resturn_loss=False``, img and img_meta should be double nested (i.e. List[Tensor], List[List[dict]]), with the outer list indicating test time augmentations. """ if return_loss: return self.forward_train(img, img_metas, **kwargs) else: return self.forward_test(img, img_metas, **kwargs) def _parse_losses(self, losses): """Parse the raw outputs (losses) of the network. Args: losses (dict): Raw output of the network, which usually contain losses and other necessary infomation. Returns: tuple[Tensor, dict]: (loss, log_vars), loss is the loss tensor \ which may be a weighted sum of all losses, log_vars contains \ all the variables to be sent to the logger. """ log_vars = OrderedDict() for loss_name, loss_value in losses.items(): if isinstance(loss_value, torch.Tensor): log_vars[loss_name] = loss_value.mean() elif isinstance(loss_value, list): log_vars[loss_name] = sum(_loss.mean() for _loss in loss_value) else: raise TypeError( f'{loss_name} is not a tensor or list of tensors') loss = sum(_value for _key, _value in log_vars.items() if 'loss' in _key) log_vars['loss'] = loss for loss_name, loss_value in log_vars.items(): # reduce loss when distributed training if dist.is_available() and dist.is_initialized(): loss_value = loss_value.data.clone() dist.all_reduce(loss_value.div_(dist.get_world_size())) log_vars[loss_name] = loss_value.item() return loss, log_vars def train_step(self, data, optimizer): """The iteration step during training. This method defines an iteration step during training, except for the back propagation and optimizer updating, which are done in an optimizer hook. Note that in some complicated cases or models, the whole process including back propagation and optimizer updating is also defined in this method, such as GAN. Args: data (dict): The output of dataloader. optimizer (:obj:`torch.optim.Optimizer` | dict): The optimizer of runner is passed to ``train_step()``. This argument is unused and reserved. Returns: dict: It should contain at least 3 keys: ``loss``, ``log_vars``, \ ``num_samples``. - ``loss`` is a tensor for back propagation, which can be a \ weighted sum of multiple losses. - ``log_vars`` contains all the variables to be sent to the logger. - ``num_samples`` indicates the batch size (when the model is \ DDP, it means the batch size on each GPU), which is used for \ averaging the logs. """ losses = self(**data) loss, log_vars = self._parse_losses(losses) outputs = dict( loss=loss, log_vars=log_vars, num_samples=len(data['img_metas'])) return outputs def val_step(self, data, optimizer): """The iteration step during validation. This method shares the same signature as :func:`train_step`, but used during val epochs. Note that the evaluation after training epochs is not implemented with this method, but an evaluation hook. """ losses = self(**data) loss, log_vars = self._parse_losses(losses) outputs = dict( loss=loss, log_vars=log_vars, num_samples=len(data['img_metas'])) return outputs def show_result(self, img, result, score_thr=0.3, bbox_color='green', text_color='green', thickness=1, font_scale=0.5, win_name='', show=False, wait_time=0, out_file=None): """Draw `result` over `img`. Args: img (str or Tensor): The image to be displayed. result (Tensor or tuple): The results to draw over `img` bbox_result or (bbox_result, segm_result). score_thr (float, optional): Minimum score of bboxes to be shown. Default: 0.3. bbox_color (str or tuple or :obj:`Color`): Color of bbox lines. text_color (str or tuple or :obj:`Color`): Color of texts. thickness (int): Thickness of lines. font_scale (float): Font scales of texts. win_name (str): The window name. wait_time (int): Value of waitKey param. Default: 0. show (bool): Whether to show the image. Default: False. out_file (str or None): The filename to write the image. Default: None. Returns: img (Tensor): Only if not `show` or `out_file` """ img = mmcv.imread(img) img = img.copy() if isinstance(result, tuple): bbox_result, segm_result = result if isinstance(segm_result, tuple): segm_result = segm_result[0] # ms rcnn else: bbox_result, segm_result = result, None bboxes = np.vstack(bbox_result) labels = [ np.full(bbox.shape[0], i, dtype=np.int32) for i, bbox in enumerate(bbox_result) ] labels = np.concatenate(labels) # draw segmentation masks if segm_result is not None and len(labels) > 0: # non empty segms = mmcv.concat_list(segm_result) inds = np.where(bboxes[:, -1] > score_thr)[0] np.random.seed(42) color_masks = [ np.random.randint(0, 256, (1, 3), dtype=np.uint8) for _ in range(max(labels) + 1) ] for i in inds: i = int(i) color_mask = color_masks[labels[i]] sg = segms[i] if isinstance(sg, torch.Tensor): sg = sg.detach().cpu().numpy() mask = sg.astype(bool) img[mask] = img[mask] * 0.5 + color_mask * 0.5 # if out_file specified, do not show image in window if out_file is not None: show = False # draw bounding boxes mmcv.imshow_det_bboxes( img, bboxes, labels, class_names=self.CLASSES, score_thr=score_thr, bbox_color=bbox_color, text_color=text_color, thickness=thickness, font_scale=font_scale, win_name=win_name, show=show, wait_time=wait_time, out_file=out_file) if not (show or out_file): return img
from abc import ABCMeta, abstractmethod from collections import OrderedDict import mmcv import numpy as np import torch import torch.distributed as dist import torch.nn as nn from mmcv.runner import auto_fp16 from mmcv.utils import print_log from mmdet.utils import get_root_logger class BaseDetector(nn.Module, metaclass=ABCMeta): """Base class for detectors.""" def __init__(self): super(BaseDetector, self).__init__() self.fp16_enabled = False @property def with_neck(self): """bool: whether the detector has a neck""" return hasattr(self, 'neck') and self.neck is not None # TODO: these properties need to be carefully handled # for both single stage & two stage detectors @property def with_shared_head(self): """bool: whether the detector has a shared head in the RoI Head""" return hasattr(self, 'roi_head') and self.roi_head.with_shared_head @property def with_bbox(self): """bool: whether the detector has a bbox head""" return ((hasattr(self, 'roi_head') and self.roi_head.with_bbox) or (hasattr(self, 'bbox_head') and self.bbox_head is not None)) @property def with_mask(self): """bool: whether the detector has a mask head""" return ((hasattr(self, 'roi_head') and self.roi_head.with_mask) or (hasattr(self, 'mask_head') and self.mask_head is not None)) @abstractmethod def extract_feat(self, imgs): """Extract features from images.""" pass def extract_feats(self, imgs): """Extract features from multiple images. Args: imgs (list[torch.Tensor]): A list of images. The images are augmented from the same image but in different ways. Returns: list[torch.Tensor]: Features of different images """ assert isinstance(imgs, list) return [self.extract_feat(img) for img in imgs] def forward_train(self, imgs, img_metas, **kwargs): """ Args: img (list[Tensor]): List of tensors of shape (1, C, H, W). Typically these should be mean centered and std scaled. img_metas (list[dict]): List of image info dict where each dict has: 'img_shape', 'scale_factor', 'flip', and may also contain 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'. For details on the values of these keys, see :class:`mmdet.datasets.pipelines.Collect`. kwargs (keyword arguments): Specific to concrete implementation. """ # NOTE the batched image size information may be useful, e.g. # in DETR, this is needed for the construction of masks, which is # then used for the transformer_head. batch_input_shape = tuple(imgs[0].size()[-2:]) for img_meta in img_metas: img_meta['batch_input_shape'] = batch_input_shape async def async_simple_test(self, img, img_metas, **kwargs): raise NotImplementedError @abstractmethod def simple_test(self, img, img_metas, **kwargs): pass @abstractmethod def aug_test(self, imgs, img_metas, **kwargs): """Test function with test time augmentation.""" pass def init_weights(self, pretrained=None): """Initialize the weights in detector. Args: pretrained (str, optional): Path to pre-trained weights. Defaults to None. """ if pretrained is not None: logger = get_root_logger() print_log(f'load model from: {pretrained}', logger=logger) async def aforward_test(self, *, img, img_metas, **kwargs): for var, name in [(img, 'img'), (img_metas, 'img_metas')]: if not isinstance(var, list): raise TypeError(f'{name} must be a list, but got {type(var)}') num_augs = len(img) if num_augs != len(img_metas): raise ValueError(f'num of augmentations ({len(img)}) ' f'!= num of image metas ({len(img_metas)})') # TODO: remove the restriction of samples_per_gpu == 1 when prepared samples_per_gpu = img[0].size(0) assert samples_per_gpu == 1 if num_augs == 1: return await self.async_simple_test(img[0], img_metas[0], **kwargs) else: raise NotImplementedError def forward_test(self, imgs, img_metas, **kwargs): """ Args: imgs (List[Tensor]): the outer list indicates test-time augmentations and inner Tensor should have a shape NxCxHxW, which contains all images in the batch. img_metas (List[List[dict]]): the outer list indicates test-time augs (multiscale, flip, etc.) and the inner list indicates images in a batch. """ for var, name in [(imgs, 'imgs'), (img_metas, 'img_metas')]: if not isinstance(var, list): raise TypeError(f'{name} must be a list, but got {type(var)}') num_augs = len(imgs) if num_augs != len(img_metas): raise ValueError(f'num of augmentations ({len(imgs)}) ' f'!= num of image meta ({len(img_metas)})') # NOTE the batched image size information may be useful, e.g. # in DETR, this is needed for the construction of masks, which is # then used for the transformer_head. for img, img_meta in zip(imgs, img_metas): batch_size = len(img_meta) for img_id in range(batch_size): img_meta[img_id]['batch_input_shape'] = tuple(img.size()[-2:]) if num_augs == 1: # proposals (List[List[Tensor]]): the outer list indicates # test-time augs (multiscale, flip, etc.) and the inner list # indicates images in a batch. # The Tensor should have a shape Px4, where P is the number of # proposals. if 'proposals' in kwargs: kwargs['proposals'] = kwargs['proposals'][0] return self.simple_test(imgs[0], img_metas[0], **kwargs) else: assert imgs[0].size(0) == 1, 'aug test does not support ' \ 'inference with batch size ' \ f'{imgs[0].size(0)}' # TODO: support test augmentation for predefined proposals assert 'proposals' not in kwargs return self.aug_test(imgs, img_metas, **kwargs) @auto_fp16(apply_to=('img', )) def forward(self, img, img_metas, return_loss=True, **kwargs): """Calls either :func:`forward_train` or :func:`forward_test` depending on whether ``return_loss`` is ``True``. Note this setting will change the expected inputs. When ``return_loss=True``, img and img_meta are single-nested (i.e. Tensor and List[dict]), and when ``resturn_loss=False``, img and img_meta should be double nested (i.e. List[Tensor], List[List[dict]]), with the outer list indicating test time augmentations. """ if return_loss: return self.forward_train(img, img_metas, **kwargs) else: return self.forward_test(img, img_metas, **kwargs) def _parse_losses(self, losses): """Parse the raw outputs (losses) of the network. Args: losses (dict): Raw output of the network, which usually contain losses and other necessary infomation. Returns: tuple[Tensor, dict]: (loss, log_vars), loss is the loss tensor \ which may be a weighted sum of all losses, log_vars contains \ all the variables to be sent to the logger. """ log_vars = OrderedDict() for loss_name, loss_value in losses.items(): if isinstance(loss_value, torch.Tensor): log_vars[loss_name] = loss_value.mean() elif isinstance(loss_value, list): log_vars[loss_name] = sum(_loss.mean() for _loss in loss_value) else: raise TypeError( f'{loss_name} is not a tensor or list of tensors') loss = sum(_value for _key, _value in log_vars.items() if 'loss' in _key) log_vars['loss'] = loss for loss_name, loss_value in log_vars.items(): # reduce loss when distributed training if dist.is_available() and dist.is_initialized(): loss_value = loss_value.data.clone() dist.all_reduce(loss_value.div_(dist.get_world_size())) log_vars[loss_name] = loss_value.item() return loss, log_vars def train_step(self, data, optimizer): """The iteration step during training. This method defines an iteration step during training, except for the back propagation and optimizer updating, which are done in an optimizer hook. Note that in some complicated cases or models, the whole process including back propagation and optimizer updating is also defined in this method, such as GAN. Args: data (dict): The output of dataloader. optimizer (:obj:`torch.optim.Optimizer` | dict): The optimizer of runner is passed to ``train_step()``. This argument is unused and reserved. Returns: dict: It should contain at least 3 keys: ``loss``, ``log_vars``, \ ``num_samples``. - ``loss`` is a tensor for back propagation, which can be a \ weighted sum of multiple losses. - ``log_vars`` contains all the variables to be sent to the logger. - ``num_samples`` indicates the batch size (when the model is \ DDP, it means the batch size on each GPU), which is used for \ averaging the logs. """ losses = self(**data) loss, log_vars = self._parse_losses(losses) outputs = dict( loss=loss, log_vars=log_vars, num_samples=len(data['img_metas'])) return outputs def val_step(self, data, optimizer): """The iteration step during validation. This method shares the same signature as :func:`train_step`, but used during val epochs. Note that the evaluation after training epochs is not implemented with this method, but an evaluation hook. """ losses = self(**data) loss, log_vars = self._parse_losses(losses) outputs = dict( loss=loss, log_vars=log_vars, num_samples=len(data['img_metas'])) return outputs def show_result(self, img, result, score_thr=0.3, bbox_color='green', text_color='green', thickness=1, font_scale=0.5, win_name='', show=False, wait_time=0, out_file=None): """Draw `result` over `img`. Args: img (str or Tensor): The image to be displayed. result (Tensor or tuple): The results to draw over `img` bbox_result or (bbox_result, segm_result). score_thr (float, optional): Minimum score of bboxes to be shown. Default: 0.3. bbox_color (str or tuple or :obj:`Color`): Color of bbox lines. text_color (str or tuple or :obj:`Color`): Color of texts. thickness (int): Thickness of lines. font_scale (float): Font scales of texts. win_name (str): The window name. wait_time (int): Value of waitKey param. Default: 0. show (bool): Whether to show the image. Default: False. out_file (str or None): The filename to write the image. Default: None. Returns: img (Tensor): Only if not `show` or `out_file` """ img = mmcv.imread(img) img = img.copy() if isinstance(result, tuple): bbox_result, segm_result = result if isinstance(segm_result, tuple): segm_result = segm_result[0] # ms rcnn else: bbox_result, segm_result = result, None bboxes = np.vstack(bbox_result) labels = [ np.full(bbox.shape[0], i, dtype=np.int32) for i, bbox in enumerate(bbox_result) ] labels = np.concatenate(labels) # draw segmentation masks if segm_result is not None and len(labels) > 0: # non empty segms = mmcv.concat_list(segm_result) inds = np.where(bboxes[:, -1] > score_thr)[0] np.random.seed(42) color_masks = [ np.random.randint(0, 256, (1, 3), dtype=np.uint8) for _ in range(max(labels) + 1) ] for i in inds: i = int(i) color_mask = color_masks[labels[i]] sg = segms[i] if isinstance(sg, torch.Tensor): sg = sg.detach().cpu().numpy() mask = sg.astype(bool) img[mask] = img[mask] * 0.5 + color_mask * 0.5 # if out_file specified, do not show image in window if out_file is not None: show = False # draw bounding boxes mmcv.imshow_det_bboxes( img, bboxes, labels, class_names=self.CLASSES, score_thr=score_thr, bbox_color=bbox_color, text_color=text_color, thickness=thickness, font_scale=font_scale, win_name=win_name, show=show, wait_time=wait_time, out_file=out_file) if not (show or out_file): return img
en
0.787981
Base class for detectors. bool: whether the detector has a neck # TODO: these properties need to be carefully handled # for both single stage & two stage detectors bool: whether the detector has a shared head in the RoI Head bool: whether the detector has a bbox head bool: whether the detector has a mask head Extract features from images. Extract features from multiple images. Args: imgs (list[torch.Tensor]): A list of images. The images are augmented from the same image but in different ways. Returns: list[torch.Tensor]: Features of different images Args: img (list[Tensor]): List of tensors of shape (1, C, H, W). Typically these should be mean centered and std scaled. img_metas (list[dict]): List of image info dict where each dict has: 'img_shape', 'scale_factor', 'flip', and may also contain 'filename', 'ori_shape', 'pad_shape', and 'img_norm_cfg'. For details on the values of these keys, see :class:`mmdet.datasets.pipelines.Collect`. kwargs (keyword arguments): Specific to concrete implementation. # NOTE the batched image size information may be useful, e.g. # in DETR, this is needed for the construction of masks, which is # then used for the transformer_head. Test function with test time augmentation. Initialize the weights in detector. Args: pretrained (str, optional): Path to pre-trained weights. Defaults to None. # TODO: remove the restriction of samples_per_gpu == 1 when prepared Args: imgs (List[Tensor]): the outer list indicates test-time augmentations and inner Tensor should have a shape NxCxHxW, which contains all images in the batch. img_metas (List[List[dict]]): the outer list indicates test-time augs (multiscale, flip, etc.) and the inner list indicates images in a batch. # NOTE the batched image size information may be useful, e.g. # in DETR, this is needed for the construction of masks, which is # then used for the transformer_head. # proposals (List[List[Tensor]]): the outer list indicates # test-time augs (multiscale, flip, etc.) and the inner list # indicates images in a batch. # The Tensor should have a shape Px4, where P is the number of # proposals. # TODO: support test augmentation for predefined proposals Calls either :func:`forward_train` or :func:`forward_test` depending on whether ``return_loss`` is ``True``. Note this setting will change the expected inputs. When ``return_loss=True``, img and img_meta are single-nested (i.e. Tensor and List[dict]), and when ``resturn_loss=False``, img and img_meta should be double nested (i.e. List[Tensor], List[List[dict]]), with the outer list indicating test time augmentations. Parse the raw outputs (losses) of the network. Args: losses (dict): Raw output of the network, which usually contain losses and other necessary infomation. Returns: tuple[Tensor, dict]: (loss, log_vars), loss is the loss tensor \ which may be a weighted sum of all losses, log_vars contains \ all the variables to be sent to the logger. # reduce loss when distributed training The iteration step during training. This method defines an iteration step during training, except for the back propagation and optimizer updating, which are done in an optimizer hook. Note that in some complicated cases or models, the whole process including back propagation and optimizer updating is also defined in this method, such as GAN. Args: data (dict): The output of dataloader. optimizer (:obj:`torch.optim.Optimizer` | dict): The optimizer of runner is passed to ``train_step()``. This argument is unused and reserved. Returns: dict: It should contain at least 3 keys: ``loss``, ``log_vars``, \ ``num_samples``. - ``loss`` is a tensor for back propagation, which can be a \ weighted sum of multiple losses. - ``log_vars`` contains all the variables to be sent to the logger. - ``num_samples`` indicates the batch size (when the model is \ DDP, it means the batch size on each GPU), which is used for \ averaging the logs. The iteration step during validation. This method shares the same signature as :func:`train_step`, but used during val epochs. Note that the evaluation after training epochs is not implemented with this method, but an evaluation hook. Draw `result` over `img`. Args: img (str or Tensor): The image to be displayed. result (Tensor or tuple): The results to draw over `img` bbox_result or (bbox_result, segm_result). score_thr (float, optional): Minimum score of bboxes to be shown. Default: 0.3. bbox_color (str or tuple or :obj:`Color`): Color of bbox lines. text_color (str or tuple or :obj:`Color`): Color of texts. thickness (int): Thickness of lines. font_scale (float): Font scales of texts. win_name (str): The window name. wait_time (int): Value of waitKey param. Default: 0. show (bool): Whether to show the image. Default: False. out_file (str or None): The filename to write the image. Default: None. Returns: img (Tensor): Only if not `show` or `out_file` # ms rcnn # draw segmentation masks # non empty # if out_file specified, do not show image in window # draw bounding boxes
2.115427
2
platform/gsutil/gslib/commands/cors.py
bopopescu/SDK
0
6625753
# -*- coding: utf-8 -*- # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of cors configuration command for GCS buckets.""" from __future__ import absolute_import import sys from gslib.command import Command from gslib.command_argument import CommandArgument from gslib.cs_api_map import ApiSelector from gslib.exception import CommandException from gslib.exception import NO_URLS_MATCHED_TARGET from gslib.help_provider import CreateHelpText from gslib.storage_url import StorageUrlFromString from gslib.third_party.storage_apitools import storage_v1_messages as apitools_messages from gslib.translation_helper import CorsTranslation from gslib.translation_helper import REMOVE_CORS_CONFIG from gslib.util import NO_MAX from gslib.util import UrlsAreForSingleProvider _GET_SYNOPSIS = """ gsutil cors get url """ _SET_SYNOPSIS = """ gsutil cors set cors-json-file url... """ _GET_DESCRIPTION = """ <B>GET</B> Gets the CORS configuration for a single bucket. The output from "cors get" can be redirected into a file, edited and then updated using "cors set". """ _SET_DESCRIPTION = """ <B>SET</B> Sets the CORS configuration for one or more buckets. The cors-json-file specified on the command line should be a path to a local file containing a JSON document as described above. """ _SYNOPSIS = _SET_SYNOPSIS + _GET_SYNOPSIS.lstrip('\n') + '\n\n' _DESCRIPTION = (""" Gets or sets the Cross-Origin Resource Sharing (CORS) configuration on one or more buckets. This command is supported for buckets only, not objects. An example CORS JSON document looks like the folllowing: [ { "origin": ["http://origin1.example.com"], "responseHeader": ["Content-Type"], "method": ["GET"], "maxAgeSeconds": 3600 } ] The above JSON document explicitly allows cross-origin GET requests from http://origin1.example.com and may include the Content-Type response header. The preflight request may be cached for 1 hour. The following (empty) CORS JSON document removes all CORS configuration for a bucket: [] The cors command has two sub-commands: """ + '\n'.join([_GET_DESCRIPTION, _SET_DESCRIPTION]) + """ For more info about CORS, see http://www.w3.org/TR/cors/. """) _DETAILED_HELP_TEXT = CreateHelpText(_SYNOPSIS, _DESCRIPTION) _get_help_text = CreateHelpText(_GET_SYNOPSIS, _GET_DESCRIPTION) _set_help_text = CreateHelpText(_SET_SYNOPSIS, _SET_DESCRIPTION) class CorsCommand(Command): """Implementation of gsutil cors command.""" # Command specification. See base class for documentation. command_spec = Command.CreateCommandSpec( 'cors', command_name_aliases=['getcors', 'setcors'], usage_synopsis=_SYNOPSIS, min_args=2, max_args=NO_MAX, supported_sub_args='', file_url_ok=False, provider_url_ok=False, urls_start_arg=1, gs_api_support=[ApiSelector.XML, ApiSelector.JSON], gs_default_api=ApiSelector.JSON, argparse_arguments={ 'set': [ CommandArgument.MakeNFileURLsArgument(1), CommandArgument.MakeZeroOrMoreCloudBucketURLsArgument() ], 'get': [ CommandArgument.MakeNCloudBucketURLsArgument(1) ] } ) # Help specification. See help_provider.py for documentation. help_spec = Command.HelpSpec( help_name='cors', help_name_aliases=['getcors', 'setcors', 'cross-origin'], help_type='command_help', help_one_line_summary=( 'Set a CORS JSON document for one or more buckets'), help_text=_DETAILED_HELP_TEXT, subcommand_help_text={'get': _get_help_text, 'set': _set_help_text}, ) def _CalculateUrlsStartArg(self): if not self.args: self.RaiseWrongNumberOfArgumentsException() if self.args[0].lower() == 'set': return 2 else: return 1 def _SetCors(self): """Sets CORS configuration on a Google Cloud Storage bucket.""" cors_arg = self.args[0] url_args = self.args[1:] # Disallow multi-provider 'cors set' requests. if not UrlsAreForSingleProvider(url_args): raise CommandException('"%s" command spanning providers not allowed.' % self.command_name) # Open, read and parse file containing JSON document. cors_file = open(cors_arg, 'r') cors_txt = cors_file.read() cors_file.close() self.api = self.gsutil_api.GetApiSelector( StorageUrlFromString(url_args[0]).scheme) # Iterate over URLs, expanding wildcards and setting the CORS on each. some_matched = False for url_str in url_args: bucket_iter = self.GetBucketUrlIterFromArg(url_str, bucket_fields=['id']) for blr in bucket_iter: url = blr.storage_url some_matched = True self.logger.info('Setting CORS on %s...', blr) if url.scheme == 's3': self.gsutil_api.XmlPassThroughSetCors( cors_txt, url, provider=url.scheme) else: cors = CorsTranslation.JsonCorsToMessageEntries(cors_txt) if not cors: cors = REMOVE_CORS_CONFIG bucket_metadata = apitools_messages.Bucket(cors=cors) self.gsutil_api.PatchBucket(url.bucket_name, bucket_metadata, provider=url.scheme, fields=['id']) if not some_matched: raise CommandException(NO_URLS_MATCHED_TARGET % list(url_args)) return 0 def _GetCors(self): """Gets CORS configuration for a Google Cloud Storage bucket.""" bucket_url, bucket_metadata = self.GetSingleBucketUrlFromArg( self.args[0], bucket_fields=['cors']) if bucket_url.scheme == 's3': sys.stdout.write(self.gsutil_api.XmlPassThroughGetCors( bucket_url, provider=bucket_url.scheme)) else: if bucket_metadata.cors: sys.stdout.write( CorsTranslation.MessageEntriesToJson(bucket_metadata.cors)) else: sys.stdout.write('%s has no CORS configuration.\n' % bucket_url) return 0 def RunCommand(self): """Command entry point for the cors command.""" action_subcommand = self.args.pop(0) if action_subcommand == 'get': func = self._GetCors elif action_subcommand == 'set': func = self._SetCors else: raise CommandException(('Invalid subcommand "%s" for the %s command.\n' 'See "gsutil help cors".') % (action_subcommand, self.command_name)) return func()
# -*- coding: utf-8 -*- # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Implementation of cors configuration command for GCS buckets.""" from __future__ import absolute_import import sys from gslib.command import Command from gslib.command_argument import CommandArgument from gslib.cs_api_map import ApiSelector from gslib.exception import CommandException from gslib.exception import NO_URLS_MATCHED_TARGET from gslib.help_provider import CreateHelpText from gslib.storage_url import StorageUrlFromString from gslib.third_party.storage_apitools import storage_v1_messages as apitools_messages from gslib.translation_helper import CorsTranslation from gslib.translation_helper import REMOVE_CORS_CONFIG from gslib.util import NO_MAX from gslib.util import UrlsAreForSingleProvider _GET_SYNOPSIS = """ gsutil cors get url """ _SET_SYNOPSIS = """ gsutil cors set cors-json-file url... """ _GET_DESCRIPTION = """ <B>GET</B> Gets the CORS configuration for a single bucket. The output from "cors get" can be redirected into a file, edited and then updated using "cors set". """ _SET_DESCRIPTION = """ <B>SET</B> Sets the CORS configuration for one or more buckets. The cors-json-file specified on the command line should be a path to a local file containing a JSON document as described above. """ _SYNOPSIS = _SET_SYNOPSIS + _GET_SYNOPSIS.lstrip('\n') + '\n\n' _DESCRIPTION = (""" Gets or sets the Cross-Origin Resource Sharing (CORS) configuration on one or more buckets. This command is supported for buckets only, not objects. An example CORS JSON document looks like the folllowing: [ { "origin": ["http://origin1.example.com"], "responseHeader": ["Content-Type"], "method": ["GET"], "maxAgeSeconds": 3600 } ] The above JSON document explicitly allows cross-origin GET requests from http://origin1.example.com and may include the Content-Type response header. The preflight request may be cached for 1 hour. The following (empty) CORS JSON document removes all CORS configuration for a bucket: [] The cors command has two sub-commands: """ + '\n'.join([_GET_DESCRIPTION, _SET_DESCRIPTION]) + """ For more info about CORS, see http://www.w3.org/TR/cors/. """) _DETAILED_HELP_TEXT = CreateHelpText(_SYNOPSIS, _DESCRIPTION) _get_help_text = CreateHelpText(_GET_SYNOPSIS, _GET_DESCRIPTION) _set_help_text = CreateHelpText(_SET_SYNOPSIS, _SET_DESCRIPTION) class CorsCommand(Command): """Implementation of gsutil cors command.""" # Command specification. See base class for documentation. command_spec = Command.CreateCommandSpec( 'cors', command_name_aliases=['getcors', 'setcors'], usage_synopsis=_SYNOPSIS, min_args=2, max_args=NO_MAX, supported_sub_args='', file_url_ok=False, provider_url_ok=False, urls_start_arg=1, gs_api_support=[ApiSelector.XML, ApiSelector.JSON], gs_default_api=ApiSelector.JSON, argparse_arguments={ 'set': [ CommandArgument.MakeNFileURLsArgument(1), CommandArgument.MakeZeroOrMoreCloudBucketURLsArgument() ], 'get': [ CommandArgument.MakeNCloudBucketURLsArgument(1) ] } ) # Help specification. See help_provider.py for documentation. help_spec = Command.HelpSpec( help_name='cors', help_name_aliases=['getcors', 'setcors', 'cross-origin'], help_type='command_help', help_one_line_summary=( 'Set a CORS JSON document for one or more buckets'), help_text=_DETAILED_HELP_TEXT, subcommand_help_text={'get': _get_help_text, 'set': _set_help_text}, ) def _CalculateUrlsStartArg(self): if not self.args: self.RaiseWrongNumberOfArgumentsException() if self.args[0].lower() == 'set': return 2 else: return 1 def _SetCors(self): """Sets CORS configuration on a Google Cloud Storage bucket.""" cors_arg = self.args[0] url_args = self.args[1:] # Disallow multi-provider 'cors set' requests. if not UrlsAreForSingleProvider(url_args): raise CommandException('"%s" command spanning providers not allowed.' % self.command_name) # Open, read and parse file containing JSON document. cors_file = open(cors_arg, 'r') cors_txt = cors_file.read() cors_file.close() self.api = self.gsutil_api.GetApiSelector( StorageUrlFromString(url_args[0]).scheme) # Iterate over URLs, expanding wildcards and setting the CORS on each. some_matched = False for url_str in url_args: bucket_iter = self.GetBucketUrlIterFromArg(url_str, bucket_fields=['id']) for blr in bucket_iter: url = blr.storage_url some_matched = True self.logger.info('Setting CORS on %s...', blr) if url.scheme == 's3': self.gsutil_api.XmlPassThroughSetCors( cors_txt, url, provider=url.scheme) else: cors = CorsTranslation.JsonCorsToMessageEntries(cors_txt) if not cors: cors = REMOVE_CORS_CONFIG bucket_metadata = apitools_messages.Bucket(cors=cors) self.gsutil_api.PatchBucket(url.bucket_name, bucket_metadata, provider=url.scheme, fields=['id']) if not some_matched: raise CommandException(NO_URLS_MATCHED_TARGET % list(url_args)) return 0 def _GetCors(self): """Gets CORS configuration for a Google Cloud Storage bucket.""" bucket_url, bucket_metadata = self.GetSingleBucketUrlFromArg( self.args[0], bucket_fields=['cors']) if bucket_url.scheme == 's3': sys.stdout.write(self.gsutil_api.XmlPassThroughGetCors( bucket_url, provider=bucket_url.scheme)) else: if bucket_metadata.cors: sys.stdout.write( CorsTranslation.MessageEntriesToJson(bucket_metadata.cors)) else: sys.stdout.write('%s has no CORS configuration.\n' % bucket_url) return 0 def RunCommand(self): """Command entry point for the cors command.""" action_subcommand = self.args.pop(0) if action_subcommand == 'get': func = self._GetCors elif action_subcommand == 'set': func = self._SetCors else: raise CommandException(('Invalid subcommand "%s" for the %s command.\n' 'See "gsutil help cors".') % (action_subcommand, self.command_name)) return func()
en
0.734944
# -*- coding: utf-8 -*- # Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. Implementation of cors configuration command for GCS buckets. gsutil cors get url gsutil cors set cors-json-file url... <B>GET</B> Gets the CORS configuration for a single bucket. The output from "cors get" can be redirected into a file, edited and then updated using "cors set". <B>SET</B> Sets the CORS configuration for one or more buckets. The cors-json-file specified on the command line should be a path to a local file containing a JSON document as described above. Gets or sets the Cross-Origin Resource Sharing (CORS) configuration on one or more buckets. This command is supported for buckets only, not objects. An example CORS JSON document looks like the folllowing: [ { "origin": ["http://origin1.example.com"], "responseHeader": ["Content-Type"], "method": ["GET"], "maxAgeSeconds": 3600 } ] The above JSON document explicitly allows cross-origin GET requests from http://origin1.example.com and may include the Content-Type response header. The preflight request may be cached for 1 hour. The following (empty) CORS JSON document removes all CORS configuration for a bucket: [] The cors command has two sub-commands: For more info about CORS, see http://www.w3.org/TR/cors/. Implementation of gsutil cors command. # Command specification. See base class for documentation. # Help specification. See help_provider.py for documentation. Sets CORS configuration on a Google Cloud Storage bucket. # Disallow multi-provider 'cors set' requests. # Open, read and parse file containing JSON document. # Iterate over URLs, expanding wildcards and setting the CORS on each. Gets CORS configuration for a Google Cloud Storage bucket. Command entry point for the cors command.
1.77858
2
azure-mgmt-botservice/azure/mgmt/botservice/models/azure_bot_service_enums.py
Christina-Kang/azure-sdk-for-python
1
6625754
<filename>azure-mgmt-botservice/azure/mgmt/botservice/models/azure_bot_service_enums.py # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from enum import Enum class SkuName(Enum): f0 = "F0" s1 = "S1" class SkuTier(Enum): free = "Free" standard = "Standard" class Kind(Enum): sdk = "sdk" designer = "designer" bot = "bot" function = "function" class ChannelName(Enum): facebook_channel = "FacebookChannel" email_channel = "EmailChannel"
<filename>azure-mgmt-botservice/azure/mgmt/botservice/models/azure_bot_service_enums.py # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from enum import Enum class SkuName(Enum): f0 = "F0" s1 = "S1" class SkuTier(Enum): free = "Free" standard = "Standard" class Kind(Enum): sdk = "sdk" designer = "designer" bot = "bot" function = "function" class ChannelName(Enum): facebook_channel = "FacebookChannel" email_channel = "EmailChannel"
en
0.583126
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # --------------------------------------------------------------------------
1.813247
2
example2.py
elplatt/repsci
2
6625755
<gh_stars>1-10 # Import the logging library import repsci # Create a config import configparser config = configparser.ConfigParser() config['DEFAULT'] = { 'message': 'Hello, World!' } # Create an experiment exp_name = "hello_config" exp = repsci.Experiment(exp_name, config=config) # Get the logger and write a log message log = exp.get_logger() log.info(config['DEFAULT']['message']) # Create an output file in the unique output directory filename = exp.get_filename('output.csv') with open(filename, "w") as f: f.write(config['DEFAULT']['message'] + '\n')
# Import the logging library import repsci # Create a config import configparser config = configparser.ConfigParser() config['DEFAULT'] = { 'message': 'Hello, World!' } # Create an experiment exp_name = "hello_config" exp = repsci.Experiment(exp_name, config=config) # Get the logger and write a log message log = exp.get_logger() log.info(config['DEFAULT']['message']) # Create an output file in the unique output directory filename = exp.get_filename('output.csv') with open(filename, "w") as f: f.write(config['DEFAULT']['message'] + '\n')
en
0.591657
# Import the logging library # Create a config # Create an experiment # Get the logger and write a log message # Create an output file in the unique output directory
2.829704
3
bioconda_utils/docker_utils.py
grst/bioconda-utils
0
6625756
#!/usr/bin/env python """ To ensure conda packages are built in the most compatible manner, we can use a docker container. This module supports using a docker container to build conda packages in the local channel which can later be uploaded to anaconda. Note that we cannot simply bind the host's conda-bld directory to the container's conda-bld directory because during building/testing, symlinks are made to the conda-pkgs dir which is not necessarily bound. Nor should it be, if we want to retain isolation from the host when building. To solve this, we mount the host's conda-bld dir to a temporary directory in the container. Once the container successfully builds a package, the corresponding package is copied over to the temporary directory (the host's conda-bld directory) so that the built package appears on the host. In the end the workflow is: - build a custom docker container (assumed to already have conda installed) where the requirements in ``bioconda-utils/bioconda-utils_requirements.txt`` have been conda installed. - mount the host's conda-bld to a read/write temporary dir in the container (configured in the RecipeBuilder) - in the container, add this directory as a local channel so that all previously-built packages can be used as dependencies. - mount the host's recipe dir to a read-only dir in the container (configured in the RecipeBuilder) - build, mount, and run a custom script that conda-builds the mounted recipe and if successful copies the built package to the mounted host's conda-bld directory. Other notes: - Most communication with the host (conda-bld options; host's UID) is via environmental variables passed to the container. - The build script is custom generated each run, providing lots of flexibility. Most magic happens here. """ import os import os.path from shlex import quote import shutil import subprocess as sp import tempfile import pwd import grp from textwrap import dedent import pkg_resources import re from distutils.version import LooseVersion import conda import conda_build from . import utils import logging logger = logging.getLogger(__name__) # ---------------------------------------------------------------------------- # BUILD_SCRIPT_TEMPLATE # ---------------------------------------------------------------------------- # # The following script is the default that will be regenerated on each call to # RecipeBuilder.build_recipe() and mounted at container run time when building # a recipe. It can be overridden by providing a different template when calling # RecipeBuilder.build_recipe(). # # It will be filled in using BUILD_SCRIPT_TEMPLATE.format(self=self), so you # can add additional attributes to the RecipeBuilder instance and have them # filled in here. # BUILD_SCRIPT_TEMPLATE = \ """ #!/bin/bash set -eo pipefail # Add the host's mounted conda-bld dir so that we can use its contents as # dependencies for building this recipe. # # Note that if the directory didn't exist on the host, then the staging area # will exist in the container but will be empty. Channels expect at least # a linux-64 and noarch directory within that directory, so we make sure it # exists before adding the channel. mkdir -p {self.container_staging}/linux-64 mkdir -p {self.container_staging}/noarch conda config --add channels file://{self.container_staging} 2> >( grep -vF "Warning: 'file://{self.container_staging}' already in 'channels' list, moving to the top" >&2 ) # The actual building... # we explicitly point to the meta.yaml, in order to keep # conda-build from building all subdirectories conda build {self.conda_build_args} {self.container_recipe}/meta.yaml 2>&1 # copy all built packages to the staging area cp `conda build {self.conda_build_args} {self.container_recipe}/meta.yaml --output` {self.container_staging}/{arch} # Ensure permissions are correct on the host. HOST_USER={self.user_info[uid]} chown $HOST_USER:$HOST_USER {self.container_staging}/{arch}/* """ # noqa: E501,E122: line too long, continuation line missing indentation or outdented # ---------------------------------------------------------------------------- # DOCKERFILE_TEMPLATE # ---------------------------------------------------------------------------- # # This template can be used for last-minute changes to the docker image, such # as adding proxies. # # The default image is created automatically on DockerHub using the Dockerfile # in the bioconda-utils repo. DOCKERFILE_TEMPLATE = \ """ FROM {docker_base_image} {proxies} RUN /opt/conda/bin/conda install -y conda={conda_ver} conda-build={conda_build_ver} """ # noqa: E122 continuation line missing indentation or outdented class DockerCalledProcessError(sp.CalledProcessError): pass class DockerBuildError(Exception): pass def get_host_conda_bld(): """ Identifies the conda-bld directory on the host. Assumes that conda-build is installed. """ # v0.16.2: this used to have a side effect, calling conda build purge # hopefully, it's not actually needed. build_conf = utils.load_conda_build_config() return build_conf.build_folder class RecipeBuilder(object): def __init__( self, tag='tmp-bioconda-builder', container_recipe='/opt/recipe', container_staging="/opt/host-conda-bld", requirements=None, build_script_template=BUILD_SCRIPT_TEMPLATE, dockerfile_template=DOCKERFILE_TEMPLATE, use_host_conda_bld=False, pkg_dir=None, keep_image=False, build_image=False, image_build_dir=None, docker_base_image='bioconda/bioconda-utils-build-env:latest' ): """ Class to handle building a custom docker container that can be used for building conda recipes. Parameters ---------- tag : str Tag to be used for the custom-build docker container. Mostly for debugging purposes when you need to inspect the container. container_recipe : str Directory to which the host's recipe will be exported. Will be read-only. container_staging : str Directory to which the host's conda-bld dir will be mounted so that the container can use previously-built packages as dependencies. Upon successful building container-built packages will be copied over. Mounted as read-write. requirements : None or str Path to a "requirements.txt" file which will be installed with conda in a newly-created container. If None, then use the default installed with bioconda_utils. build_script_template : str Template that will be filled in with .format(self=self) and that will be run in the container each time build_recipe() is called. If not specified, uses docker_utils.BUILD_SCRIPT_TEMPLATE. dockerfile_template : str Template that will be filled in with .format(self=self) and that will be used to build a custom image. Uses docker_utils.DOCKERFILE_TEMPLATE by default. use_host_conda_bld : bool If True, then use the host's conda-bld directory. This will export the host's existing conda-bld directory to the docker container, and any recipes successfully built by the container will be added here. Otherwise, use **pkg_dir** as a common host directory used across multiple runs of this RecipeBuilder object. pkg_dir : str or None Specify where packages should appear on the host. If **pkg_dir** is None, then a temporary directory will be created once for each `RecipeBuilder` instance and that directory will be used for each call to `RecipeBuilder.build_recipe()`. This allows subsequent recipes built by the container to see previous built recipes without polluting the host's conda-bld directory. If **pkg_dir** is a string, then it will be created if needed and this directory will be used store all built packages on the host instead of the temp dir. If the above argument **use_host_conda_bld** is `True`, then the value of **pkg_dir** will be ignored and the host's conda-bld directory will be used. In all cases, **pkg_dir** will be mounted to **container_staging** in the container. build_image : bool Build a local layer on top of the **docker_base_image** layer using **dockerfile_template**. This can be used to adjust the versions of conda and conda-build in the build container. keep_image : bool By default, the built docker image will be removed when done, freeing up storage space. Set ``keep_image=True`` to disable this behavior. image_build_dir : str or None If not None, use an existing directory as a docker image context instead of a temporary one. For testing purposes only. docker_base_image : str or None Name of base image that can be used in **dockerfile_template**. Defaults to 'bioconda/bioconda-utils-build-env:latest' """ self.requirements = requirements self.conda_build_args = "" self.build_script_template = build_script_template self.dockerfile_template = dockerfile_template self.keep_image = keep_image self.build_image = build_image self.image_build_dir = image_build_dir self.docker_base_image = docker_base_image self.docker_temp_image = tag # find and store user info uid = os.getuid() usr = pwd.getpwuid(uid) self.user_info = dict( uid=uid, gid=usr.pw_gid, groupname=grp.getgrgid(usr.pw_gid).gr_name, username=usr.pw_name) self.container_recipe = container_recipe self.container_staging = container_staging self.host_conda_bld = get_host_conda_bld() if use_host_conda_bld: self.pkg_dir = self.host_conda_bld else: if pkg_dir is None: self.pkg_dir = tempfile.mkdtemp() else: if not os.path.exists(pkg_dir): os.makedirs(pkg_dir) self.pkg_dir = pkg_dir # Copy the conda build config files to the staging directory that is # visible in the container for i, config_file in enumerate(utils.get_conda_build_config_files()): dst_file = self._get_config_path(self.pkg_dir, i, config_file) shutil.copyfile(config_file.path, dst_file) if self.build_image: self._build_image() def _get_config_path(self, staging_prefix, i, config_file): src_basename = os.path.basename(config_file.path) dst_basename = 'conda_build_config_{}_{}_{}'.format(i, config_file.arg, src_basename) return os.path.join(staging_prefix, dst_basename) def __del__(self): self.cleanup() def _find_proxy_settings(self): res = {} for var in ('http_proxy', 'https_proxy'): values = set([ os.environ.get(var, None), os.environ.get(var.upper(), None) ]).difference([None]) if len(values) == 1: res[var] = next(iter(values)) elif len(values) > 1: raise ValueError(f"{var} and {var.upper()} have different values") return res def _build_image(self): """ Builds a new image with requirements installed. """ if self.image_build_dir is None: # Create a temporary build directory since we'll be copying the # requirements file over build_dir = tempfile.mkdtemp() else: build_dir = self.image_build_dir logger.info('DOCKER: Building image "%s" from %s', self.docker_temp_image, build_dir) with open(os.path.join(build_dir, 'requirements.txt'), 'w') as fout: if self.requirements: fout.write(open(self.requirements).read()) else: fout.write(open(pkg_resources.resource_filename( 'bioconda_utils', 'bioconda_utils-requirements.txt') ).read()) proxies = "\n".join("ENV {} {}".format(k, v) for k, v in self._find_proxy_settings()) with open(os.path.join(build_dir, "Dockerfile"), 'w') as fout: fout.write(self.dockerfile_template.format( docker_base_image=self.docker_base_image, proxies=proxies, conda_ver=conda.__version__, conda_build_ver=conda_build.__version__) ) logger.debug('Dockerfile:\n' + open(fout.name).read()) # Check if the installed version of docker supports the --network flag # (requires version >= 1.13.0) # Parse output of `docker --version` since the format of the # `docker version` command (note the missing dashes) is not consistent # between different docker versions. The --version string is the same # for docker 1.6.2 and 1.12.6 try: s = sp.check_output(["docker", "--version"]).decode() except FileNotFoundError: logger.error('DOCKER FAILED: Error checking docker version, is it installed?') raise except sp.CalledProcessError: logger.error('DOCKER FAILED: Error checking docker version.') raise p = re.compile(r"\d+\.\d+\.\d+") # three groups of at least on digit separated by dots version_string = re.search(p, s).group(0) if LooseVersion(version_string) >= LooseVersion("1.13.0"): cmd = [ 'docker', 'build', # xref #5027 '--network', 'host', '-t', self.docker_temp_image, build_dir ] else: # Network flag was added in 1.13.0, do not add it for lower versions. xref #5387 cmd = [ 'docker', 'build', '-t', self.docker_temp_image, build_dir ] try: with utils.Progress(): p = utils.run(cmd, mask=False) except sp.CalledProcessError as e: logger.error( 'DOCKER FAILED: Error building docker container %s. ', self.docker_temp_image) raise e logger.info('DOCKER: Built docker image tag=%s', self.docker_temp_image) if self.image_build_dir is None: shutil.rmtree(build_dir) return p def build_recipe(self, recipe_dir, build_args, env, noarch=False): """ Build a single recipe. Parameters ---------- recipe_dir : str Path to recipe that contains meta.yaml build_args : str Additional arguments to ``conda build``. For example --channel, --skip-existing, etc env : dict Environmental variables noarch: bool Has to be set to true if this is a noarch build Note that the binds are set up automatically to match the expectations of the build script, and will use the currently-configured self.container_staging and self.container_recipe. """ # Attach the build args to self so that it can be filled in by the # template. if not isinstance(build_args, str): raise ValueError('build_args must be str') build_args_list = [build_args] for i, config_file in enumerate(utils.get_conda_build_config_files()): dst_file = self._get_config_path(self.container_staging, i, config_file) build_args_list.extend([config_file.arg, quote(dst_file)]) self.conda_build_args = ' '.join(build_args_list) # Write build script to tempfile build_dir = os.path.realpath(tempfile.mkdtemp()) script = self.build_script_template.format( self=self, arch='noarch' if noarch else 'linux-64') with open(os.path.join(build_dir, 'build_script.bash'), 'w') as fout: fout.write(script) build_script = fout.name logger.debug('DOCKER: Container build script: \n%s', open(fout.name).read()) # Build the args for env vars. Note can also write these to tempfile # and use --env-file arg, but using -e seems clearer in debug output. env_list = [] for k, v in env.items(): env_list.append('-e') env_list.append('{0}={1}'.format(k, v)) env_list.append('-e') env_list.append('{0}={1}'.format('HOST_USER_ID', self.user_info['uid'])) cmd = [ 'docker', 'run', '-t', '--net', 'host', '--rm', '-v', '{0}:/opt/build_script.bash'.format(build_script), '-v', '{0}:{1}'.format(self.pkg_dir, self.container_staging), '-v', '{0}:{1}'.format(recipe_dir, self.container_recipe), ] cmd += env_list if self.build_image: cmd += [self.docker_temp_image] else: cmd += [self.docker_base_image] cmd += ['/bin/bash', '/opt/build_script.bash'] logger.debug('DOCKER: cmd: %s', cmd) with utils.Progress(): p = utils.run(cmd, mask=False) return p def cleanup(self): if self.build_image and not self.keep_image: cmd = ['docker', 'rmi', self.docker_temp_image] utils.run(cmd, mask=False)
#!/usr/bin/env python """ To ensure conda packages are built in the most compatible manner, we can use a docker container. This module supports using a docker container to build conda packages in the local channel which can later be uploaded to anaconda. Note that we cannot simply bind the host's conda-bld directory to the container's conda-bld directory because during building/testing, symlinks are made to the conda-pkgs dir which is not necessarily bound. Nor should it be, if we want to retain isolation from the host when building. To solve this, we mount the host's conda-bld dir to a temporary directory in the container. Once the container successfully builds a package, the corresponding package is copied over to the temporary directory (the host's conda-bld directory) so that the built package appears on the host. In the end the workflow is: - build a custom docker container (assumed to already have conda installed) where the requirements in ``bioconda-utils/bioconda-utils_requirements.txt`` have been conda installed. - mount the host's conda-bld to a read/write temporary dir in the container (configured in the RecipeBuilder) - in the container, add this directory as a local channel so that all previously-built packages can be used as dependencies. - mount the host's recipe dir to a read-only dir in the container (configured in the RecipeBuilder) - build, mount, and run a custom script that conda-builds the mounted recipe and if successful copies the built package to the mounted host's conda-bld directory. Other notes: - Most communication with the host (conda-bld options; host's UID) is via environmental variables passed to the container. - The build script is custom generated each run, providing lots of flexibility. Most magic happens here. """ import os import os.path from shlex import quote import shutil import subprocess as sp import tempfile import pwd import grp from textwrap import dedent import pkg_resources import re from distutils.version import LooseVersion import conda import conda_build from . import utils import logging logger = logging.getLogger(__name__) # ---------------------------------------------------------------------------- # BUILD_SCRIPT_TEMPLATE # ---------------------------------------------------------------------------- # # The following script is the default that will be regenerated on each call to # RecipeBuilder.build_recipe() and mounted at container run time when building # a recipe. It can be overridden by providing a different template when calling # RecipeBuilder.build_recipe(). # # It will be filled in using BUILD_SCRIPT_TEMPLATE.format(self=self), so you # can add additional attributes to the RecipeBuilder instance and have them # filled in here. # BUILD_SCRIPT_TEMPLATE = \ """ #!/bin/bash set -eo pipefail # Add the host's mounted conda-bld dir so that we can use its contents as # dependencies for building this recipe. # # Note that if the directory didn't exist on the host, then the staging area # will exist in the container but will be empty. Channels expect at least # a linux-64 and noarch directory within that directory, so we make sure it # exists before adding the channel. mkdir -p {self.container_staging}/linux-64 mkdir -p {self.container_staging}/noarch conda config --add channels file://{self.container_staging} 2> >( grep -vF "Warning: 'file://{self.container_staging}' already in 'channels' list, moving to the top" >&2 ) # The actual building... # we explicitly point to the meta.yaml, in order to keep # conda-build from building all subdirectories conda build {self.conda_build_args} {self.container_recipe}/meta.yaml 2>&1 # copy all built packages to the staging area cp `conda build {self.conda_build_args} {self.container_recipe}/meta.yaml --output` {self.container_staging}/{arch} # Ensure permissions are correct on the host. HOST_USER={self.user_info[uid]} chown $HOST_USER:$HOST_USER {self.container_staging}/{arch}/* """ # noqa: E501,E122: line too long, continuation line missing indentation or outdented # ---------------------------------------------------------------------------- # DOCKERFILE_TEMPLATE # ---------------------------------------------------------------------------- # # This template can be used for last-minute changes to the docker image, such # as adding proxies. # # The default image is created automatically on DockerHub using the Dockerfile # in the bioconda-utils repo. DOCKERFILE_TEMPLATE = \ """ FROM {docker_base_image} {proxies} RUN /opt/conda/bin/conda install -y conda={conda_ver} conda-build={conda_build_ver} """ # noqa: E122 continuation line missing indentation or outdented class DockerCalledProcessError(sp.CalledProcessError): pass class DockerBuildError(Exception): pass def get_host_conda_bld(): """ Identifies the conda-bld directory on the host. Assumes that conda-build is installed. """ # v0.16.2: this used to have a side effect, calling conda build purge # hopefully, it's not actually needed. build_conf = utils.load_conda_build_config() return build_conf.build_folder class RecipeBuilder(object): def __init__( self, tag='tmp-bioconda-builder', container_recipe='/opt/recipe', container_staging="/opt/host-conda-bld", requirements=None, build_script_template=BUILD_SCRIPT_TEMPLATE, dockerfile_template=DOCKERFILE_TEMPLATE, use_host_conda_bld=False, pkg_dir=None, keep_image=False, build_image=False, image_build_dir=None, docker_base_image='bioconda/bioconda-utils-build-env:latest' ): """ Class to handle building a custom docker container that can be used for building conda recipes. Parameters ---------- tag : str Tag to be used for the custom-build docker container. Mostly for debugging purposes when you need to inspect the container. container_recipe : str Directory to which the host's recipe will be exported. Will be read-only. container_staging : str Directory to which the host's conda-bld dir will be mounted so that the container can use previously-built packages as dependencies. Upon successful building container-built packages will be copied over. Mounted as read-write. requirements : None or str Path to a "requirements.txt" file which will be installed with conda in a newly-created container. If None, then use the default installed with bioconda_utils. build_script_template : str Template that will be filled in with .format(self=self) and that will be run in the container each time build_recipe() is called. If not specified, uses docker_utils.BUILD_SCRIPT_TEMPLATE. dockerfile_template : str Template that will be filled in with .format(self=self) and that will be used to build a custom image. Uses docker_utils.DOCKERFILE_TEMPLATE by default. use_host_conda_bld : bool If True, then use the host's conda-bld directory. This will export the host's existing conda-bld directory to the docker container, and any recipes successfully built by the container will be added here. Otherwise, use **pkg_dir** as a common host directory used across multiple runs of this RecipeBuilder object. pkg_dir : str or None Specify where packages should appear on the host. If **pkg_dir** is None, then a temporary directory will be created once for each `RecipeBuilder` instance and that directory will be used for each call to `RecipeBuilder.build_recipe()`. This allows subsequent recipes built by the container to see previous built recipes without polluting the host's conda-bld directory. If **pkg_dir** is a string, then it will be created if needed and this directory will be used store all built packages on the host instead of the temp dir. If the above argument **use_host_conda_bld** is `True`, then the value of **pkg_dir** will be ignored and the host's conda-bld directory will be used. In all cases, **pkg_dir** will be mounted to **container_staging** in the container. build_image : bool Build a local layer on top of the **docker_base_image** layer using **dockerfile_template**. This can be used to adjust the versions of conda and conda-build in the build container. keep_image : bool By default, the built docker image will be removed when done, freeing up storage space. Set ``keep_image=True`` to disable this behavior. image_build_dir : str or None If not None, use an existing directory as a docker image context instead of a temporary one. For testing purposes only. docker_base_image : str or None Name of base image that can be used in **dockerfile_template**. Defaults to 'bioconda/bioconda-utils-build-env:latest' """ self.requirements = requirements self.conda_build_args = "" self.build_script_template = build_script_template self.dockerfile_template = dockerfile_template self.keep_image = keep_image self.build_image = build_image self.image_build_dir = image_build_dir self.docker_base_image = docker_base_image self.docker_temp_image = tag # find and store user info uid = os.getuid() usr = pwd.getpwuid(uid) self.user_info = dict( uid=uid, gid=usr.pw_gid, groupname=grp.getgrgid(usr.pw_gid).gr_name, username=usr.pw_name) self.container_recipe = container_recipe self.container_staging = container_staging self.host_conda_bld = get_host_conda_bld() if use_host_conda_bld: self.pkg_dir = self.host_conda_bld else: if pkg_dir is None: self.pkg_dir = tempfile.mkdtemp() else: if not os.path.exists(pkg_dir): os.makedirs(pkg_dir) self.pkg_dir = pkg_dir # Copy the conda build config files to the staging directory that is # visible in the container for i, config_file in enumerate(utils.get_conda_build_config_files()): dst_file = self._get_config_path(self.pkg_dir, i, config_file) shutil.copyfile(config_file.path, dst_file) if self.build_image: self._build_image() def _get_config_path(self, staging_prefix, i, config_file): src_basename = os.path.basename(config_file.path) dst_basename = 'conda_build_config_{}_{}_{}'.format(i, config_file.arg, src_basename) return os.path.join(staging_prefix, dst_basename) def __del__(self): self.cleanup() def _find_proxy_settings(self): res = {} for var in ('http_proxy', 'https_proxy'): values = set([ os.environ.get(var, None), os.environ.get(var.upper(), None) ]).difference([None]) if len(values) == 1: res[var] = next(iter(values)) elif len(values) > 1: raise ValueError(f"{var} and {var.upper()} have different values") return res def _build_image(self): """ Builds a new image with requirements installed. """ if self.image_build_dir is None: # Create a temporary build directory since we'll be copying the # requirements file over build_dir = tempfile.mkdtemp() else: build_dir = self.image_build_dir logger.info('DOCKER: Building image "%s" from %s', self.docker_temp_image, build_dir) with open(os.path.join(build_dir, 'requirements.txt'), 'w') as fout: if self.requirements: fout.write(open(self.requirements).read()) else: fout.write(open(pkg_resources.resource_filename( 'bioconda_utils', 'bioconda_utils-requirements.txt') ).read()) proxies = "\n".join("ENV {} {}".format(k, v) for k, v in self._find_proxy_settings()) with open(os.path.join(build_dir, "Dockerfile"), 'w') as fout: fout.write(self.dockerfile_template.format( docker_base_image=self.docker_base_image, proxies=proxies, conda_ver=conda.__version__, conda_build_ver=conda_build.__version__) ) logger.debug('Dockerfile:\n' + open(fout.name).read()) # Check if the installed version of docker supports the --network flag # (requires version >= 1.13.0) # Parse output of `docker --version` since the format of the # `docker version` command (note the missing dashes) is not consistent # between different docker versions. The --version string is the same # for docker 1.6.2 and 1.12.6 try: s = sp.check_output(["docker", "--version"]).decode() except FileNotFoundError: logger.error('DOCKER FAILED: Error checking docker version, is it installed?') raise except sp.CalledProcessError: logger.error('DOCKER FAILED: Error checking docker version.') raise p = re.compile(r"\d+\.\d+\.\d+") # three groups of at least on digit separated by dots version_string = re.search(p, s).group(0) if LooseVersion(version_string) >= LooseVersion("1.13.0"): cmd = [ 'docker', 'build', # xref #5027 '--network', 'host', '-t', self.docker_temp_image, build_dir ] else: # Network flag was added in 1.13.0, do not add it for lower versions. xref #5387 cmd = [ 'docker', 'build', '-t', self.docker_temp_image, build_dir ] try: with utils.Progress(): p = utils.run(cmd, mask=False) except sp.CalledProcessError as e: logger.error( 'DOCKER FAILED: Error building docker container %s. ', self.docker_temp_image) raise e logger.info('DOCKER: Built docker image tag=%s', self.docker_temp_image) if self.image_build_dir is None: shutil.rmtree(build_dir) return p def build_recipe(self, recipe_dir, build_args, env, noarch=False): """ Build a single recipe. Parameters ---------- recipe_dir : str Path to recipe that contains meta.yaml build_args : str Additional arguments to ``conda build``. For example --channel, --skip-existing, etc env : dict Environmental variables noarch: bool Has to be set to true if this is a noarch build Note that the binds are set up automatically to match the expectations of the build script, and will use the currently-configured self.container_staging and self.container_recipe. """ # Attach the build args to self so that it can be filled in by the # template. if not isinstance(build_args, str): raise ValueError('build_args must be str') build_args_list = [build_args] for i, config_file in enumerate(utils.get_conda_build_config_files()): dst_file = self._get_config_path(self.container_staging, i, config_file) build_args_list.extend([config_file.arg, quote(dst_file)]) self.conda_build_args = ' '.join(build_args_list) # Write build script to tempfile build_dir = os.path.realpath(tempfile.mkdtemp()) script = self.build_script_template.format( self=self, arch='noarch' if noarch else 'linux-64') with open(os.path.join(build_dir, 'build_script.bash'), 'w') as fout: fout.write(script) build_script = fout.name logger.debug('DOCKER: Container build script: \n%s', open(fout.name).read()) # Build the args for env vars. Note can also write these to tempfile # and use --env-file arg, but using -e seems clearer in debug output. env_list = [] for k, v in env.items(): env_list.append('-e') env_list.append('{0}={1}'.format(k, v)) env_list.append('-e') env_list.append('{0}={1}'.format('HOST_USER_ID', self.user_info['uid'])) cmd = [ 'docker', 'run', '-t', '--net', 'host', '--rm', '-v', '{0}:/opt/build_script.bash'.format(build_script), '-v', '{0}:{1}'.format(self.pkg_dir, self.container_staging), '-v', '{0}:{1}'.format(recipe_dir, self.container_recipe), ] cmd += env_list if self.build_image: cmd += [self.docker_temp_image] else: cmd += [self.docker_base_image] cmd += ['/bin/bash', '/opt/build_script.bash'] logger.debug('DOCKER: cmd: %s', cmd) with utils.Progress(): p = utils.run(cmd, mask=False) return p def cleanup(self): if self.build_image and not self.keep_image: cmd = ['docker', 'rmi', self.docker_temp_image] utils.run(cmd, mask=False)
en
0.77908
#!/usr/bin/env python To ensure conda packages are built in the most compatible manner, we can use a docker container. This module supports using a docker container to build conda packages in the local channel which can later be uploaded to anaconda. Note that we cannot simply bind the host's conda-bld directory to the container's conda-bld directory because during building/testing, symlinks are made to the conda-pkgs dir which is not necessarily bound. Nor should it be, if we want to retain isolation from the host when building. To solve this, we mount the host's conda-bld dir to a temporary directory in the container. Once the container successfully builds a package, the corresponding package is copied over to the temporary directory (the host's conda-bld directory) so that the built package appears on the host. In the end the workflow is: - build a custom docker container (assumed to already have conda installed) where the requirements in ``bioconda-utils/bioconda-utils_requirements.txt`` have been conda installed. - mount the host's conda-bld to a read/write temporary dir in the container (configured in the RecipeBuilder) - in the container, add this directory as a local channel so that all previously-built packages can be used as dependencies. - mount the host's recipe dir to a read-only dir in the container (configured in the RecipeBuilder) - build, mount, and run a custom script that conda-builds the mounted recipe and if successful copies the built package to the mounted host's conda-bld directory. Other notes: - Most communication with the host (conda-bld options; host's UID) is via environmental variables passed to the container. - The build script is custom generated each run, providing lots of flexibility. Most magic happens here. # ---------------------------------------------------------------------------- # BUILD_SCRIPT_TEMPLATE # ---------------------------------------------------------------------------- # # The following script is the default that will be regenerated on each call to # RecipeBuilder.build_recipe() and mounted at container run time when building # a recipe. It can be overridden by providing a different template when calling # RecipeBuilder.build_recipe(). # # It will be filled in using BUILD_SCRIPT_TEMPLATE.format(self=self), so you # can add additional attributes to the RecipeBuilder instance and have them # filled in here. # #!/bin/bash set -eo pipefail # Add the host's mounted conda-bld dir so that we can use its contents as # dependencies for building this recipe. # # Note that if the directory didn't exist on the host, then the staging area # will exist in the container but will be empty. Channels expect at least # a linux-64 and noarch directory within that directory, so we make sure it # exists before adding the channel. mkdir -p {self.container_staging}/linux-64 mkdir -p {self.container_staging}/noarch conda config --add channels file://{self.container_staging} 2> >( grep -vF "Warning: 'file://{self.container_staging}' already in 'channels' list, moving to the top" >&2 ) # The actual building... # we explicitly point to the meta.yaml, in order to keep # conda-build from building all subdirectories conda build {self.conda_build_args} {self.container_recipe}/meta.yaml 2>&1 # copy all built packages to the staging area cp `conda build {self.conda_build_args} {self.container_recipe}/meta.yaml --output` {self.container_staging}/{arch} # Ensure permissions are correct on the host. HOST_USER={self.user_info[uid]} chown $HOST_USER:$HOST_USER {self.container_staging}/{arch}/* # noqa: E501,E122: line too long, continuation line missing indentation or outdented # ---------------------------------------------------------------------------- # DOCKERFILE_TEMPLATE # ---------------------------------------------------------------------------- # # This template can be used for last-minute changes to the docker image, such # as adding proxies. # # The default image is created automatically on DockerHub using the Dockerfile # in the bioconda-utils repo. FROM {docker_base_image} {proxies} RUN /opt/conda/bin/conda install -y conda={conda_ver} conda-build={conda_build_ver} # noqa: E122 continuation line missing indentation or outdented Identifies the conda-bld directory on the host. Assumes that conda-build is installed. # v0.16.2: this used to have a side effect, calling conda build purge # hopefully, it's not actually needed. Class to handle building a custom docker container that can be used for building conda recipes. Parameters ---------- tag : str Tag to be used for the custom-build docker container. Mostly for debugging purposes when you need to inspect the container. container_recipe : str Directory to which the host's recipe will be exported. Will be read-only. container_staging : str Directory to which the host's conda-bld dir will be mounted so that the container can use previously-built packages as dependencies. Upon successful building container-built packages will be copied over. Mounted as read-write. requirements : None or str Path to a "requirements.txt" file which will be installed with conda in a newly-created container. If None, then use the default installed with bioconda_utils. build_script_template : str Template that will be filled in with .format(self=self) and that will be run in the container each time build_recipe() is called. If not specified, uses docker_utils.BUILD_SCRIPT_TEMPLATE. dockerfile_template : str Template that will be filled in with .format(self=self) and that will be used to build a custom image. Uses docker_utils.DOCKERFILE_TEMPLATE by default. use_host_conda_bld : bool If True, then use the host's conda-bld directory. This will export the host's existing conda-bld directory to the docker container, and any recipes successfully built by the container will be added here. Otherwise, use **pkg_dir** as a common host directory used across multiple runs of this RecipeBuilder object. pkg_dir : str or None Specify where packages should appear on the host. If **pkg_dir** is None, then a temporary directory will be created once for each `RecipeBuilder` instance and that directory will be used for each call to `RecipeBuilder.build_recipe()`. This allows subsequent recipes built by the container to see previous built recipes without polluting the host's conda-bld directory. If **pkg_dir** is a string, then it will be created if needed and this directory will be used store all built packages on the host instead of the temp dir. If the above argument **use_host_conda_bld** is `True`, then the value of **pkg_dir** will be ignored and the host's conda-bld directory will be used. In all cases, **pkg_dir** will be mounted to **container_staging** in the container. build_image : bool Build a local layer on top of the **docker_base_image** layer using **dockerfile_template**. This can be used to adjust the versions of conda and conda-build in the build container. keep_image : bool By default, the built docker image will be removed when done, freeing up storage space. Set ``keep_image=True`` to disable this behavior. image_build_dir : str or None If not None, use an existing directory as a docker image context instead of a temporary one. For testing purposes only. docker_base_image : str or None Name of base image that can be used in **dockerfile_template**. Defaults to 'bioconda/bioconda-utils-build-env:latest' # find and store user info # Copy the conda build config files to the staging directory that is # visible in the container Builds a new image with requirements installed. # Create a temporary build directory since we'll be copying the # requirements file over # Check if the installed version of docker supports the --network flag # (requires version >= 1.13.0) # Parse output of `docker --version` since the format of the # `docker version` command (note the missing dashes) is not consistent # between different docker versions. The --version string is the same # for docker 1.6.2 and 1.12.6 # three groups of at least on digit separated by dots # xref #5027 # Network flag was added in 1.13.0, do not add it for lower versions. xref #5387 Build a single recipe. Parameters ---------- recipe_dir : str Path to recipe that contains meta.yaml build_args : str Additional arguments to ``conda build``. For example --channel, --skip-existing, etc env : dict Environmental variables noarch: bool Has to be set to true if this is a noarch build Note that the binds are set up automatically to match the expectations of the build script, and will use the currently-configured self.container_staging and self.container_recipe. # Attach the build args to self so that it can be filled in by the # template. # Write build script to tempfile # Build the args for env vars. Note can also write these to tempfile # and use --env-file arg, but using -e seems clearer in debug output.
2.419465
2
examples/schedulers/sync.py
sasirajpuvvada/apscheduler
4,294
6625757
<gh_stars>1000+ import logging from apscheduler.schedulers.sync import Scheduler from apscheduler.triggers.interval import IntervalTrigger from apscheduler.workers.sync import Worker def say_hello(): print('Hello!') logging.basicConfig(level=logging.DEBUG) try: with Scheduler() as scheduler, Worker(scheduler.data_store, portal=scheduler.portal): scheduler.add_schedule(say_hello, IntervalTrigger(seconds=1)) scheduler.wait_until_stopped() except (KeyboardInterrupt, SystemExit): pass
import logging from apscheduler.schedulers.sync import Scheduler from apscheduler.triggers.interval import IntervalTrigger from apscheduler.workers.sync import Worker def say_hello(): print('Hello!') logging.basicConfig(level=logging.DEBUG) try: with Scheduler() as scheduler, Worker(scheduler.data_store, portal=scheduler.portal): scheduler.add_schedule(say_hello, IntervalTrigger(seconds=1)) scheduler.wait_until_stopped() except (KeyboardInterrupt, SystemExit): pass
none
1
2.335916
2
adblocker.py
iam-shanmukha/adlocker
3
6625758
<filename>adblocker.py #!/usr/bin/python import os,sys, platform import datetime hosts = ["https://adaway.org/hosts.txt", "https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts"] WINDOWS_ETC = "c:\\Windows\\System32\\Drivers\\etc\\" WINDOWS_HOSTS = "c:\\Windows\\System32\\Drivers\\etc\\hosts" count = 1 print(r''' _ _ _ _ __ _ __| | |__ | | ___ ___| | _____ _ __ _ __ _ _ / _` |/ _` | '_ \| |/ _ \ / __| |/ / _ \ '__| | '_ \| | | | | (_| | (_| | |_) | | (_) | (__| < __/ | _ | |_) | |_| | \__,_|\__,_|_.__/|_|\___/ \___|_|\_\___|_| (_) | .__/ \__, | |_| |___/ @gitub.com/iam-shanmukha ''') basename = "hosts_" suffix = datetime.datetime.now().strftime("%d%m%y_%H%M%S") filename = "_".join([basename, suffix]) def execute(): global count os.system(cmd) print(f'completed {count}/{len(hosts)}') count = count+1 if platform.system() == 'Linux': print("Starting Script on Linux") try: if os.geteuid() !=0: raise PermissionError os.system(r"sudo cp /etc/hosts /etc/{}".format(filename)) print("Backup success \nBackup file --> /etc/{}".format(filename)) open('/etc/hosts', 'w').close() for i in hosts: cmd = f'sudo curl -s {i} >> /etc/hosts' execute() print("Successfully Blocked Ad's") sys.exit() except PermissionError: print("Please run as root \nsudo python adblocker.py") sys.exit() elif platform.system() == 'Windows': print("starting Script on Windows") try: os.system(f'copy {WINDOWS_HOSTS} {WINDOWS_ETC}{filename} /y') print(f'Backup success \nBackup file --> {WINDOWS_ETC}{filename}') open(f'{WINDOWS_HOSTS}','w').close() for i in hosts: cmd = f'curl -s {i} >> {WINDOWS_HOSTS}' execute() print("Successfully Blocked AD's") sys.exit() except PermissionError: print("Abort! Please run as Administrator") sys.exit() else: print("Sorry! Platform Not Supported")
<filename>adblocker.py #!/usr/bin/python import os,sys, platform import datetime hosts = ["https://adaway.org/hosts.txt", "https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts"] WINDOWS_ETC = "c:\\Windows\\System32\\Drivers\\etc\\" WINDOWS_HOSTS = "c:\\Windows\\System32\\Drivers\\etc\\hosts" count = 1 print(r''' _ _ _ _ __ _ __| | |__ | | ___ ___| | _____ _ __ _ __ _ _ / _` |/ _` | '_ \| |/ _ \ / __| |/ / _ \ '__| | '_ \| | | | | (_| | (_| | |_) | | (_) | (__| < __/ | _ | |_) | |_| | \__,_|\__,_|_.__/|_|\___/ \___|_|\_\___|_| (_) | .__/ \__, | |_| |___/ @gitub.com/iam-shanmukha ''') basename = "hosts_" suffix = datetime.datetime.now().strftime("%d%m%y_%H%M%S") filename = "_".join([basename, suffix]) def execute(): global count os.system(cmd) print(f'completed {count}/{len(hosts)}') count = count+1 if platform.system() == 'Linux': print("Starting Script on Linux") try: if os.geteuid() !=0: raise PermissionError os.system(r"sudo cp /etc/hosts /etc/{}".format(filename)) print("Backup success \nBackup file --> /etc/{}".format(filename)) open('/etc/hosts', 'w').close() for i in hosts: cmd = f'sudo curl -s {i} >> /etc/hosts' execute() print("Successfully Blocked Ad's") sys.exit() except PermissionError: print("Please run as root \nsudo python adblocker.py") sys.exit() elif platform.system() == 'Windows': print("starting Script on Windows") try: os.system(f'copy {WINDOWS_HOSTS} {WINDOWS_ETC}{filename} /y') print(f'Backup success \nBackup file --> {WINDOWS_ETC}{filename}') open(f'{WINDOWS_HOSTS}','w').close() for i in hosts: cmd = f'curl -s {i} >> {WINDOWS_HOSTS}' execute() print("Successfully Blocked AD's") sys.exit() except PermissionError: print("Abort! Please run as Administrator") sys.exit() else: print("Sorry! Platform Not Supported")
en
0.310139
#!/usr/bin/python _ _ _ _ __ _ __| | |__ | | ___ ___| | _____ _ __ _ __ _ _ / _` |/ _` | '_ \| |/ _ \ / __| |/ / _ \ '__| | '_ \| | | | | (_| | (_| | |_) | | (_) | (__| < __/ | _ | |_) | |_| | \__,_|\__,_|_.__/|_|\___/ \___|_|\_\___|_| (_) | .__/ \__, | |_| |___/ @gitub.com/iam-shanmukha
2.382369
2
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_infra_dumper_cfg.py
tkamata-test/ydk-py
0
6625759
<filename>cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_infra_dumper_cfg.py """ Cisco_IOS_XR_infra_dumper_cfg This module contains a collection of YANG definitions for Cisco IOS\-XR infra\-dumper package configuration. This module contains definitions for the following management objects\: exception\: Core dump configuration commands Copyright (c) 2013\-2016 by Cisco Systems, Inc. All rights reserved. """ import re import collections from enum import Enum from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict from ydk.errors import YPYError, YPYModelError class Exception(object): """ Core dump configuration commands .. attribute:: choice1 Preference of the dump location **type**\: :py:class:`Choice1 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_infra_dumper_cfg.Exception.Choice1>` .. attribute:: choice2 Preference of the dump location **type**\: :py:class:`Choice2 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_infra_dumper_cfg.Exception.Choice2>` .. attribute:: choice3 Preference of the dump location **type**\: :py:class:`Choice3 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_infra_dumper_cfg.Exception.Choice3>` .. attribute:: kernel_debugger Enable kernel debugger **type**\: :py:class:`Empty<ydk.types.Empty>` .. attribute:: packet_memory Specify 'true' to dump packet memory for all process, 'false' to disable dump of packet memory **type**\: bool .. attribute:: sparse Specify 'true' to enable sparse core dump, 'false' to disable sparse core dump **type**\: bool .. attribute:: sparse_size Switch to sparse core dump at this size **type**\: int **range:** 1..4095 """ _prefix = 'infra-dumper-cfg' _revision = '2015-11-09' def __init__(self): self.choice1 = Exception.Choice1() self.choice1.parent = self self.choice2 = Exception.Choice2() self.choice2.parent = self self.choice3 = Exception.Choice3() self.choice3.parent = self self.kernel_debugger = None self.packet_memory = None self.sparse = None self.sparse_size = None class Choice1(object): """ Preference of the dump location .. attribute:: compress Specify 'true' to compress core files dumped on this path, 'false' to not compress **type**\: bool .. attribute:: file_path Protocol and directory **type**\: str .. attribute:: filename Dump filename **type**\: str .. attribute:: higher_limit Higher limit. This is required if Filename is specified **type**\: int **range:** 5..64 .. attribute:: lower_limit Lower limit. This is required if Filename is specified **type**\: int **range:** 0..4 """ _prefix = 'infra-dumper-cfg' _revision = '2015-11-09' def __init__(self): self.parent = None self.compress = None self.file_path = None self.filename = None self.higher_limit = None self.lower_limit = None @property def _common_path(self): return '/Cisco-IOS-XR-infra-dumper-cfg:exception/Cisco-IOS-XR-infra-dumper-cfg:choice1' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' return True def _has_data(self): if not self.is_config(): return False if self.compress is not None: return True if self.file_path is not None: return True if self.filename is not None: return True if self.higher_limit is not None: return True if self.lower_limit is not None: return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_infra_dumper_cfg as meta return meta._meta_table['Exception.Choice1']['meta_info'] class Choice3(object): """ Preference of the dump location .. attribute:: compress Specify 'true' to compress core files dumped on this path, 'false' to not compress **type**\: bool .. attribute:: file_path Protocol and directory **type**\: str .. attribute:: filename Dump filename **type**\: str .. attribute:: higher_limit Higher limit. This is required if Filename is specified **type**\: int **range:** 5..64 .. attribute:: lower_limit Lower limit. This is required if Filename is specified **type**\: int **range:** 0..4 """ _prefix = 'infra-dumper-cfg' _revision = '2015-11-09' def __init__(self): self.parent = None self.compress = None self.file_path = None self.filename = None self.higher_limit = None self.lower_limit = None @property def _common_path(self): return '/Cisco-IOS-XR-infra-dumper-cfg:exception/Cisco-IOS-XR-infra-dumper-cfg:choice3' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' return True def _has_data(self): if not self.is_config(): return False if self.compress is not None: return True if self.file_path is not None: return True if self.filename is not None: return True if self.higher_limit is not None: return True if self.lower_limit is not None: return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_infra_dumper_cfg as meta return meta._meta_table['Exception.Choice3']['meta_info'] class Choice2(object): """ Preference of the dump location .. attribute:: compress Specify 'true' to compress core files dumped on this path, 'false' to not compress **type**\: bool .. attribute:: file_path Protocol and directory **type**\: str .. attribute:: filename Dump filename **type**\: str .. attribute:: higher_limit Higher limit. This is required if Filename is specified **type**\: int **range:** 5..64 .. attribute:: lower_limit Lower limit. This is required if Filename is specified **type**\: int **range:** 0..4 """ _prefix = 'infra-dumper-cfg' _revision = '2015-11-09' def __init__(self): self.parent = None self.compress = None self.file_path = None self.filename = None self.higher_limit = None self.lower_limit = None @property def _common_path(self): return '/Cisco-IOS-XR-infra-dumper-cfg:exception/Cisco-IOS-XR-infra-dumper-cfg:choice2' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' return True def _has_data(self): if not self.is_config(): return False if self.compress is not None: return True if self.file_path is not None: return True if self.filename is not None: return True if self.higher_limit is not None: return True if self.lower_limit is not None: return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_infra_dumper_cfg as meta return meta._meta_table['Exception.Choice2']['meta_info'] @property def _common_path(self): return '/Cisco-IOS-XR-infra-dumper-cfg:exception' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' return True def _has_data(self): if not self.is_config(): return False if self.choice1 is not None and self.choice1._has_data(): return True if self.choice2 is not None and self.choice2._has_data(): return True if self.choice3 is not None and self.choice3._has_data(): return True if self.kernel_debugger is not None: return True if self.packet_memory is not None: return True if self.sparse is not None: return True if self.sparse_size is not None: return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_infra_dumper_cfg as meta return meta._meta_table['Exception']['meta_info']
<filename>cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_infra_dumper_cfg.py """ Cisco_IOS_XR_infra_dumper_cfg This module contains a collection of YANG definitions for Cisco IOS\-XR infra\-dumper package configuration. This module contains definitions for the following management objects\: exception\: Core dump configuration commands Copyright (c) 2013\-2016 by Cisco Systems, Inc. All rights reserved. """ import re import collections from enum import Enum from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict from ydk.errors import YPYError, YPYModelError class Exception(object): """ Core dump configuration commands .. attribute:: choice1 Preference of the dump location **type**\: :py:class:`Choice1 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_infra_dumper_cfg.Exception.Choice1>` .. attribute:: choice2 Preference of the dump location **type**\: :py:class:`Choice2 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_infra_dumper_cfg.Exception.Choice2>` .. attribute:: choice3 Preference of the dump location **type**\: :py:class:`Choice3 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_infra_dumper_cfg.Exception.Choice3>` .. attribute:: kernel_debugger Enable kernel debugger **type**\: :py:class:`Empty<ydk.types.Empty>` .. attribute:: packet_memory Specify 'true' to dump packet memory for all process, 'false' to disable dump of packet memory **type**\: bool .. attribute:: sparse Specify 'true' to enable sparse core dump, 'false' to disable sparse core dump **type**\: bool .. attribute:: sparse_size Switch to sparse core dump at this size **type**\: int **range:** 1..4095 """ _prefix = 'infra-dumper-cfg' _revision = '2015-11-09' def __init__(self): self.choice1 = Exception.Choice1() self.choice1.parent = self self.choice2 = Exception.Choice2() self.choice2.parent = self self.choice3 = Exception.Choice3() self.choice3.parent = self self.kernel_debugger = None self.packet_memory = None self.sparse = None self.sparse_size = None class Choice1(object): """ Preference of the dump location .. attribute:: compress Specify 'true' to compress core files dumped on this path, 'false' to not compress **type**\: bool .. attribute:: file_path Protocol and directory **type**\: str .. attribute:: filename Dump filename **type**\: str .. attribute:: higher_limit Higher limit. This is required if Filename is specified **type**\: int **range:** 5..64 .. attribute:: lower_limit Lower limit. This is required if Filename is specified **type**\: int **range:** 0..4 """ _prefix = 'infra-dumper-cfg' _revision = '2015-11-09' def __init__(self): self.parent = None self.compress = None self.file_path = None self.filename = None self.higher_limit = None self.lower_limit = None @property def _common_path(self): return '/Cisco-IOS-XR-infra-dumper-cfg:exception/Cisco-IOS-XR-infra-dumper-cfg:choice1' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' return True def _has_data(self): if not self.is_config(): return False if self.compress is not None: return True if self.file_path is not None: return True if self.filename is not None: return True if self.higher_limit is not None: return True if self.lower_limit is not None: return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_infra_dumper_cfg as meta return meta._meta_table['Exception.Choice1']['meta_info'] class Choice3(object): """ Preference of the dump location .. attribute:: compress Specify 'true' to compress core files dumped on this path, 'false' to not compress **type**\: bool .. attribute:: file_path Protocol and directory **type**\: str .. attribute:: filename Dump filename **type**\: str .. attribute:: higher_limit Higher limit. This is required if Filename is specified **type**\: int **range:** 5..64 .. attribute:: lower_limit Lower limit. This is required if Filename is specified **type**\: int **range:** 0..4 """ _prefix = 'infra-dumper-cfg' _revision = '2015-11-09' def __init__(self): self.parent = None self.compress = None self.file_path = None self.filename = None self.higher_limit = None self.lower_limit = None @property def _common_path(self): return '/Cisco-IOS-XR-infra-dumper-cfg:exception/Cisco-IOS-XR-infra-dumper-cfg:choice3' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' return True def _has_data(self): if not self.is_config(): return False if self.compress is not None: return True if self.file_path is not None: return True if self.filename is not None: return True if self.higher_limit is not None: return True if self.lower_limit is not None: return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_infra_dumper_cfg as meta return meta._meta_table['Exception.Choice3']['meta_info'] class Choice2(object): """ Preference of the dump location .. attribute:: compress Specify 'true' to compress core files dumped on this path, 'false' to not compress **type**\: bool .. attribute:: file_path Protocol and directory **type**\: str .. attribute:: filename Dump filename **type**\: str .. attribute:: higher_limit Higher limit. This is required if Filename is specified **type**\: int **range:** 5..64 .. attribute:: lower_limit Lower limit. This is required if Filename is specified **type**\: int **range:** 0..4 """ _prefix = 'infra-dumper-cfg' _revision = '2015-11-09' def __init__(self): self.parent = None self.compress = None self.file_path = None self.filename = None self.higher_limit = None self.lower_limit = None @property def _common_path(self): return '/Cisco-IOS-XR-infra-dumper-cfg:exception/Cisco-IOS-XR-infra-dumper-cfg:choice2' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' return True def _has_data(self): if not self.is_config(): return False if self.compress is not None: return True if self.file_path is not None: return True if self.filename is not None: return True if self.higher_limit is not None: return True if self.lower_limit is not None: return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_infra_dumper_cfg as meta return meta._meta_table['Exception.Choice2']['meta_info'] @property def _common_path(self): return '/Cisco-IOS-XR-infra-dumper-cfg:exception' def is_config(self): ''' Returns True if this instance represents config data else returns False ''' return True def _has_data(self): if not self.is_config(): return False if self.choice1 is not None and self.choice1._has_data(): return True if self.choice2 is not None and self.choice2._has_data(): return True if self.choice3 is not None and self.choice3._has_data(): return True if self.kernel_debugger is not None: return True if self.packet_memory is not None: return True if self.sparse is not None: return True if self.sparse_size is not None: return True return False @staticmethod def _meta_info(): from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_infra_dumper_cfg as meta return meta._meta_table['Exception']['meta_info']
en
0.405607
Cisco_IOS_XR_infra_dumper_cfg This module contains a collection of YANG definitions for Cisco IOS\-XR infra\-dumper package configuration. This module contains definitions for the following management objects\: exception\: Core dump configuration commands Copyright (c) 2013\-2016 by Cisco Systems, Inc. All rights reserved. Core dump configuration commands .. attribute:: choice1 Preference of the dump location **type**\: :py:class:`Choice1 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_infra_dumper_cfg.Exception.Choice1>` .. attribute:: choice2 Preference of the dump location **type**\: :py:class:`Choice2 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_infra_dumper_cfg.Exception.Choice2>` .. attribute:: choice3 Preference of the dump location **type**\: :py:class:`Choice3 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_infra_dumper_cfg.Exception.Choice3>` .. attribute:: kernel_debugger Enable kernel debugger **type**\: :py:class:`Empty<ydk.types.Empty>` .. attribute:: packet_memory Specify 'true' to dump packet memory for all process, 'false' to disable dump of packet memory **type**\: bool .. attribute:: sparse Specify 'true' to enable sparse core dump, 'false' to disable sparse core dump **type**\: bool .. attribute:: sparse_size Switch to sparse core dump at this size **type**\: int **range:** 1..4095 Preference of the dump location .. attribute:: compress Specify 'true' to compress core files dumped on this path, 'false' to not compress **type**\: bool .. attribute:: file_path Protocol and directory **type**\: str .. attribute:: filename Dump filename **type**\: str .. attribute:: higher_limit Higher limit. This is required if Filename is specified **type**\: int **range:** 5..64 .. attribute:: lower_limit Lower limit. This is required if Filename is specified **type**\: int **range:** 0..4 Returns True if this instance represents config data else returns False Preference of the dump location .. attribute:: compress Specify 'true' to compress core files dumped on this path, 'false' to not compress **type**\: bool .. attribute:: file_path Protocol and directory **type**\: str .. attribute:: filename Dump filename **type**\: str .. attribute:: higher_limit Higher limit. This is required if Filename is specified **type**\: int **range:** 5..64 .. attribute:: lower_limit Lower limit. This is required if Filename is specified **type**\: int **range:** 0..4 Returns True if this instance represents config data else returns False Preference of the dump location .. attribute:: compress Specify 'true' to compress core files dumped on this path, 'false' to not compress **type**\: bool .. attribute:: file_path Protocol and directory **type**\: str .. attribute:: filename Dump filename **type**\: str .. attribute:: higher_limit Higher limit. This is required if Filename is specified **type**\: int **range:** 5..64 .. attribute:: lower_limit Lower limit. This is required if Filename is specified **type**\: int **range:** 0..4 Returns True if this instance represents config data else returns False Returns True if this instance represents config data else returns False
1.858802
2
signalProcessing/backscatter_expt_040716.py
macoskey/backscatter
0
6625760
# <NAME>, U of Michigan, I-GUTL, April 2017 # backscatter analysis of signals from 250 kHz 256-element array # Objective: observe bubble cloud migration on high-speed camera and compare to # ACE peak arrival (and edge detection) signal. import numpy as np import scipi.io as sio import matplotlib.pyplot as plt class array(): def __init__(self): coords = sio.loadmat('256x2cm_Hemispherical_Array_CAD_Coordinates.mat') X = coords['XCAD'][7:] Y = coords['YCAD'][7:] self.z = coords['ZCAD'][7:] t1 = np.arctan2(Y,X)-0.75*pi rr1 = (X**2+Y**2)**0.5 self.x = rr1*np.cos(t1) self.y = rr1*np.sin(t1) self.z = rr1*np.tan(t1) class bSignals(): def FTsig(self,signal,interval) insig = signal(interval) ft = np.fftshift(np.fft(insig)) return ft fig = plt.figure() plt.plot(ft) plt.show()
# <NAME>, U of Michigan, I-GUTL, April 2017 # backscatter analysis of signals from 250 kHz 256-element array # Objective: observe bubble cloud migration on high-speed camera and compare to # ACE peak arrival (and edge detection) signal. import numpy as np import scipi.io as sio import matplotlib.pyplot as plt class array(): def __init__(self): coords = sio.loadmat('256x2cm_Hemispherical_Array_CAD_Coordinates.mat') X = coords['XCAD'][7:] Y = coords['YCAD'][7:] self.z = coords['ZCAD'][7:] t1 = np.arctan2(Y,X)-0.75*pi rr1 = (X**2+Y**2)**0.5 self.x = rr1*np.cos(t1) self.y = rr1*np.sin(t1) self.z = rr1*np.tan(t1) class bSignals(): def FTsig(self,signal,interval) insig = signal(interval) ft = np.fftshift(np.fft(insig)) return ft fig = plt.figure() plt.plot(ft) plt.show()
en
0.837807
# <NAME>, U of Michigan, I-GUTL, April 2017 # backscatter analysis of signals from 250 kHz 256-element array # Objective: observe bubble cloud migration on high-speed camera and compare to # ACE peak arrival (and edge detection) signal.
2.350068
2
SNCKPE19/BUDDYNIM.py
Chhekur/codechef-solutions
1
6625761
<gh_stars>1-10 for _ in range(int(input())): n,m = [int(x) for x in input().split()] a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] e,f = [],[] c,d = 0,0 n1,n2 = 0,0 for i in a: if(i > 0): e.append(i) c += 1 if(i == 1):n1 += 1 for i in b: if(i > 0): f.append(i) d += 1 if(i == 1):n2 += 1 e.sort() f.sort() if(c == 0 and d == 0):print('Bob') elif(len(e) != len(f)):print('Alice') elif(len(e) == len(f) and e == f):print('Bob') else:print('Alice')
for _ in range(int(input())): n,m = [int(x) for x in input().split()] a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] e,f = [],[] c,d = 0,0 n1,n2 = 0,0 for i in a: if(i > 0): e.append(i) c += 1 if(i == 1):n1 += 1 for i in b: if(i > 0): f.append(i) d += 1 if(i == 1):n2 += 1 e.sort() f.sort() if(c == 0 and d == 0):print('Bob') elif(len(e) != len(f)):print('Alice') elif(len(e) == len(f) and e == f):print('Bob') else:print('Alice')
none
1
2.880741
3
setup.py
ZYunH/Convert-Into-Command
5
6625762
#!/usr/bin/env python import os import sys from setuptools import setup, find_packages # 'setup.py publish' shortcut. if sys.argv[-1] == 'publish': os.system('pip3 install twine') os.system('pip3 install wheel') os.system('python3 setup.py sdist bdist_wheel') os.system('twine upload dist/*') os.system('rm -rf build dist .egg zmail.egg-info') sys.exit() PROJECT_NAME = 'python-script-converter' MODULE_NAME = 'psc' setup( name='python-script-converter', version='1.2', author='ZhangYunHao', author_email='<EMAIL>', description='This is a tiny tool used to convert a python script to a executable file(only for Mac and Linux).', long_description='This is a tiny tool used to convert a python script to a executable file(only for Mac and Linux)', keywords='python tool converter', url='https://github.com/ZYunH/Python-script-converter', license="MIT Licence", platforms='Mac Linux', packages=find_packages(), include_package_data=True, entry_points={ 'console_scripts': [ 'psc = psc.__main__:main' ] } )
#!/usr/bin/env python import os import sys from setuptools import setup, find_packages # 'setup.py publish' shortcut. if sys.argv[-1] == 'publish': os.system('pip3 install twine') os.system('pip3 install wheel') os.system('python3 setup.py sdist bdist_wheel') os.system('twine upload dist/*') os.system('rm -rf build dist .egg zmail.egg-info') sys.exit() PROJECT_NAME = 'python-script-converter' MODULE_NAME = 'psc' setup( name='python-script-converter', version='1.2', author='ZhangYunHao', author_email='<EMAIL>', description='This is a tiny tool used to convert a python script to a executable file(only for Mac and Linux).', long_description='This is a tiny tool used to convert a python script to a executable file(only for Mac and Linux)', keywords='python tool converter', url='https://github.com/ZYunH/Python-script-converter', license="MIT Licence", platforms='Mac Linux', packages=find_packages(), include_package_data=True, entry_points={ 'console_scripts': [ 'psc = psc.__main__:main' ] } )
en
0.151061
#!/usr/bin/env python # 'setup.py publish' shortcut.
2.17891
2
model.py
lmm6895071/leo
0
6625763
# Copyright 2018 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Code defining LEO inner loop. See "Meta-Learning with Latent Embedding Optimization" by Rusu et al. (https://arxiv.org/pdf/1807.05960.pdf). """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from six.moves import range from six.moves import zip import sonnet as snt import tensorflow as tf import tensorflow_probability as tfp import data as data_module def get_orthogonality_regularizer(orthogonality_penalty_weight): """Returns the orthogonality regularizer.""" def orthogonality(weight): """Calculates the layer-wise penalty encouraging orthogonality.""" with tf.name_scope(None, "orthogonality", [weight]) as name: w2 = tf.matmul(weight, weight, transpose_b=True) wn = tf.norm(weight, ord=2, axis=1, keepdims=True) + 1e-32 correlation_matrix = w2 / tf.matmul(wn, wn, transpose_b=True) matrix_size = correlation_matrix.get_shape().as_list()[0] base_dtype = weight.dtype.base_dtype identity = tf.eye(matrix_size, dtype=base_dtype) weight_corr = tf.reduce_mean( tf.squared_difference(correlation_matrix, identity)) return tf.multiply( tf.cast(orthogonality_penalty_weight, base_dtype), weight_corr, name=name) return orthogonality class LEO(snt.AbstractModule): """Sonnet module implementing the inner loop of LEO.""" def __init__(self, config=None, use_64bits_dtype=True, name="leo"): super(LEO, self).__init__(name=name) self._float_dtype = tf.float64 if use_64bits_dtype else tf.float32 self._int_dtype = tf.int64 if use_64bits_dtype else tf.int32 self._inner_unroll_length = config["inner_unroll_length"] self._finetuning_unroll_length = config["finetuning_unroll_length"] self._inner_lr_init = config["inner_lr_init"] self._finetuning_lr_init = config["finetuning_lr_init"] self._num_latents = config["num_latents"] self._dropout_rate = config["dropout_rate"] self._kl_weight = config["kl_weight"] # beta self._encoder_penalty_weight = config["encoder_penalty_weight"] # gamma self._l2_penalty_weight = config["l2_penalty_weight"] # lambda_1 # lambda_2 self._orthogonality_penalty_weight = config["orthogonality_penalty_weight"] assert self._inner_unroll_length > 0, ("Positive unroll length is necessary" " to create the graph") def _build(self, data, is_meta_training=True): """Connects the LEO module to the graph, creating the variables. Args: data: A data_module.ProblemInstance constaining Tensors with the following shapes: - tr_input: (N, K, dim) - tr_output: (N, K, 1) - tr_info: (N, K) - val_input: (N, K_valid, dim) - val_output: (N, K_valid, 1) - val_info: (N, K_valid) where N is the number of classes (as in N-way) and K and the and K_valid are numbers of training and validation examples within a problem instance correspondingly (as in K-shot), and dim is the dimensionality of the embedding. is_meta_training: A boolean describing whether we run in the training mode. Returns: Tensor with the inner validation loss of LEO (include both adaptation in the latent space and finetuning). """ if isinstance(data, list): data = data_module.ProblemInstance(*data) self.is_meta_training = is_meta_training self.save_problem_instance_stats(data.tr_input) latents, kl = self.forward_encoder(data) tr_loss, adapted_classifier_weights, encoder_penalty = self.leo_inner_loop( data, latents) val_loss, val_accuracy = self.finetuning_inner_loop( data, tr_loss, adapted_classifier_weights) val_loss += self._kl_weight * kl val_loss += self._encoder_penalty_weight * encoder_penalty # The l2 regularization is is already added to the graph when constructing # the snt.Linear modules. We pass the orthogonality regularizer separately, # because it is not used in self.grads_and_vars. regularization_penalty = ( self._l2_regularization + self._decoder_orthogonality_reg) batch_val_loss = tf.reduce_mean(val_loss) batch_val_accuracy = tf.reduce_mean(val_accuracy) return batch_val_loss + regularization_penalty, batch_val_accuracy @snt.reuse_variables def leo_inner_loop(self, data, latents): with tf.variable_scope("leo_inner"): inner_lr = tf.get_variable( "lr", [1, 1, self._num_latents], dtype=self._float_dtype, initializer=tf.constant_initializer(self._inner_lr_init)) starting_latents = latents loss, _ = self.forward_decoder(data, latents) for _ in range(self._inner_unroll_length): loss_grad = tf.gradients(loss, latents) # dLtrain/dz latents -= inner_lr * loss_grad[0] loss, classifier_weights = self.forward_decoder(data, latents) if self.is_meta_training: encoder_penalty = tf.losses.mean_squared_error( labels=tf.stop_gradient(latents), predictions=starting_latents) encoder_penalty = tf.cast(encoder_penalty, self._float_dtype) else: encoder_penalty = tf.constant(0., self._float_dtype) return loss, classifier_weights, encoder_penalty @snt.reuse_variables def finetuning_inner_loop(self, data, leo_loss, classifier_weights): tr_loss = leo_loss with tf.variable_scope("finetuning"): finetuning_lr = tf.get_variable( "lr", [1, 1, self.embedding_dim], dtype=self._float_dtype, initializer=tf.constant_initializer(self._finetuning_lr_init)) for _ in range(self._finetuning_unroll_length): loss_grad = tf.gradients(tr_loss, classifier_weights) classifier_weights -= finetuning_lr * loss_grad[0] tr_loss, _ = self.calculate_inner_loss(data.tr_input, data.tr_output, classifier_weights) val_loss, val_accuracy = self.calculate_inner_loss( data.val_input, data.val_output, classifier_weights) return val_loss, val_accuracy @snt.reuse_variables def forward_encoder(self, data): encoder_outputs = self.encoder(data.tr_input) relation_network_outputs = self.relation_network(encoder_outputs) latent_dist_params = self.average_codes_per_class(relation_network_outputs) latents, kl = self.possibly_sample(latent_dist_params) return latents, kl @snt.reuse_variables def forward_decoder(self, data, latents): weights_dist_params = self.decoder(latents) # Default to glorot_initialization and not stddev=1. fan_in = self.embedding_dim.value fan_out = self.num_classes.value stddev_offset = np.sqrt(2. / (fan_out + fan_in)) classifier_weights, _ = self.possibly_sample(weights_dist_params, stddev_offset=stddev_offset) tr_loss, _ = self.calculate_inner_loss(data.tr_input, data.tr_output, classifier_weights) return tr_loss, classifier_weights @snt.reuse_variables def encoder(self, inputs): with tf.variable_scope("encoder"): after_dropout = tf.nn.dropout(inputs, keep_prob=self.dropout_rate) regularizer = tf.contrib.layers.l2_regularizer(self._l2_penalty_weight) initializer = tf.initializers.glorot_uniform(dtype=self._float_dtype) encoder_module = snt.Linear( self._num_latents, use_bias=False, regularizers={"w": regularizer}, initializers={"w": initializer}, ) outputs = snt.BatchApply(encoder_module)(after_dropout) return outputs @snt.reuse_variables def relation_network(self, inputs): with tf.variable_scope("relation_network"): regularizer = tf.contrib.layers.l2_regularizer(self._l2_penalty_weight) initializer = tf.initializers.glorot_uniform(dtype=self._float_dtype) relation_network_module = snt.nets.MLP( [2 * self._num_latents] * 3, use_bias=False, regularizers={"w": regularizer}, initializers={"w": initializer}, ) total_num_examples = self.num_examples_per_class*self.num_classes inputs = tf.reshape(inputs, [total_num_examples, self._num_latents]) left = tf.tile(tf.expand_dims(inputs, 1), [1, total_num_examples, 1]) right = tf.tile(tf.expand_dims(inputs, 0), [total_num_examples, 1, 1]) concat_codes = tf.concat([left, right], axis=-1) outputs = snt.BatchApply(relation_network_module)(concat_codes) outputs = tf.reduce_mean(outputs, axis=1) # 2 * latents, because we are returning means and variances of a Gaussian outputs = tf.reshape(outputs, [self.num_classes, self.num_examples_per_class, 2 * self._num_latents]) return outputs @snt.reuse_variables def decoder(self, inputs): with tf.variable_scope("decoder"): l2_regularizer = tf.contrib.layers.l2_regularizer(self._l2_penalty_weight) orthogonality_reg = get_orthogonality_regularizer( self._orthogonality_penalty_weight) initializer = tf.initializers.glorot_uniform(dtype=self._float_dtype) # 2 * embedding_dim, because we are returning means and variances decoder_module = snt.Linear( 2 * self.embedding_dim, use_bias=False, regularizers={"w": l2_regularizer}, initializers={"w": initializer}, ) outputs = snt.BatchApply(decoder_module)(inputs) self._orthogonality_reg = orthogonality_reg(decoder_module.w) return outputs def average_codes_per_class(self, codes): codes = tf.reduce_mean(codes, axis=1, keep_dims=True) # K dimension # Keep the shape (N, K, *) codes = tf.tile(codes, [1, self.num_examples_per_class, 1]) return codes def possibly_sample(self, distribution_params, stddev_offset=0.): means, unnormalized_stddev = tf.split(distribution_params, 2, axis=-1) stddev = tf.exp(unnormalized_stddev) stddev -= (1. - stddev_offset) stddev = tf.maximum(stddev, 1e-10) distribution = tfp.distributions.Normal(loc=means, scale=stddev) if not self.is_meta_training: return means, tf.constant(0., dtype=self._float_dtype) samples = distribution.sample() kl_divergence = self.kl_divergence(samples, distribution) return samples, kl_divergence def kl_divergence(self, samples, normal_distribution): random_prior = tfp.distributions.Normal( loc=tf.zeros_like(samples), scale=tf.ones_like(samples)) kl = tf.reduce_mean( normal_distribution.log_prob(samples) - random_prior.log_prob(samples)) return kl def predict(self, inputs, weights): after_dropout = tf.nn.dropout(inputs, keep_prob=self.dropout_rate) # This is 3-dimensional equivalent of a matrix product, where we sum over # the last (embedding_dim) dimension. We get [N, K, N, K] tensor as output. per_image_predictions = tf.einsum("ijk,lmk->ijlm", after_dropout, weights) # Predictions have shape [N, K, N]: for each image ([N, K] of them), what # is the probability of a given class (N)? predictions = tf.reduce_mean(per_image_predictions, axis=-1) return predictions def calculate_inner_loss(self, inputs, true_outputs, classifier_weights): model_outputs = self.predict(inputs, classifier_weights) model_predictions = tf.argmax( model_outputs, -1, output_type=self._int_dtype) accuracy = tf.contrib.metrics.accuracy(model_predictions, tf.squeeze(true_outputs, axis=-1)) return self.loss_fn(model_outputs, true_outputs), accuracy def save_problem_instance_stats(self, instance): num_classes, num_examples_per_class, embedding_dim = instance.get_shape() if hasattr(self, "num_classes"): assert self.num_classes == num_classes, ( "Given different number of classes (N in N-way) in consecutive runs.") if hasattr(self, "num_examples_per_class"): assert self.num_examples_per_class == num_examples_per_class, ( "Given different number of examples (K in K-shot) in consecutive" "runs.") if hasattr(self, "embedding_dim"): assert self.embedding_dim == embedding_dim, ( "Given different embedding dimension in consecutive runs.") self.num_classes = num_classes self.num_examples_per_class = num_examples_per_class self.embedding_dim = embedding_dim @property def dropout_rate(self): return self._dropout_rate if self.is_meta_training else 0.01 def loss_fn(self, model_outputs, original_classes): original_classes = tf.squeeze(original_classes, axis=-1) # Tensorflow doesn't handle second order gradients of a sparse_softmax yet. one_hot_outputs = tf.one_hot(original_classes, depth=self.num_classes) return tf.nn.softmax_cross_entropy_with_logits_v2( labels=one_hot_outputs, logits=model_outputs) def grads_and_vars(self, metatrain_loss): """Computes gradients of metatrain_loss, avoiding NaN. Uses a fixed penalty of 1e-4 to enforce only the l2 regularization (and not minimize the loss) when metatrain_loss or any of its gradients with respect to trainable_vars are NaN. In practice, this approach pulls the variables back into a feasible region of the space when the loss or its gradients are not defined. Args: metatrain_loss: A tensor with the LEO meta-training loss. Returns: A tuple with: metatrain_gradients: A list of gradient tensors. metatrain_variables: A list of variables for this LEO model. """ metatrain_variables = self.trainable_variables metatrain_gradients = tf.gradients(metatrain_loss, metatrain_variables) nan_loss_or_grad = tf.logical_or( tf.is_nan(metatrain_loss), tf.reduce_any([tf.reduce_any(tf.is_nan(g)) for g in metatrain_gradients])) regularization_penalty = ( 1e-4 / self._l2_penalty_weight * self._l2_regularization) zero_or_regularization_gradients = [ g if g is not None else tf.zeros_like(v) for v, g in zip(tf.gradients(regularization_penalty, metatrain_variables), metatrain_variables)] metatrain_gradients = tf.cond(nan_loss_or_grad, lambda: zero_or_regularization_gradients, lambda: metatrain_gradients, strict=True) return metatrain_gradients, metatrain_variables @property def _l2_regularization(self): return tf.cast( tf.reduce_sum(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)), dtype=self._float_dtype) @property def _decoder_orthogonality_reg(self): return self._orthogonality_reg
# Copyright 2018 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Code defining LEO inner loop. See "Meta-Learning with Latent Embedding Optimization" by Rusu et al. (https://arxiv.org/pdf/1807.05960.pdf). """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from six.moves import range from six.moves import zip import sonnet as snt import tensorflow as tf import tensorflow_probability as tfp import data as data_module def get_orthogonality_regularizer(orthogonality_penalty_weight): """Returns the orthogonality regularizer.""" def orthogonality(weight): """Calculates the layer-wise penalty encouraging orthogonality.""" with tf.name_scope(None, "orthogonality", [weight]) as name: w2 = tf.matmul(weight, weight, transpose_b=True) wn = tf.norm(weight, ord=2, axis=1, keepdims=True) + 1e-32 correlation_matrix = w2 / tf.matmul(wn, wn, transpose_b=True) matrix_size = correlation_matrix.get_shape().as_list()[0] base_dtype = weight.dtype.base_dtype identity = tf.eye(matrix_size, dtype=base_dtype) weight_corr = tf.reduce_mean( tf.squared_difference(correlation_matrix, identity)) return tf.multiply( tf.cast(orthogonality_penalty_weight, base_dtype), weight_corr, name=name) return orthogonality class LEO(snt.AbstractModule): """Sonnet module implementing the inner loop of LEO.""" def __init__(self, config=None, use_64bits_dtype=True, name="leo"): super(LEO, self).__init__(name=name) self._float_dtype = tf.float64 if use_64bits_dtype else tf.float32 self._int_dtype = tf.int64 if use_64bits_dtype else tf.int32 self._inner_unroll_length = config["inner_unroll_length"] self._finetuning_unroll_length = config["finetuning_unroll_length"] self._inner_lr_init = config["inner_lr_init"] self._finetuning_lr_init = config["finetuning_lr_init"] self._num_latents = config["num_latents"] self._dropout_rate = config["dropout_rate"] self._kl_weight = config["kl_weight"] # beta self._encoder_penalty_weight = config["encoder_penalty_weight"] # gamma self._l2_penalty_weight = config["l2_penalty_weight"] # lambda_1 # lambda_2 self._orthogonality_penalty_weight = config["orthogonality_penalty_weight"] assert self._inner_unroll_length > 0, ("Positive unroll length is necessary" " to create the graph") def _build(self, data, is_meta_training=True): """Connects the LEO module to the graph, creating the variables. Args: data: A data_module.ProblemInstance constaining Tensors with the following shapes: - tr_input: (N, K, dim) - tr_output: (N, K, 1) - tr_info: (N, K) - val_input: (N, K_valid, dim) - val_output: (N, K_valid, 1) - val_info: (N, K_valid) where N is the number of classes (as in N-way) and K and the and K_valid are numbers of training and validation examples within a problem instance correspondingly (as in K-shot), and dim is the dimensionality of the embedding. is_meta_training: A boolean describing whether we run in the training mode. Returns: Tensor with the inner validation loss of LEO (include both adaptation in the latent space and finetuning). """ if isinstance(data, list): data = data_module.ProblemInstance(*data) self.is_meta_training = is_meta_training self.save_problem_instance_stats(data.tr_input) latents, kl = self.forward_encoder(data) tr_loss, adapted_classifier_weights, encoder_penalty = self.leo_inner_loop( data, latents) val_loss, val_accuracy = self.finetuning_inner_loop( data, tr_loss, adapted_classifier_weights) val_loss += self._kl_weight * kl val_loss += self._encoder_penalty_weight * encoder_penalty # The l2 regularization is is already added to the graph when constructing # the snt.Linear modules. We pass the orthogonality regularizer separately, # because it is not used in self.grads_and_vars. regularization_penalty = ( self._l2_regularization + self._decoder_orthogonality_reg) batch_val_loss = tf.reduce_mean(val_loss) batch_val_accuracy = tf.reduce_mean(val_accuracy) return batch_val_loss + regularization_penalty, batch_val_accuracy @snt.reuse_variables def leo_inner_loop(self, data, latents): with tf.variable_scope("leo_inner"): inner_lr = tf.get_variable( "lr", [1, 1, self._num_latents], dtype=self._float_dtype, initializer=tf.constant_initializer(self._inner_lr_init)) starting_latents = latents loss, _ = self.forward_decoder(data, latents) for _ in range(self._inner_unroll_length): loss_grad = tf.gradients(loss, latents) # dLtrain/dz latents -= inner_lr * loss_grad[0] loss, classifier_weights = self.forward_decoder(data, latents) if self.is_meta_training: encoder_penalty = tf.losses.mean_squared_error( labels=tf.stop_gradient(latents), predictions=starting_latents) encoder_penalty = tf.cast(encoder_penalty, self._float_dtype) else: encoder_penalty = tf.constant(0., self._float_dtype) return loss, classifier_weights, encoder_penalty @snt.reuse_variables def finetuning_inner_loop(self, data, leo_loss, classifier_weights): tr_loss = leo_loss with tf.variable_scope("finetuning"): finetuning_lr = tf.get_variable( "lr", [1, 1, self.embedding_dim], dtype=self._float_dtype, initializer=tf.constant_initializer(self._finetuning_lr_init)) for _ in range(self._finetuning_unroll_length): loss_grad = tf.gradients(tr_loss, classifier_weights) classifier_weights -= finetuning_lr * loss_grad[0] tr_loss, _ = self.calculate_inner_loss(data.tr_input, data.tr_output, classifier_weights) val_loss, val_accuracy = self.calculate_inner_loss( data.val_input, data.val_output, classifier_weights) return val_loss, val_accuracy @snt.reuse_variables def forward_encoder(self, data): encoder_outputs = self.encoder(data.tr_input) relation_network_outputs = self.relation_network(encoder_outputs) latent_dist_params = self.average_codes_per_class(relation_network_outputs) latents, kl = self.possibly_sample(latent_dist_params) return latents, kl @snt.reuse_variables def forward_decoder(self, data, latents): weights_dist_params = self.decoder(latents) # Default to glorot_initialization and not stddev=1. fan_in = self.embedding_dim.value fan_out = self.num_classes.value stddev_offset = np.sqrt(2. / (fan_out + fan_in)) classifier_weights, _ = self.possibly_sample(weights_dist_params, stddev_offset=stddev_offset) tr_loss, _ = self.calculate_inner_loss(data.tr_input, data.tr_output, classifier_weights) return tr_loss, classifier_weights @snt.reuse_variables def encoder(self, inputs): with tf.variable_scope("encoder"): after_dropout = tf.nn.dropout(inputs, keep_prob=self.dropout_rate) regularizer = tf.contrib.layers.l2_regularizer(self._l2_penalty_weight) initializer = tf.initializers.glorot_uniform(dtype=self._float_dtype) encoder_module = snt.Linear( self._num_latents, use_bias=False, regularizers={"w": regularizer}, initializers={"w": initializer}, ) outputs = snt.BatchApply(encoder_module)(after_dropout) return outputs @snt.reuse_variables def relation_network(self, inputs): with tf.variable_scope("relation_network"): regularizer = tf.contrib.layers.l2_regularizer(self._l2_penalty_weight) initializer = tf.initializers.glorot_uniform(dtype=self._float_dtype) relation_network_module = snt.nets.MLP( [2 * self._num_latents] * 3, use_bias=False, regularizers={"w": regularizer}, initializers={"w": initializer}, ) total_num_examples = self.num_examples_per_class*self.num_classes inputs = tf.reshape(inputs, [total_num_examples, self._num_latents]) left = tf.tile(tf.expand_dims(inputs, 1), [1, total_num_examples, 1]) right = tf.tile(tf.expand_dims(inputs, 0), [total_num_examples, 1, 1]) concat_codes = tf.concat([left, right], axis=-1) outputs = snt.BatchApply(relation_network_module)(concat_codes) outputs = tf.reduce_mean(outputs, axis=1) # 2 * latents, because we are returning means and variances of a Gaussian outputs = tf.reshape(outputs, [self.num_classes, self.num_examples_per_class, 2 * self._num_latents]) return outputs @snt.reuse_variables def decoder(self, inputs): with tf.variable_scope("decoder"): l2_regularizer = tf.contrib.layers.l2_regularizer(self._l2_penalty_weight) orthogonality_reg = get_orthogonality_regularizer( self._orthogonality_penalty_weight) initializer = tf.initializers.glorot_uniform(dtype=self._float_dtype) # 2 * embedding_dim, because we are returning means and variances decoder_module = snt.Linear( 2 * self.embedding_dim, use_bias=False, regularizers={"w": l2_regularizer}, initializers={"w": initializer}, ) outputs = snt.BatchApply(decoder_module)(inputs) self._orthogonality_reg = orthogonality_reg(decoder_module.w) return outputs def average_codes_per_class(self, codes): codes = tf.reduce_mean(codes, axis=1, keep_dims=True) # K dimension # Keep the shape (N, K, *) codes = tf.tile(codes, [1, self.num_examples_per_class, 1]) return codes def possibly_sample(self, distribution_params, stddev_offset=0.): means, unnormalized_stddev = tf.split(distribution_params, 2, axis=-1) stddev = tf.exp(unnormalized_stddev) stddev -= (1. - stddev_offset) stddev = tf.maximum(stddev, 1e-10) distribution = tfp.distributions.Normal(loc=means, scale=stddev) if not self.is_meta_training: return means, tf.constant(0., dtype=self._float_dtype) samples = distribution.sample() kl_divergence = self.kl_divergence(samples, distribution) return samples, kl_divergence def kl_divergence(self, samples, normal_distribution): random_prior = tfp.distributions.Normal( loc=tf.zeros_like(samples), scale=tf.ones_like(samples)) kl = tf.reduce_mean( normal_distribution.log_prob(samples) - random_prior.log_prob(samples)) return kl def predict(self, inputs, weights): after_dropout = tf.nn.dropout(inputs, keep_prob=self.dropout_rate) # This is 3-dimensional equivalent of a matrix product, where we sum over # the last (embedding_dim) dimension. We get [N, K, N, K] tensor as output. per_image_predictions = tf.einsum("ijk,lmk->ijlm", after_dropout, weights) # Predictions have shape [N, K, N]: for each image ([N, K] of them), what # is the probability of a given class (N)? predictions = tf.reduce_mean(per_image_predictions, axis=-1) return predictions def calculate_inner_loss(self, inputs, true_outputs, classifier_weights): model_outputs = self.predict(inputs, classifier_weights) model_predictions = tf.argmax( model_outputs, -1, output_type=self._int_dtype) accuracy = tf.contrib.metrics.accuracy(model_predictions, tf.squeeze(true_outputs, axis=-1)) return self.loss_fn(model_outputs, true_outputs), accuracy def save_problem_instance_stats(self, instance): num_classes, num_examples_per_class, embedding_dim = instance.get_shape() if hasattr(self, "num_classes"): assert self.num_classes == num_classes, ( "Given different number of classes (N in N-way) in consecutive runs.") if hasattr(self, "num_examples_per_class"): assert self.num_examples_per_class == num_examples_per_class, ( "Given different number of examples (K in K-shot) in consecutive" "runs.") if hasattr(self, "embedding_dim"): assert self.embedding_dim == embedding_dim, ( "Given different embedding dimension in consecutive runs.") self.num_classes = num_classes self.num_examples_per_class = num_examples_per_class self.embedding_dim = embedding_dim @property def dropout_rate(self): return self._dropout_rate if self.is_meta_training else 0.01 def loss_fn(self, model_outputs, original_classes): original_classes = tf.squeeze(original_classes, axis=-1) # Tensorflow doesn't handle second order gradients of a sparse_softmax yet. one_hot_outputs = tf.one_hot(original_classes, depth=self.num_classes) return tf.nn.softmax_cross_entropy_with_logits_v2( labels=one_hot_outputs, logits=model_outputs) def grads_and_vars(self, metatrain_loss): """Computes gradients of metatrain_loss, avoiding NaN. Uses a fixed penalty of 1e-4 to enforce only the l2 regularization (and not minimize the loss) when metatrain_loss or any of its gradients with respect to trainable_vars are NaN. In practice, this approach pulls the variables back into a feasible region of the space when the loss or its gradients are not defined. Args: metatrain_loss: A tensor with the LEO meta-training loss. Returns: A tuple with: metatrain_gradients: A list of gradient tensors. metatrain_variables: A list of variables for this LEO model. """ metatrain_variables = self.trainable_variables metatrain_gradients = tf.gradients(metatrain_loss, metatrain_variables) nan_loss_or_grad = tf.logical_or( tf.is_nan(metatrain_loss), tf.reduce_any([tf.reduce_any(tf.is_nan(g)) for g in metatrain_gradients])) regularization_penalty = ( 1e-4 / self._l2_penalty_weight * self._l2_regularization) zero_or_regularization_gradients = [ g if g is not None else tf.zeros_like(v) for v, g in zip(tf.gradients(regularization_penalty, metatrain_variables), metatrain_variables)] metatrain_gradients = tf.cond(nan_loss_or_grad, lambda: zero_or_regularization_gradients, lambda: metatrain_gradients, strict=True) return metatrain_gradients, metatrain_variables @property def _l2_regularization(self): return tf.cast( tf.reduce_sum(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)), dtype=self._float_dtype) @property def _decoder_orthogonality_reg(self): return self._orthogonality_reg
en
0.818106
# Copyright 2018 DeepMind Technologies Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ Code defining LEO inner loop. See "Meta-Learning with Latent Embedding Optimization" by Rusu et al. (https://arxiv.org/pdf/1807.05960.pdf). Returns the orthogonality regularizer. Calculates the layer-wise penalty encouraging orthogonality. Sonnet module implementing the inner loop of LEO. # beta # gamma # lambda_1 # lambda_2 Connects the LEO module to the graph, creating the variables. Args: data: A data_module.ProblemInstance constaining Tensors with the following shapes: - tr_input: (N, K, dim) - tr_output: (N, K, 1) - tr_info: (N, K) - val_input: (N, K_valid, dim) - val_output: (N, K_valid, 1) - val_info: (N, K_valid) where N is the number of classes (as in N-way) and K and the and K_valid are numbers of training and validation examples within a problem instance correspondingly (as in K-shot), and dim is the dimensionality of the embedding. is_meta_training: A boolean describing whether we run in the training mode. Returns: Tensor with the inner validation loss of LEO (include both adaptation in the latent space and finetuning). # The l2 regularization is is already added to the graph when constructing # the snt.Linear modules. We pass the orthogonality regularizer separately, # because it is not used in self.grads_and_vars. # dLtrain/dz # Default to glorot_initialization and not stddev=1. # 2 * latents, because we are returning means and variances of a Gaussian # 2 * embedding_dim, because we are returning means and variances # K dimension # Keep the shape (N, K, *) # This is 3-dimensional equivalent of a matrix product, where we sum over # the last (embedding_dim) dimension. We get [N, K, N, K] tensor as output. # Predictions have shape [N, K, N]: for each image ([N, K] of them), what # is the probability of a given class (N)? # Tensorflow doesn't handle second order gradients of a sparse_softmax yet. Computes gradients of metatrain_loss, avoiding NaN. Uses a fixed penalty of 1e-4 to enforce only the l2 regularization (and not minimize the loss) when metatrain_loss or any of its gradients with respect to trainable_vars are NaN. In practice, this approach pulls the variables back into a feasible region of the space when the loss or its gradients are not defined. Args: metatrain_loss: A tensor with the LEO meta-training loss. Returns: A tuple with: metatrain_gradients: A list of gradient tensors. metatrain_variables: A list of variables for this LEO model.
2.056504
2
tests/integrationv2/test_well_known_endpoints.py
glaubitz/s2n
0
6625764
<reponame>glaubitz/s2n import copy import os import pytest from constants import TRUST_STORE_BUNDLE from configuration import available_ports, PROTOCOLS from common import ProviderOptions, Protocols, Ciphers from fixtures import managed_process from global_flags import get_flag, S2N_NO_PQ, S2N_FIPS_MODE from providers import Provider, S2N from utils import invalid_test_parameters, get_parameter_name ENDPOINTS = [ {"endpoint": "amazon.com"}, {"endpoint": "facebook.com"}, {"endpoint": "google.com"}, {"endpoint": "netflix.com"}, {"endpoint": "s3.amazonaws.com"}, {"endpoint": "twitter.com"}, {"endpoint": "wikipedia.org"}, {"endpoint": "yahoo.com"}, ] if get_flag(S2N_NO_PQ, False) is False: # If PQ was compiled into S2N, test the PQ preferences against KMS pq_endpoints = [ { "endpoint": "kms.us-east-1.amazonaws.com", "cipher_preference_version": Ciphers.KMS_PQ_TLS_1_0_2019_06, "expected_cipher": "ECDHE-BIKE-RSA-AES256-GCM-SHA384", "expected_kem": "BIKE1r1-Level1", }, { "endpoint": "kms.us-east-1.amazonaws.com", "cipher_preference_version": Ciphers.PQ_SIKE_TEST_TLS_1_0_2019_11, "expected_cipher": "ECDHE-SIKE-RSA-AES256-GCM-SHA384", "expected_kem": "SIKEp503r1-KEM", }, { "endpoint": "kms.us-east-1.amazonaws.com", "cipher_preference_version": Ciphers.KMS_PQ_TLS_1_0_2020_07, "expected_cipher": "ECDHE-KYBER-RSA-AES256-GCM-SHA384", "expected_kem": "kyber512r2", }, { "endpoint": "kms.us-east-1.amazonaws.com", "cipher_preference_version": Ciphers.KMS_PQ_TLS_1_0_2020_02, "expected_cipher": "ECDHE-BIKE-RSA-AES256-GCM-SHA384", "expected_kem": "BIKE1r2-Level1", }, { "endpoint": "kms.us-east-1.amazonaws.com", "cipher_preference_version": Ciphers.PQ_SIKE_TEST_TLS_1_0_2020_02, "expected_cipher": "ECDHE-SIKE-RSA-AES256-GCM-SHA384", "expected_kem": "SIKEp434r2-KEM", }, ] ENDPOINTS.extend(pq_endpoints) @pytest.mark.uncollect_if(func=invalid_test_parameters) @pytest.mark.parametrize("protocol", PROTOCOLS, ids=get_parameter_name) @pytest.mark.parametrize("endpoint", ENDPOINTS, ids=lambda x: "{}-{}".format(x['endpoint'], x.get('cipher_preference_version', 'Default'))) def test_well_known_endpoints(managed_process, protocol, endpoint): port = "443" client_options = ProviderOptions( mode=Provider.ClientMode, host=endpoint['endpoint'], port=port, insecure=False, client_trust_store=TRUST_STORE_BUNDLE, protocol=protocol) if get_flag(S2N_FIPS_MODE) is True: client_options.client_trust_store = "../integration/trust-store/ca-bundle.trust.crt" else: client_options.client_trust_store = "../integration/trust-store/ca-bundle.crt" if 'cipher_preference_version' in endpoint: client_options.cipher = endpoint['cipher_preference_version'] client = managed_process(S2N, client_options, timeout=5) for results in client.get_results(): assert results.exception is None assert results.exit_code == 0 if 'expected_cipher' in endpoint: assert bytes(endpoint['expected_cipher'].encode('utf-8')) in results.stdout if 'expected_kem' in endpoint: assert bytes(endpoint['expected_kem'].encode('utf-8')) in results.stdout
import copy import os import pytest from constants import TRUST_STORE_BUNDLE from configuration import available_ports, PROTOCOLS from common import ProviderOptions, Protocols, Ciphers from fixtures import managed_process from global_flags import get_flag, S2N_NO_PQ, S2N_FIPS_MODE from providers import Provider, S2N from utils import invalid_test_parameters, get_parameter_name ENDPOINTS = [ {"endpoint": "amazon.com"}, {"endpoint": "facebook.com"}, {"endpoint": "google.com"}, {"endpoint": "netflix.com"}, {"endpoint": "s3.amazonaws.com"}, {"endpoint": "twitter.com"}, {"endpoint": "wikipedia.org"}, {"endpoint": "yahoo.com"}, ] if get_flag(S2N_NO_PQ, False) is False: # If PQ was compiled into S2N, test the PQ preferences against KMS pq_endpoints = [ { "endpoint": "kms.us-east-1.amazonaws.com", "cipher_preference_version": Ciphers.KMS_PQ_TLS_1_0_2019_06, "expected_cipher": "ECDHE-BIKE-RSA-AES256-GCM-SHA384", "expected_kem": "BIKE1r1-Level1", }, { "endpoint": "kms.us-east-1.amazonaws.com", "cipher_preference_version": Ciphers.PQ_SIKE_TEST_TLS_1_0_2019_11, "expected_cipher": "ECDHE-SIKE-RSA-AES256-GCM-SHA384", "expected_kem": "SIKEp503r1-KEM", }, { "endpoint": "kms.us-east-1.amazonaws.com", "cipher_preference_version": Ciphers.KMS_PQ_TLS_1_0_2020_07, "expected_cipher": "ECDHE-KYBER-RSA-AES256-GCM-SHA384", "expected_kem": "kyber512r2", }, { "endpoint": "kms.us-east-1.amazonaws.com", "cipher_preference_version": Ciphers.KMS_PQ_TLS_1_0_2020_02, "expected_cipher": "ECDHE-BIKE-RSA-AES256-GCM-SHA384", "expected_kem": "BIKE1r2-Level1", }, { "endpoint": "kms.us-east-1.amazonaws.com", "cipher_preference_version": Ciphers.PQ_SIKE_TEST_TLS_1_0_2020_02, "expected_cipher": "ECDHE-SIKE-RSA-AES256-GCM-SHA384", "expected_kem": "SIKEp434r2-KEM", }, ] ENDPOINTS.extend(pq_endpoints) @pytest.mark.uncollect_if(func=invalid_test_parameters) @pytest.mark.parametrize("protocol", PROTOCOLS, ids=get_parameter_name) @pytest.mark.parametrize("endpoint", ENDPOINTS, ids=lambda x: "{}-{}".format(x['endpoint'], x.get('cipher_preference_version', 'Default'))) def test_well_known_endpoints(managed_process, protocol, endpoint): port = "443" client_options = ProviderOptions( mode=Provider.ClientMode, host=endpoint['endpoint'], port=port, insecure=False, client_trust_store=TRUST_STORE_BUNDLE, protocol=protocol) if get_flag(S2N_FIPS_MODE) is True: client_options.client_trust_store = "../integration/trust-store/ca-bundle.trust.crt" else: client_options.client_trust_store = "../integration/trust-store/ca-bundle.crt" if 'cipher_preference_version' in endpoint: client_options.cipher = endpoint['cipher_preference_version'] client = managed_process(S2N, client_options, timeout=5) for results in client.get_results(): assert results.exception is None assert results.exit_code == 0 if 'expected_cipher' in endpoint: assert bytes(endpoint['expected_cipher'].encode('utf-8')) in results.stdout if 'expected_kem' in endpoint: assert bytes(endpoint['expected_kem'].encode('utf-8')) in results.stdout
en
0.987002
# If PQ was compiled into S2N, test the PQ preferences against KMS
1.840452
2
examples/gurobipy/metrorail/metrorail.py
adampkehoe/ticdat
0
6625765
<gh_stars>0 # # Models Tallys Yunes Metrorail tickets problem. # https://orbythebeach.wordpress.com/2018/03/01/buying-metrorail-tickets-in-miami/ # https://www.linkedin.com/pulse/miami-metrorail-meets-python-peter-cacioppi/ # # Implement core functionality needed to achieve modularity. # 1. Define the input data schema # 2. Define the output data schema # 3. Create a solve function that accepts a data set consistent with the input # schema and (if possible) returns a data set consistent with the output schema. # # Provides command line interface via ticdat.standard_main # For example, typing # python metrorail.py -i metrorail_sample_data.json -o metrorail_solution_data.json # will read from a model stored in the file metrorail_sample_data.json and write the # solution to metrorail_solution_data.json. try: # if you don't have gurobipy installed, the code will still load and then fail on solve import gurobipy as gu except: gu = None from ticdat import TicDatFactory, standard_main from itertools import product # ------------------------ define the input schema -------------------------------- input_schema = TicDatFactory ( parameters=[["Parameter"], ["Value"]], load_amounts=[["Amount"],[]], number_of_one_way_trips=[["Number"],[]], amount_leftover=[["Amount"], []]) input_schema.set_data_type("load_amounts", "Amount", min=0, max=float("inf"), inclusive_min=False, inclusive_max=False) input_schema.set_data_type("number_of_one_way_trips", "Number", min=0, max=float("inf"), inclusive_min=False, inclusive_max=False, must_be_int=True) input_schema.set_data_type("amount_leftover", "Amount", min=0, max=float("inf"), inclusive_min=True, inclusive_max=False) input_schema.add_parameter("One Way Price", default_value=2.25, min=0, max=float("inf"), inclusive_min=True, inclusive_max=False) input_schema.add_parameter("Amount Leftover Constraint", default_value="Upper Bound", number_allowed=False, strings_allowed=["Equality", "Upper Bound", "Upper Bound With Leftover Multiple Rule"]) # --------------------------------------------------------------------------------- # ------------------------ define the output schema ------------------------------- solution_schema = TicDatFactory( load_amount_details=[["Number One Way Trips", "Amount Leftover", "Load Amount"], ["Number Of Visits"]], load_amount_summary=[["Number One Way Trips", "Amount Leftover"],["Number Of Visits"]]) # --------------------------------------------------------------------------------- # ------------------------ create a solve function -------------------------------- def solve(dat): """ core solving routine :param dat: a good ticdat for the input_schema :return: a good ticdat for the solution_schema, or None """ assert input_schema.good_tic_dat_object(dat) assert not input_schema.find_foreign_key_failures(dat) assert not input_schema.find_data_type_failures(dat) assert not input_schema.find_data_row_failures(dat) full_parameters = input_schema.create_full_parameters_dict(dat) sln = solution_schema.TicDat() # create an empty solution' # solve a distinct MIP for each pair of (# of one-way-trips, amount leftover) for number_trips, amount_leftover in product(dat.number_of_one_way_trips, dat.amount_leftover): mdl = gu.Model("metrorail") # Create decision variables number_vists = {la:mdl.addVar(vtype = gu.GRB.INTEGER, name="load_amount_%s"%la) for la in dat.load_amounts} amount_leftover_var = mdl.addVar(name="amount_leftover", lb=0, ub=amount_leftover) # an equality constraint is modeled here as amount_leftover_var.lb = amount_leftover_var.ub if full_parameters["Amount Leftover Constraint"] == "Equality": amount_leftover_var.lb = amount_leftover # for left-over is multiple, we will still respect the amount leftover upper bound # but will also enforce that the amount leftover is a multiple of the one way price if full_parameters["Amount Leftover Constraint"] == "Upper Bound With Leftover Multiple Rule": leftover_multiple = mdl.addVar(vtype = gu.GRB.INTEGER, name="leftover_multiple") mdl.addConstr(amount_leftover_var == full_parameters["One Way Price"] * leftover_multiple, name="set_leftover_multiple") # add a constraint to set the amount leftover mdl.addConstr(amount_leftover_var == gu.quicksum(la * number_vists[la] for la in dat.load_amounts) - full_parameters["One Way Price"] * number_trips, name="set_amount_leftover") # minimize the total number of visits to the ticket office mdl.setObjective(gu.quicksum(number_vists.values()), sense=gu.GRB.MINIMIZE) mdl.optimize() if mdl.status in [gu.GRB.OPTIMAL, gu.GRB.SUBOPTIMAL]: # store the results if and only if the model is feasible for la,x in number_vists.items(): if round(x.x) > 0: sln.load_amount_details[number_trips, amount_leftover, la] = round(x.x) sln.load_amount_summary[number_trips, amount_leftover]["Number Of Visits"]\ += round(x.x) return sln # --------------------------------------------------------------------------------- # ------------------------ provide stand-alone functionality ---------------------- # when run from the command line, will read/write json/xls/csv/db/sql/mdb files if __name__ == "__main__": standard_main(input_schema, solution_schema, solve) # ---------------------------------------------------------------------------------
# # Models Tallys Yunes Metrorail tickets problem. # https://orbythebeach.wordpress.com/2018/03/01/buying-metrorail-tickets-in-miami/ # https://www.linkedin.com/pulse/miami-metrorail-meets-python-peter-cacioppi/ # # Implement core functionality needed to achieve modularity. # 1. Define the input data schema # 2. Define the output data schema # 3. Create a solve function that accepts a data set consistent with the input # schema and (if possible) returns a data set consistent with the output schema. # # Provides command line interface via ticdat.standard_main # For example, typing # python metrorail.py -i metrorail_sample_data.json -o metrorail_solution_data.json # will read from a model stored in the file metrorail_sample_data.json and write the # solution to metrorail_solution_data.json. try: # if you don't have gurobipy installed, the code will still load and then fail on solve import gurobipy as gu except: gu = None from ticdat import TicDatFactory, standard_main from itertools import product # ------------------------ define the input schema -------------------------------- input_schema = TicDatFactory ( parameters=[["Parameter"], ["Value"]], load_amounts=[["Amount"],[]], number_of_one_way_trips=[["Number"],[]], amount_leftover=[["Amount"], []]) input_schema.set_data_type("load_amounts", "Amount", min=0, max=float("inf"), inclusive_min=False, inclusive_max=False) input_schema.set_data_type("number_of_one_way_trips", "Number", min=0, max=float("inf"), inclusive_min=False, inclusive_max=False, must_be_int=True) input_schema.set_data_type("amount_leftover", "Amount", min=0, max=float("inf"), inclusive_min=True, inclusive_max=False) input_schema.add_parameter("One Way Price", default_value=2.25, min=0, max=float("inf"), inclusive_min=True, inclusive_max=False) input_schema.add_parameter("Amount Leftover Constraint", default_value="Upper Bound", number_allowed=False, strings_allowed=["Equality", "Upper Bound", "Upper Bound With Leftover Multiple Rule"]) # --------------------------------------------------------------------------------- # ------------------------ define the output schema ------------------------------- solution_schema = TicDatFactory( load_amount_details=[["Number One Way Trips", "Amount Leftover", "Load Amount"], ["Number Of Visits"]], load_amount_summary=[["Number One Way Trips", "Amount Leftover"],["Number Of Visits"]]) # --------------------------------------------------------------------------------- # ------------------------ create a solve function -------------------------------- def solve(dat): """ core solving routine :param dat: a good ticdat for the input_schema :return: a good ticdat for the solution_schema, or None """ assert input_schema.good_tic_dat_object(dat) assert not input_schema.find_foreign_key_failures(dat) assert not input_schema.find_data_type_failures(dat) assert not input_schema.find_data_row_failures(dat) full_parameters = input_schema.create_full_parameters_dict(dat) sln = solution_schema.TicDat() # create an empty solution' # solve a distinct MIP for each pair of (# of one-way-trips, amount leftover) for number_trips, amount_leftover in product(dat.number_of_one_way_trips, dat.amount_leftover): mdl = gu.Model("metrorail") # Create decision variables number_vists = {la:mdl.addVar(vtype = gu.GRB.INTEGER, name="load_amount_%s"%la) for la in dat.load_amounts} amount_leftover_var = mdl.addVar(name="amount_leftover", lb=0, ub=amount_leftover) # an equality constraint is modeled here as amount_leftover_var.lb = amount_leftover_var.ub if full_parameters["Amount Leftover Constraint"] == "Equality": amount_leftover_var.lb = amount_leftover # for left-over is multiple, we will still respect the amount leftover upper bound # but will also enforce that the amount leftover is a multiple of the one way price if full_parameters["Amount Leftover Constraint"] == "Upper Bound With Leftover Multiple Rule": leftover_multiple = mdl.addVar(vtype = gu.GRB.INTEGER, name="leftover_multiple") mdl.addConstr(amount_leftover_var == full_parameters["One Way Price"] * leftover_multiple, name="set_leftover_multiple") # add a constraint to set the amount leftover mdl.addConstr(amount_leftover_var == gu.quicksum(la * number_vists[la] for la in dat.load_amounts) - full_parameters["One Way Price"] * number_trips, name="set_amount_leftover") # minimize the total number of visits to the ticket office mdl.setObjective(gu.quicksum(number_vists.values()), sense=gu.GRB.MINIMIZE) mdl.optimize() if mdl.status in [gu.GRB.OPTIMAL, gu.GRB.SUBOPTIMAL]: # store the results if and only if the model is feasible for la,x in number_vists.items(): if round(x.x) > 0: sln.load_amount_details[number_trips, amount_leftover, la] = round(x.x) sln.load_amount_summary[number_trips, amount_leftover]["Number Of Visits"]\ += round(x.x) return sln # --------------------------------------------------------------------------------- # ------------------------ provide stand-alone functionality ---------------------- # when run from the command line, will read/write json/xls/csv/db/sql/mdb files if __name__ == "__main__": standard_main(input_schema, solution_schema, solve) # ---------------------------------------------------------------------------------
en
0.551666
# # Models Tallys Yunes Metrorail tickets problem. # https://orbythebeach.wordpress.com/2018/03/01/buying-metrorail-tickets-in-miami/ # https://www.linkedin.com/pulse/miami-metrorail-meets-python-peter-cacioppi/ # # Implement core functionality needed to achieve modularity. # 1. Define the input data schema # 2. Define the output data schema # 3. Create a solve function that accepts a data set consistent with the input # schema and (if possible) returns a data set consistent with the output schema. # # Provides command line interface via ticdat.standard_main # For example, typing # python metrorail.py -i metrorail_sample_data.json -o metrorail_solution_data.json # will read from a model stored in the file metrorail_sample_data.json and write the # solution to metrorail_solution_data.json. # if you don't have gurobipy installed, the code will still load and then fail on solve # ------------------------ define the input schema -------------------------------- # --------------------------------------------------------------------------------- # ------------------------ define the output schema ------------------------------- # --------------------------------------------------------------------------------- # ------------------------ create a solve function -------------------------------- core solving routine :param dat: a good ticdat for the input_schema :return: a good ticdat for the solution_schema, or None # create an empty solution' # solve a distinct MIP for each pair of (# of one-way-trips, amount leftover) # Create decision variables # an equality constraint is modeled here as amount_leftover_var.lb = amount_leftover_var.ub # for left-over is multiple, we will still respect the amount leftover upper bound # but will also enforce that the amount leftover is a multiple of the one way price # add a constraint to set the amount leftover # minimize the total number of visits to the ticket office # store the results if and only if the model is feasible # --------------------------------------------------------------------------------- # ------------------------ provide stand-alone functionality ---------------------- # when run from the command line, will read/write json/xls/csv/db/sql/mdb files # ---------------------------------------------------------------------------------
2.710314
3
genetic-tuner/lib/listtools.py
windstrip/Genetic-Algorithm-PID-Controller-Tuner
39
6625766
<reponame>windstrip/Genetic-Algorithm-PID-Controller-Tuner # Reference: # http://code.activestate.com/recipes/278258/ def sumList(L): return reduce(lambda x,y:x+y, L) def avgList(L): return reduce(lambda x,y:x+y, L) /(len(L)*1.0) def normList(L, normalizeTo=1): '''normalize values of a list to make its max = normalizeTo''' vMax = max(L) return [ x/(vMax*1.0)*normalizeTo for x in L] def normListSumTo(L, sumTo=1): '''normalize values of a list to make it sum = sumTo''' sum = reduce(lambda x,y:x+y, L) return [ x/(sum*1.0)*sumTo for x in L] def accumList(L, normalizeTo=None): ''' L= [1, 2, 3, 4, 5]: accumList(L)=> [1, 3, 6, 10, 15] L= [0.25, 0.25, 0.25, 0.25]: accumList(L)=> [0.25, 0.50, 0.75, 1.00] normalizeTo: set the last number of the returned list to this value ''' if normalizeTo: LL = normListSumTo(L, sumTo=normalizeTo) else: LL = L[:] r = range(1, len(LL)) newList=[LL[0]] for i in r: newList.append( newList[-1]+ LL[i] ) return newList def findIndex(sortedList, x, indexBuffer=0): ''' Given a sortedList and value x, return the index i where sortedList[i-1] <= x < sortedList[i] Which means, sortedList.insert( findIndex(sortedList, x), x ) will give a sorted list ''' if len(sortedList)==2: if x==sortedList[-1]: return indexBuffer+2 elif x>=sortedList[0]: return indexBuffer+1 else: L = len(sortedList) firstHalf = sortedList[:L/2+1] secondHalf = sortedList[(L/2):] if secondHalf[-1]<=x: return indexBuffer + len(sortedList) elif x< firstHalf[0]: return indexBuffer else: if firstHalf[-1] < x: return findIndex(secondHalf, x, indexBuffer=L/2+indexBuffer) else: return findIndex(firstHalf,x, indexBuffer=indexBuffer) def randomPickList(L): ''' given a list L, with all values are numbers, randomly pick an item and return it's index according to the percentage of all values''' return findIndex(accumList(L,1), random.random()) def deepList(LString): ''' Given string representation of a nested list tree, return a list containing all the deepest list contents. For example: '[[1,[2, 2a]],[[3,3b],4]]' ==> ['2, 2a', '3,3b'] '[[[1,[2, 2a]],[[3,3b],4]],6]' ==> ['2, 2a', '3,3b'] '[[[[a1,a2],out],o1],[o2,o3]]' ==> ['a1,a2', 'o2,o3'] '[[[[[a1,a2], out], [o1,o2]],[o3,o4]],[o5,o6]]' ==> ['a1,a2', 'o1,o2', 'o3,o4', 'o5,o6'] The code: [x.split(']') for x in code.split('[')] returns something like: [[''], [''], [''], [''], [''], ['a1,a2', ', out', ', '], ['o1,o2', '', ','], ['o3,o4', '', ','], ['o5,o6', '', '']] ''' result= [x[0] for x in \ [x.split(']') for x in LString.split('[')] \ if len(x)>1] if result==['']: result =[] return result def getListStartsWith(aList, startsWith, isStrip=1): ''' for a list: L= ['abcdef', 'kkddff', 'xyz', '0wer'...], getListStartWith(L, 'kk') will return: ['kkddff', 'xyz', '0wer'...], getListStartWith(L, 'xy') will return: ['xyz', '0wer'...], if isStrip: any item ' xyz' will be considered 'xyz' else: the spaces in ' xyz' count. ''' tmp = aList[:] if isStrip: tmp = [x.strip() for x in tmp] startLineIndex = 0 for i in range(len(tmp)): if tmp[i].startswith(startsWith): startLineIndex = i return aList[startLineIndex:] def rezip(aList): ''' d = [[1, 5, 8, 3], [2, 2, 3, 9], [3, 2, 4, 6]] rezip(d): [(1, 2, 3), (5, 2, 2), (8, 3, 4), (3, 9, 6)] If a =[1, 5, 8], b=[2, 2, 3], c=[3, 2, 4] then it's eazy to: zip(a,b,c) = [(1, 2, 3), (5, 2, 2), (8, 3, 4)] But it's hard for d = [[1, 5, 8], [2, 2, 3], [3, 2, 4]] ''' tmp = [ [] for x in range(len(aList[0])) ] for i in range(len(aList[0])): for j in range(len(aList)): tmp[i].append(aList[j][i]) return tmp def sumInList(complexList): ''' Given a complexList [ [a1,b1,c1], [a2,b2,c2], [a3,b3,c3] ], return a list [ a, b, c] where a = a1+a2+a3, etc.''' d = rezip(complexList) return [ reduce(lambda x,y:x+y, z) for z in d ] def avgInList(complexList): ''' Given a complexList [ [a1,b1,c1], [a2,b2,c2], [a3,b3,c3] ], return a list [ a, b, c] where a = avg of a1, a2, a3, etc.''' d = rezip(complexList) return [ reduce(lambda x,y:x+y, z)/(len(z)*1.0) for z in d ] ## requires positive values (0 counts) def max_value_in_list(list): max_index = 0 max_value = -1 for i in range(len(list)): if list[i] > max_value: max_value = list[i] max_index = i return max_value def max_index_in_list(list): max_index = 0 max_value = -1 for i in range(len(list)): if list[i] > max_value: max_value = list[i] max_index = i return max_index def min_value_in_list(list): min_index = 0 min_value = 99999999 for i in range(len(list)): if list[i] < min_value: min_value = list[i] return min_value
# Reference: # http://code.activestate.com/recipes/278258/ def sumList(L): return reduce(lambda x,y:x+y, L) def avgList(L): return reduce(lambda x,y:x+y, L) /(len(L)*1.0) def normList(L, normalizeTo=1): '''normalize values of a list to make its max = normalizeTo''' vMax = max(L) return [ x/(vMax*1.0)*normalizeTo for x in L] def normListSumTo(L, sumTo=1): '''normalize values of a list to make it sum = sumTo''' sum = reduce(lambda x,y:x+y, L) return [ x/(sum*1.0)*sumTo for x in L] def accumList(L, normalizeTo=None): ''' L= [1, 2, 3, 4, 5]: accumList(L)=> [1, 3, 6, 10, 15] L= [0.25, 0.25, 0.25, 0.25]: accumList(L)=> [0.25, 0.50, 0.75, 1.00] normalizeTo: set the last number of the returned list to this value ''' if normalizeTo: LL = normListSumTo(L, sumTo=normalizeTo) else: LL = L[:] r = range(1, len(LL)) newList=[LL[0]] for i in r: newList.append( newList[-1]+ LL[i] ) return newList def findIndex(sortedList, x, indexBuffer=0): ''' Given a sortedList and value x, return the index i where sortedList[i-1] <= x < sortedList[i] Which means, sortedList.insert( findIndex(sortedList, x), x ) will give a sorted list ''' if len(sortedList)==2: if x==sortedList[-1]: return indexBuffer+2 elif x>=sortedList[0]: return indexBuffer+1 else: L = len(sortedList) firstHalf = sortedList[:L/2+1] secondHalf = sortedList[(L/2):] if secondHalf[-1]<=x: return indexBuffer + len(sortedList) elif x< firstHalf[0]: return indexBuffer else: if firstHalf[-1] < x: return findIndex(secondHalf, x, indexBuffer=L/2+indexBuffer) else: return findIndex(firstHalf,x, indexBuffer=indexBuffer) def randomPickList(L): ''' given a list L, with all values are numbers, randomly pick an item and return it's index according to the percentage of all values''' return findIndex(accumList(L,1), random.random()) def deepList(LString): ''' Given string representation of a nested list tree, return a list containing all the deepest list contents. For example: '[[1,[2, 2a]],[[3,3b],4]]' ==> ['2, 2a', '3,3b'] '[[[1,[2, 2a]],[[3,3b],4]],6]' ==> ['2, 2a', '3,3b'] '[[[[a1,a2],out],o1],[o2,o3]]' ==> ['a1,a2', 'o2,o3'] '[[[[[a1,a2], out], [o1,o2]],[o3,o4]],[o5,o6]]' ==> ['a1,a2', 'o1,o2', 'o3,o4', 'o5,o6'] The code: [x.split(']') for x in code.split('[')] returns something like: [[''], [''], [''], [''], [''], ['a1,a2', ', out', ', '], ['o1,o2', '', ','], ['o3,o4', '', ','], ['o5,o6', '', '']] ''' result= [x[0] for x in \ [x.split(']') for x in LString.split('[')] \ if len(x)>1] if result==['']: result =[] return result def getListStartsWith(aList, startsWith, isStrip=1): ''' for a list: L= ['abcdef', 'kkddff', 'xyz', '0wer'...], getListStartWith(L, 'kk') will return: ['kkddff', 'xyz', '0wer'...], getListStartWith(L, 'xy') will return: ['xyz', '0wer'...], if isStrip: any item ' xyz' will be considered 'xyz' else: the spaces in ' xyz' count. ''' tmp = aList[:] if isStrip: tmp = [x.strip() for x in tmp] startLineIndex = 0 for i in range(len(tmp)): if tmp[i].startswith(startsWith): startLineIndex = i return aList[startLineIndex:] def rezip(aList): ''' d = [[1, 5, 8, 3], [2, 2, 3, 9], [3, 2, 4, 6]] rezip(d): [(1, 2, 3), (5, 2, 2), (8, 3, 4), (3, 9, 6)] If a =[1, 5, 8], b=[2, 2, 3], c=[3, 2, 4] then it's eazy to: zip(a,b,c) = [(1, 2, 3), (5, 2, 2), (8, 3, 4)] But it's hard for d = [[1, 5, 8], [2, 2, 3], [3, 2, 4]] ''' tmp = [ [] for x in range(len(aList[0])) ] for i in range(len(aList[0])): for j in range(len(aList)): tmp[i].append(aList[j][i]) return tmp def sumInList(complexList): ''' Given a complexList [ [a1,b1,c1], [a2,b2,c2], [a3,b3,c3] ], return a list [ a, b, c] where a = a1+a2+a3, etc.''' d = rezip(complexList) return [ reduce(lambda x,y:x+y, z) for z in d ] def avgInList(complexList): ''' Given a complexList [ [a1,b1,c1], [a2,b2,c2], [a3,b3,c3] ], return a list [ a, b, c] where a = avg of a1, a2, a3, etc.''' d = rezip(complexList) return [ reduce(lambda x,y:x+y, z)/(len(z)*1.0) for z in d ] ## requires positive values (0 counts) def max_value_in_list(list): max_index = 0 max_value = -1 for i in range(len(list)): if list[i] > max_value: max_value = list[i] max_index = i return max_value def max_index_in_list(list): max_index = 0 max_value = -1 for i in range(len(list)): if list[i] > max_value: max_value = list[i] max_index = i return max_index def min_value_in_list(list): min_index = 0 min_value = 99999999 for i in range(len(list)): if list[i] < min_value: min_value = list[i] return min_value
en
0.466604
# Reference: # http://code.activestate.com/recipes/278258/ normalize values of a list to make its max = normalizeTo normalize values of a list to make it sum = sumTo L= [1, 2, 3, 4, 5]: accumList(L)=> [1, 3, 6, 10, 15] L= [0.25, 0.25, 0.25, 0.25]: accumList(L)=> [0.25, 0.50, 0.75, 1.00] normalizeTo: set the last number of the returned list to this value Given a sortedList and value x, return the index i where sortedList[i-1] <= x < sortedList[i] Which means, sortedList.insert( findIndex(sortedList, x), x ) will give a sorted list given a list L, with all values are numbers, randomly pick an item and return it's index according to the percentage of all values Given string representation of a nested list tree, return a list containing all the deepest list contents. For example: '[[1,[2, 2a]],[[3,3b],4]]' ==> ['2, 2a', '3,3b'] '[[[1,[2, 2a]],[[3,3b],4]],6]' ==> ['2, 2a', '3,3b'] '[[[[a1,a2],out],o1],[o2,o3]]' ==> ['a1,a2', 'o2,o3'] '[[[[[a1,a2], out], [o1,o2]],[o3,o4]],[o5,o6]]' ==> ['a1,a2', 'o1,o2', 'o3,o4', 'o5,o6'] The code: [x.split(']') for x in code.split('[')] returns something like: [[''], [''], [''], [''], [''], ['a1,a2', ', out', ', '], ['o1,o2', '', ','], ['o3,o4', '', ','], ['o5,o6', '', '']] for a list: L= ['abcdef', 'kkddff', 'xyz', '0wer'...], getListStartWith(L, 'kk') will return: ['kkddff', 'xyz', '0wer'...], getListStartWith(L, 'xy') will return: ['xyz', '0wer'...], if isStrip: any item ' xyz' will be considered 'xyz' else: the spaces in ' xyz' count. d = [[1, 5, 8, 3], [2, 2, 3, 9], [3, 2, 4, 6]] rezip(d): [(1, 2, 3), (5, 2, 2), (8, 3, 4), (3, 9, 6)] If a =[1, 5, 8], b=[2, 2, 3], c=[3, 2, 4] then it's eazy to: zip(a,b,c) = [(1, 2, 3), (5, 2, 2), (8, 3, 4)] But it's hard for d = [[1, 5, 8], [2, 2, 3], [3, 2, 4]] Given a complexList [ [a1,b1,c1], [a2,b2,c2], [a3,b3,c3] ], return a list [ a, b, c] where a = a1+a2+a3, etc. Given a complexList [ [a1,b1,c1], [a2,b2,c2], [a3,b3,c3] ], return a list [ a, b, c] where a = avg of a1, a2, a3, etc. ## requires positive values (0 counts)
3.32148
3
appspotify/pytify/core/album.py
DiegoSantosWS/spotfy-py
0
6625767
<reponame>DiegoSantosWS/spotfy-py<filename>appspotify/pytify/core/album.py from .parameter import prepare_params from .request import execute_request def get_album_tracks(album_id, auth, params=None): if album_id is None or album_id is '': raise AttributeError( 'Parameter `album_id` cannot be `None` or empty.') url_template = '{base_url}/{area}/{albumid}/{postfix}{query}' url_params = { 'query': prepare_params(params), 'area': 'albums', 'albumid': album_id, 'postfix': 'tracks', } return execute_request(url_template, auth, url_params)
from .parameter import prepare_params from .request import execute_request def get_album_tracks(album_id, auth, params=None): if album_id is None or album_id is '': raise AttributeError( 'Parameter `album_id` cannot be `None` or empty.') url_template = '{base_url}/{area}/{albumid}/{postfix}{query}' url_params = { 'query': prepare_params(params), 'area': 'albums', 'albumid': album_id, 'postfix': 'tracks', } return execute_request(url_template, auth, url_params)
none
1
2.423047
2
collection/clientlib/base.py
WilkinsonK/python-collections
0
6625768
<reponame>WilkinsonK/python-collections<filename>collection/clientlib/base.py import functools from abc import ABC, abstractmethod from clientlib.enums import Method from clientlib.errors import HTTPError from clientlib.mixins import ClientInitMixIn, ClientValidationMixIn from clientlib.typedefs import Response, Session def not_implemented(method): """ Raise a not implemented error if method returns 'NotImplemented' type. """ @functools.wraps(method) def inner(*args, **kwargs): result = method(*args, **kwargs) if result is NotImplemented: raise_not_implemented() return result def raise_not_implemented(): message = f"method {method!r} has not been implemented yet!" raise NotImplementedError(message) return inner class BaseClient(ClientInitMixIn, ClientValidationMixIn, ABC): def _init(self, *args, **kwargs): super()._init(*args, **kwargs) self.healthcheck() def _send(self, method, endpoint, **kwargs): root_url, timeout, kwargs = self._parse_send_kwargs(**kwargs) method, address = self._parse_send_args(method, root_url, endpoint) return self.session.request( method, url=address, timeout=timeout, **kwargs) def _parse_send_address(self, root_url, endpoint): address = "/".join([root_url, endpoint or ""]) return address def _parse_send_args(self, method, root_url, endpoint): address = self._parse_send_address(root_url, endpoint) method = self._parse_send_method(method) return method, address def _parse_send_kwargs(self, **kwargs): timeout = kwargs.pop("max_timeout", self.max_timeout) root_url = kwargs.pop("root_url", self.root_url) return root_url, timeout, kwargs def _parse_send_method(self, method): if method.__class__ in (str, Method): return str(method) return NotImplemented @property def session(self) -> Session: return self._session def __enter__(self): return self def __exit__(self, type, value, traceback): self.session.close() @abstractmethod @not_implemented def handle_http_error(self, error: HTTPError, resp: Response = None) -> None: """ Not implemented here. Handle http protocol errors. """ return NotImplemented @abstractmethod @not_implemented def healthcheck(self) -> int: """ Not implemented here. Send a health check ping to api reference. """ return NotImplemented @abstractmethod @not_implemented def refresh(self, **kwargs) -> None: """ Not implemented here. Reset the client session. """ return NotImplemented @abstractmethod @not_implemented def send(self, method: Method, endpoint: str = None, data: dict = None, **kwargs) -> Response: """ Not implemented here. Send a request using the ApiClient settings. """ return NotImplemented
import functools from abc import ABC, abstractmethod from clientlib.enums import Method from clientlib.errors import HTTPError from clientlib.mixins import ClientInitMixIn, ClientValidationMixIn from clientlib.typedefs import Response, Session def not_implemented(method): """ Raise a not implemented error if method returns 'NotImplemented' type. """ @functools.wraps(method) def inner(*args, **kwargs): result = method(*args, **kwargs) if result is NotImplemented: raise_not_implemented() return result def raise_not_implemented(): message = f"method {method!r} has not been implemented yet!" raise NotImplementedError(message) return inner class BaseClient(ClientInitMixIn, ClientValidationMixIn, ABC): def _init(self, *args, **kwargs): super()._init(*args, **kwargs) self.healthcheck() def _send(self, method, endpoint, **kwargs): root_url, timeout, kwargs = self._parse_send_kwargs(**kwargs) method, address = self._parse_send_args(method, root_url, endpoint) return self.session.request( method, url=address, timeout=timeout, **kwargs) def _parse_send_address(self, root_url, endpoint): address = "/".join([root_url, endpoint or ""]) return address def _parse_send_args(self, method, root_url, endpoint): address = self._parse_send_address(root_url, endpoint) method = self._parse_send_method(method) return method, address def _parse_send_kwargs(self, **kwargs): timeout = kwargs.pop("max_timeout", self.max_timeout) root_url = kwargs.pop("root_url", self.root_url) return root_url, timeout, kwargs def _parse_send_method(self, method): if method.__class__ in (str, Method): return str(method) return NotImplemented @property def session(self) -> Session: return self._session def __enter__(self): return self def __exit__(self, type, value, traceback): self.session.close() @abstractmethod @not_implemented def handle_http_error(self, error: HTTPError, resp: Response = None) -> None: """ Not implemented here. Handle http protocol errors. """ return NotImplemented @abstractmethod @not_implemented def healthcheck(self) -> int: """ Not implemented here. Send a health check ping to api reference. """ return NotImplemented @abstractmethod @not_implemented def refresh(self, **kwargs) -> None: """ Not implemented here. Reset the client session. """ return NotImplemented @abstractmethod @not_implemented def send(self, method: Method, endpoint: str = None, data: dict = None, **kwargs) -> Response: """ Not implemented here. Send a request using the ApiClient settings. """ return NotImplemented
en
0.701957
Raise a not implemented error if method returns 'NotImplemented' type. Not implemented here. Handle http protocol errors. Not implemented here. Send a health check ping to api reference. Not implemented here. Reset the client session. Not implemented here. Send a request using the ApiClient settings.
2.349908
2
simulation_ws/src/ros2_robot_simulation/launch/launch.py
samuk/ANI717_Robotics
0
6625769
#!/usr/bin/env python # -*- coding: utf-8 -*- """ROS2 Robot Simulation Launch File. This script simulates a robot in Gazebo simulation. Revision History: 2021-10-23 (Animesh): Baseline Software. Example: $ colcon build && source install/setup.bash && ros2 launch ros2_robot_simulation launch.py $ source install/setup.bash && ros2 launch ros2_robot_simulation launch.py $ ros2 launch ros2_robot_simulation launch.py """ #___Import Modules: import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.substitutions import LaunchConfiguration from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription from launch.launch_description_sources import PythonLaunchDescriptionSource from launch_ros.actions import Node #___Function: def generate_launch_description(): # Get the package directory ros2_world_simulation_dir = get_package_share_directory('ros2_world_simulation') ros2_robot_simulation_dir = get_package_share_directory('ros2_robot_simulation') # Create launch configuration variables use_simulator = LaunchConfiguration('use_simulator') headless = LaunchConfiguration('headless') world = LaunchConfiguration('world') x_pos = LaunchConfiguration('x_pos') y_pos = LaunchConfiguration('y_pos') z_pos = LaunchConfiguration('z_pos') roll = LaunchConfiguration('roll') pitch = LaunchConfiguration('pitch') yaw = LaunchConfiguration('yaw') urdf_file = LaunchConfiguration('urdf_file') # Declare the launch arguments declare_use_simulator_cmd = DeclareLaunchArgument( 'use_simulator', default_value='True', description='Whether to start the simulator') declare_simulator_cmd = DeclareLaunchArgument( 'headless', default_value='False', description='Whether to execute gzclient)') declare_world_cmd = DeclareLaunchArgument( 'world', default_value=os.path.join(ros2_world_simulation_dir, 'worlds', 'empty.world'), description='Full path to world model file to load') declare_x_pos_cmd = DeclareLaunchArgument( 'x_pos', default_value='0.0') declare_y_pos_cmd = DeclareLaunchArgument( 'y_pos', default_value='0.0') declare_z_pos_cmd = DeclareLaunchArgument( 'z_pos', default_value='0.0') declare_roll_cmd = DeclareLaunchArgument( 'roll', default_value='0.0') declare_pitch_cmd = DeclareLaunchArgument( 'pitch', default_value='0.0') declare_yaw_cmd = DeclareLaunchArgument( 'yaw', default_value='0.0') declare_urdf_file_cmd = DeclareLaunchArgument( 'urdf_file', default_value='jetbot.urdf') # Specify the actions world_launch_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource(os.path.join(ros2_world_simulation_dir, 'launch', 'launch.py')), launch_arguments={'use_simulator': use_simulator, 'headless': headless, 'world': world}.items()) spawn_robot_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource(os.path.join(ros2_robot_simulation_dir, 'launch', 'spawn.py')), launch_arguments={'x_pos': x_pos, 'y_pos': y_pos, 'z_pos': z_pos, 'roll': roll, 'pitch': pitch, 'yaw': yaw, 'urdf': urdf_file}.items()) robot_states_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource(os.path.join(ros2_robot_simulation_dir, 'launch', 'states.py')), launch_arguments={'urdf': urdf_file,}.items()) # Create the launch description and populate ld = LaunchDescription() # Declare the launch options ld.add_action(declare_use_simulator_cmd) ld.add_action(declare_simulator_cmd) ld.add_action(declare_world_cmd) ld.add_action(declare_x_pos_cmd) ld.add_action(declare_y_pos_cmd) ld.add_action(declare_z_pos_cmd) ld.add_action(declare_roll_cmd) ld.add_action(declare_pitch_cmd) ld.add_action(declare_yaw_cmd) ld.add_action(declare_urdf_file_cmd) # Add all actions ld.add_action(world_launch_cmd) ld.add_action(spawn_robot_cmd) ld.add_action(robot_states_cmd) return ld # # end of file """ANI717"""
#!/usr/bin/env python # -*- coding: utf-8 -*- """ROS2 Robot Simulation Launch File. This script simulates a robot in Gazebo simulation. Revision History: 2021-10-23 (Animesh): Baseline Software. Example: $ colcon build && source install/setup.bash && ros2 launch ros2_robot_simulation launch.py $ source install/setup.bash && ros2 launch ros2_robot_simulation launch.py $ ros2 launch ros2_robot_simulation launch.py """ #___Import Modules: import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.substitutions import LaunchConfiguration from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription from launch.launch_description_sources import PythonLaunchDescriptionSource from launch_ros.actions import Node #___Function: def generate_launch_description(): # Get the package directory ros2_world_simulation_dir = get_package_share_directory('ros2_world_simulation') ros2_robot_simulation_dir = get_package_share_directory('ros2_robot_simulation') # Create launch configuration variables use_simulator = LaunchConfiguration('use_simulator') headless = LaunchConfiguration('headless') world = LaunchConfiguration('world') x_pos = LaunchConfiguration('x_pos') y_pos = LaunchConfiguration('y_pos') z_pos = LaunchConfiguration('z_pos') roll = LaunchConfiguration('roll') pitch = LaunchConfiguration('pitch') yaw = LaunchConfiguration('yaw') urdf_file = LaunchConfiguration('urdf_file') # Declare the launch arguments declare_use_simulator_cmd = DeclareLaunchArgument( 'use_simulator', default_value='True', description='Whether to start the simulator') declare_simulator_cmd = DeclareLaunchArgument( 'headless', default_value='False', description='Whether to execute gzclient)') declare_world_cmd = DeclareLaunchArgument( 'world', default_value=os.path.join(ros2_world_simulation_dir, 'worlds', 'empty.world'), description='Full path to world model file to load') declare_x_pos_cmd = DeclareLaunchArgument( 'x_pos', default_value='0.0') declare_y_pos_cmd = DeclareLaunchArgument( 'y_pos', default_value='0.0') declare_z_pos_cmd = DeclareLaunchArgument( 'z_pos', default_value='0.0') declare_roll_cmd = DeclareLaunchArgument( 'roll', default_value='0.0') declare_pitch_cmd = DeclareLaunchArgument( 'pitch', default_value='0.0') declare_yaw_cmd = DeclareLaunchArgument( 'yaw', default_value='0.0') declare_urdf_file_cmd = DeclareLaunchArgument( 'urdf_file', default_value='jetbot.urdf') # Specify the actions world_launch_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource(os.path.join(ros2_world_simulation_dir, 'launch', 'launch.py')), launch_arguments={'use_simulator': use_simulator, 'headless': headless, 'world': world}.items()) spawn_robot_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource(os.path.join(ros2_robot_simulation_dir, 'launch', 'spawn.py')), launch_arguments={'x_pos': x_pos, 'y_pos': y_pos, 'z_pos': z_pos, 'roll': roll, 'pitch': pitch, 'yaw': yaw, 'urdf': urdf_file}.items()) robot_states_cmd = IncludeLaunchDescription( PythonLaunchDescriptionSource(os.path.join(ros2_robot_simulation_dir, 'launch', 'states.py')), launch_arguments={'urdf': urdf_file,}.items()) # Create the launch description and populate ld = LaunchDescription() # Declare the launch options ld.add_action(declare_use_simulator_cmd) ld.add_action(declare_simulator_cmd) ld.add_action(declare_world_cmd) ld.add_action(declare_x_pos_cmd) ld.add_action(declare_y_pos_cmd) ld.add_action(declare_z_pos_cmd) ld.add_action(declare_roll_cmd) ld.add_action(declare_pitch_cmd) ld.add_action(declare_yaw_cmd) ld.add_action(declare_urdf_file_cmd) # Add all actions ld.add_action(world_launch_cmd) ld.add_action(spawn_robot_cmd) ld.add_action(robot_states_cmd) return ld # # end of file """ANI717"""
en
0.511068
#!/usr/bin/env python # -*- coding: utf-8 -*- ROS2 Robot Simulation Launch File. This script simulates a robot in Gazebo simulation. Revision History: 2021-10-23 (Animesh): Baseline Software. Example: $ colcon build && source install/setup.bash && ros2 launch ros2_robot_simulation launch.py $ source install/setup.bash && ros2 launch ros2_robot_simulation launch.py $ ros2 launch ros2_robot_simulation launch.py #___Import Modules: #___Function: # Get the package directory # Create launch configuration variables # Declare the launch arguments # Specify the actions # Create the launch description and populate # Declare the launch options # Add all actions # # end of file ANI717
2.215135
2
zillowdb/packages/sfm/str_encoding.py
MacHu-GWU/zillowdb-project
0
6625770
<reponame>MacHu-GWU/zillowdb-project #!/usr/bin/env python # -*- coding: utf-8 -*- import base64 def encode_base64_urlsafe(text): """Convert any utf-8 string to url safe string using base64 encoding. **中文文档** 将任意utf-8字符串用base64编码算法编码为纯数字和字母。 """ return base64.urlsafe_b64encode(text.encode("utf-8")).decode("utf-8") def decode_base64_urlsafe(text): """Reverse operation of :func:`encode_base64_urlsafe`. **中文文档** 将base64字符串解码为原字符串。 """ return base64.urlsafe_b64decode(text.encode("utf-8")).decode("utf-8")
#!/usr/bin/env python # -*- coding: utf-8 -*- import base64 def encode_base64_urlsafe(text): """Convert any utf-8 string to url safe string using base64 encoding. **中文文档** 将任意utf-8字符串用base64编码算法编码为纯数字和字母。 """ return base64.urlsafe_b64encode(text.encode("utf-8")).decode("utf-8") def decode_base64_urlsafe(text): """Reverse operation of :func:`encode_base64_urlsafe`. **中文文档** 将base64字符串解码为原字符串。 """ return base64.urlsafe_b64decode(text.encode("utf-8")).decode("utf-8")
zh
0.478128
#!/usr/bin/env python # -*- coding: utf-8 -*- Convert any utf-8 string to url safe string using base64 encoding. **中文文档** 将任意utf-8字符串用base64编码算法编码为纯数字和字母。 Reverse operation of :func:`encode_base64_urlsafe`. **中文文档** 将base64字符串解码为原字符串。
2.961841
3
unit_tests.py
ccubed/OTPy
2
6625771
import unittest from otpy.hotp import hotp from otpy.totp import totp class TestHotp(unittest.TestCase): def setUp(self): self.expected = [755224, 287082, 359152, 969429, 338314, 254676, 287922, 162583, 399871, 520489] self.instance = hotp("12345678901234567890", 0, 6) def test_rfc4226(self): for x in range(10): self.assertEqual(self.instance.at(x), str(self.expected[x])) for x in range(10): self.assertEqual(self.instance.next(), str(self.expected[x])) for x in range(10): self.assertTrue(self.instance.verify(str(self.expected[x]), x)) self.assertEqual(self.instance.drift(3, 1, 1), ['359152', '969429', '338314']) class TestTotp(unittest.TestCase): def setUp(self): self.instance = totp("12345678901234567890", 15108406016, 30, 8) def test_rfc6238_sha1(self): self.assertTrue(self.instance.verify_seconds("94287082", 59)) self.assertTrue(self.instance.verify_seconds("07081804", 1111111109)) self.assertTrue(self.instance.verify_seconds("14050471", 1111111111)) self.assertTrue(self.instance.verify_seconds("89005924", 1234567890)) self.assertTrue(self.instance.verify_seconds("69279037", 2000000000)) self.assertTrue(self.instance.verify_seconds("65353130", 20000000000))
import unittest from otpy.hotp import hotp from otpy.totp import totp class TestHotp(unittest.TestCase): def setUp(self): self.expected = [755224, 287082, 359152, 969429, 338314, 254676, 287922, 162583, 399871, 520489] self.instance = hotp("12345678901234567890", 0, 6) def test_rfc4226(self): for x in range(10): self.assertEqual(self.instance.at(x), str(self.expected[x])) for x in range(10): self.assertEqual(self.instance.next(), str(self.expected[x])) for x in range(10): self.assertTrue(self.instance.verify(str(self.expected[x]), x)) self.assertEqual(self.instance.drift(3, 1, 1), ['359152', '969429', '338314']) class TestTotp(unittest.TestCase): def setUp(self): self.instance = totp("12345678901234567890", 15108406016, 30, 8) def test_rfc6238_sha1(self): self.assertTrue(self.instance.verify_seconds("94287082", 59)) self.assertTrue(self.instance.verify_seconds("07081804", 1111111109)) self.assertTrue(self.instance.verify_seconds("14050471", 1111111111)) self.assertTrue(self.instance.verify_seconds("89005924", 1234567890)) self.assertTrue(self.instance.verify_seconds("69279037", 2000000000)) self.assertTrue(self.instance.verify_seconds("65353130", 20000000000))
none
1
2.639287
3
cinder/zonemanager/drivers/cisco/cisco_fc_zone_driver.py
hashsos/hashcloudos-cinder
0
6625772
<filename>cinder/zonemanager/drivers/cisco/cisco_fc_zone_driver.py<gh_stars>0 # (c) Copyright 2014 Cisco Systems Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # """ Cisco Zone Driver is responsible to manage access control using FC zoning for Cisco FC fabrics. This is a concrete implementation of FCZoneDriver interface implementing add_connection and delete_connection interfaces. **Related Flags** :zone_activate: Used by: class: 'FCZoneDriver'. Defaults to True :zone_name_prefix: Used by: class: 'FCZoneDriver'. Defaults to 'openstack' """ from oslo_concurrency import lockutils from oslo_config import cfg from oslo_log import log as logging from oslo_utils import excutils from oslo_utils import importutils import six import string from cinder import exception from cinder.i18n import _ from cinder import interface from cinder.zonemanager.drivers.cisco import cisco_fabric_opts as fabric_opts from cinder.zonemanager.drivers.cisco import fc_zone_constants as ZoneConstant from cinder.zonemanager.drivers import driver_utils from cinder.zonemanager.drivers import fc_zone_driver from cinder.zonemanager import utils as zm_utils LOG = logging.getLogger(__name__) SUPPORTED_CHARS = string.ascii_letters + string.digits + '$' + '-' + '^' + '_' cisco_opts = [ cfg.StrOpt('cisco_sb_connector', default='cinder.zonemanager.drivers.cisco' '.cisco_fc_zone_client_cli.CiscoFCZoneClientCLI', help='Southbound connector for zoning operation'), ] CONF = cfg.CONF CONF.register_opts(cisco_opts, group='fc-zone-manager') @interface.fczmdriver class CiscoFCZoneDriver(fc_zone_driver.FCZoneDriver): """Cisco FC zone driver implementation. OpenStack Fibre Channel zone driver to manage FC zoning in Cisco SAN fabrics. Version history: 1.0 - Initial Cisco FC zone driver 1.1 - Added friendly zone name support """ VERSION = "1.1.0" # ThirdPartySystems wiki name CI_WIKI_NAME = "Cisco_ZM_CI" # TODO(jsbryant) Remove driver in Rocky if CI is not fixed SUPPORTED = False def __init__(self, **kwargs): super(CiscoFCZoneDriver, self).__init__(**kwargs) self.configuration = kwargs.get('configuration', None) if self.configuration: self.configuration.append_config_values(cisco_opts) # Adding a hack to handle parameters from super classes # in case configured with multi backends. fabric_names = self.configuration.safe_get('fc_fabric_names') activate = self.configuration.safe_get('cisco_zone_activate') prefix = self.configuration.safe_get('cisco_zone_name_prefix') base_san_opts = [] if not fabric_names: base_san_opts.append( cfg.StrOpt('fc_fabric_names', help='Comma separated list of fibre channel ' 'fabric names. This list of names is used to' ' retrieve other SAN credentials for connecting' ' to each SAN fabric' )) if not activate: base_san_opts.append( cfg.BoolOpt('cisco_zone_activate', default=True, help='Indicates whether zone should ' 'be activated or not')) if not prefix: base_san_opts.append( cfg.StrOpt('cisco_zone_name_prefix', default="openstack", help="A prefix to be used when naming zone")) if len(base_san_opts) > 0: CONF.register_opts(base_san_opts) self.configuration.append_config_values(base_san_opts) fabric_names = [x.strip() for x in self. configuration.fc_fabric_names.split(',')] # There can be more than one SAN in the network and we need to # get credentials for each SAN. if fabric_names: self.fabric_configs = fabric_opts.load_fabric_configurations( fabric_names) @lockutils.synchronized('cisco', 'fcfabric-', True) def add_connection(self, fabric, initiator_target_map, host_name=None, storage_system=None): """Concrete implementation of add_connection. Based on zoning policy and state of each I-T pair, list of zone members are created and pushed to the fabric to add zones. The new zones created or zones updated are activated based on isActivate flag set in cinder.conf returned by volume driver after attach operation. :param fabric: Fabric name from cinder.conf file :param initiator_target_map: Mapping of initiator to list of targets """ LOG.debug("Add connection for Fabric: %s", fabric) LOG.info("CiscoFCZoneDriver - Add connection " "for I-T map: %s", initiator_target_map) fabric_ip = self.fabric_configs[fabric].safe_get( 'cisco_fc_fabric_address') fabric_user = self.fabric_configs[fabric].safe_get( 'cisco_fc_fabric_user') fabric_pwd = self.fabric_configs[fabric].safe_get( 'cisco_fc_fabric_password') fabric_port = self.fabric_configs[fabric].safe_get( 'cisco_fc_fabric_port') zoning_policy = self.configuration.zoning_policy zoning_policy_fab = self.fabric_configs[fabric].safe_get( 'cisco_zoning_policy') if zoning_policy_fab: zoning_policy = zoning_policy_fab zoning_vsan = self.fabric_configs[fabric].safe_get('cisco_zoning_vsan') LOG.info("Zoning policy for Fabric %s", zoning_policy) statusmap_from_fabric = self.get_zoning_status( fabric_ip, fabric_user, fabric_pwd, fabric_port, zoning_vsan) if statusmap_from_fabric.get('session') == 'none': cfgmap_from_fabric = self.get_active_zone_set( fabric_ip, fabric_user, fabric_pwd, fabric_port, zoning_vsan) zone_names = [] if cfgmap_from_fabric.get('zones'): zone_names = cfgmap_from_fabric['zones'].keys() # based on zoning policy, create zone member list and # push changes to fabric. for initiator_key in initiator_target_map.keys(): zone_map = {} zone_update_map = {} initiator = initiator_key.lower() t_list = initiator_target_map[initiator_key] if zoning_policy == 'initiator-target': for t in t_list: target = t.lower() zone_members = [ zm_utils.get_formatted_wwn(initiator), zm_utils.get_formatted_wwn(target)] zone_name = ( driver_utils.get_friendly_zone_name( zoning_policy, initiator, target, host_name, storage_system, self.configuration.cisco_zone_name_prefix, SUPPORTED_CHARS)) if (len(cfgmap_from_fabric) == 0 or ( zone_name not in zone_names)): zone_map[zone_name] = zone_members else: # This is I-T zoning, skip if zone exists. LOG.info("Zone exists in I-T mode. " "Skipping zone creation %s", zone_name) elif zoning_policy == 'initiator': zone_members = [ zm_utils.get_formatted_wwn(initiator)] for t in t_list: target = t.lower() zone_members.append( zm_utils.get_formatted_wwn(target)) zone_name = ( driver_utils.get_friendly_zone_name( zoning_policy, initiator, target, host_name, storage_system, self.configuration.cisco_zone_name_prefix, SUPPORTED_CHARS)) # If zone exists, then perform an update_zone and add # new members into existing zone. if zone_name and (zone_name in zone_names): zone_members = filter( lambda x: x not in cfgmap_from_fabric['zones'][zone_name], zone_members) if zone_members: zone_update_map[zone_name] = zone_members else: zone_map[zone_name] = zone_members else: msg = _("Zoning Policy: %s, not" " recognized") % zoning_policy LOG.error(msg) raise exception.FCZoneDriverException(msg) LOG.info("Zone map to add: %(zone_map)s", {'zone_map': zone_map}) LOG.info("Zone map to update add: %(zone_update_map)s", {'zone_update_map': zone_update_map}) if zone_map or zone_update_map: conn = None try: conn = importutils.import_object( self.configuration.cisco_sb_connector, ipaddress=fabric_ip, username=fabric_user, password=<PASSWORD>, port=fabric_port, vsan=zoning_vsan) if zone_map: conn.add_zones( zone_map, self.configuration.cisco_zone_activate, zoning_vsan, cfgmap_from_fabric, statusmap_from_fabric) if zone_update_map: conn.update_zones( zone_update_map, self.configuration.cisco_zone_activate, zoning_vsan, ZoneConstant.ZONE_ADD, cfgmap_from_fabric, statusmap_from_fabric) conn.cleanup() except exception.CiscoZoningCliException as cisco_ex: msg = _("Exception: %s") % six.text_type(cisco_ex) raise exception.FCZoneDriverException(msg) except Exception: msg = _("Failed to add zoning configuration.") LOG.exception(msg) raise exception.FCZoneDriverException(msg) LOG.debug("Zones added successfully: %s", zone_map) else: LOG.debug("Zones already exist - Initiator Target Map: %s", initiator_target_map) else: LOG.debug("Zoning session exists VSAN: %s", zoning_vsan) @lockutils.synchronized('cisco', 'fcfabric-', True) def delete_connection(self, fabric, initiator_target_map, host_name=None, storage_system=None): """Concrete implementation of delete_connection. Based on zoning policy and state of each I-T pair, list of zones are created for deletion. The zones are either updated deleted based on the policy and attach/detach state of each I-T pair. :param fabric: Fabric name from cinder.conf file :param initiator_target_map: Mapping of initiator to list of targets """ LOG.debug("Delete connection for fabric: %s", fabric) LOG.info("CiscoFCZoneDriver - Delete connection for I-T map: %s", initiator_target_map) fabric_ip = self.fabric_configs[fabric].safe_get( 'cisco_fc_fabric_address') fabric_user = self.fabric_configs[fabric].safe_get( 'cisco_fc_fabric_user') fabric_pwd = self.fabric_configs[fabric].safe_get( 'cisco_fc_fabric_password') fabric_port = self.fabric_configs[fabric].safe_get( 'cisco_fc_fabric_port') zoning_policy = self.configuration.zoning_policy zoning_policy_fab = self.fabric_configs[fabric].safe_get( 'cisco_zoning_policy') if zoning_policy_fab: zoning_policy = zoning_policy_fab zoning_vsan = self.fabric_configs[fabric].safe_get('cisco_zoning_vsan') LOG.info("Zoning policy for fabric %s", zoning_policy) statusmap_from_fabric = self.get_zoning_status( fabric_ip, fabric_user, fabric_pwd, fabric_port, zoning_vsan) if statusmap_from_fabric.get('session') == 'none': cfgmap_from_fabric = self.get_active_zone_set( fabric_ip, fabric_user, fabric_pwd, fabric_port, zoning_vsan) zone_names = [] if cfgmap_from_fabric.get('zones'): zone_names = cfgmap_from_fabric['zones'].keys() # Based on zoning policy, get zone member list and push # changes to fabric. This operation could result in an update # for zone config with new member list or deleting zones from # active cfg. LOG.debug("zone config from Fabric: %s", cfgmap_from_fabric) for initiator_key in initiator_target_map.keys(): initiator = initiator_key.lower() formatted_initiator = zm_utils.get_formatted_wwn(initiator) zone_update_map = {} zones_to_delete = [] t_list = initiator_target_map[initiator_key] if zoning_policy == 'initiator-target': # In this case, zone needs to be deleted. for t in t_list: target = t.lower() zone_name = ( driver_utils.get_friendly_zone_name( zoning_policy, initiator, target, host_name, storage_system, self.configuration.cisco_zone_name_prefix, SUPPORTED_CHARS)) LOG.debug("Zone name to del: %s", zone_name) if (len(zone_names) > 0 and (zone_name in zone_names)): # delete zone. LOG.debug("Added zone to delete to list: %s", zone_name) zones_to_delete.append(zone_name) elif zoning_policy == 'initiator': zone_members = [formatted_initiator] for t in t_list: target = t.lower() zone_members.append( zm_utils.get_formatted_wwn(target)) zone_name = driver_utils.get_friendly_zone_name( zoning_policy, initiator, target, host_name, storage_system, self.configuration.cisco_zone_name_prefix, SUPPORTED_CHARS) # Check if there are zone members leftover after removal if (zone_names and (zone_name in zone_names)): filtered_members = filter( lambda x: x not in zone_members, cfgmap_from_fabric['zones'][zone_name]) # The assumption here is that initiator is always # there in the zone as it is 'initiator' policy. # If filtered list is empty, we remove that zone. # If there are other members leftover, then perform # update_zone to remove targets LOG.debug("Zone delete - I mode: filtered targets: %s", filtered_members) if filtered_members: remove_members = filter( lambda x: x in cfgmap_from_fabric['zones'][zone_name], zone_members) if remove_members: # Do not want to remove the initiator remove_members.remove(formatted_initiator) LOG.debug("Zone members to remove: %s", remove_members) zone_update_map[zone_name] = remove_members LOG.debug("Filtered zone Map to update: %s", zone_update_map) else: zones_to_delete.append(zone_name) else: LOG.info("Zoning Policy: %s, not recognized", zoning_policy) LOG.debug("Zone map to remove update: %s", zone_update_map) LOG.debug("Final Zone list to delete: %s", zones_to_delete) conn = None try: conn = importutils.import_object( self.configuration.cisco_sb_connector, ipaddress=fabric_ip, username=fabric_user, password=<PASSWORD>, port=fabric_port, vsan=zoning_vsan) # Update zone membership. if zone_update_map: conn.update_zones( zone_update_map, self.configuration.cisco_zone_activate, zoning_vsan, ZoneConstant.ZONE_REMOVE, cfgmap_from_fabric, statusmap_from_fabric) # Delete zones ~sk. if zones_to_delete: zone_name_string = '' num_zones = len(zones_to_delete) for i in range(0, num_zones): if i == 0: zone_name_string = ('%s%s' % ( zone_name_string, zones_to_delete[i])) else: zone_name_string = ('%s%s%s' % ( zone_name_string, ';', zones_to_delete[i])) conn.delete_zones(zone_name_string, self.configuration. cisco_zone_activate, zoning_vsan, cfgmap_from_fabric, statusmap_from_fabric) conn.cleanup() except Exception: msg = _("Failed to update or delete zoning configuration") LOG.exception(msg) raise exception.FCZoneDriverException(msg) LOG.debug("Zones deleted successfully: %s", zone_update_map) else: LOG.debug("Zoning session exists VSAN: %s", zoning_vsan) def get_san_context(self, target_wwn_list): """Lookup SAN context for visible end devices. Look up each SAN configured and return a map of SAN (fabric IP) to list of target WWNs visible to the fabric. """ formatted_target_list = [] fabric_map = {} fabrics = [x.strip() for x in self. configuration.fc_fabric_names.split(',')] LOG.debug("Fabric List: %s", fabrics) LOG.debug("Target wwn List: %s", target_wwn_list) if len(fabrics) > 0: for t in target_wwn_list: formatted_target_list.append( zm_utils.get_formatted_wwn(t.lower())) LOG.debug("Formatted Target wwn List: %s", formatted_target_list) for fabric_name in fabrics: fabric_ip = self.fabric_configs[fabric_name].safe_get( 'cisco_fc_fabric_address') fabric_user = self.fabric_configs[fabric_name].safe_get( 'cisco_fc_fabric_user') fabric_pwd = self.fabric_configs[fabric_name].safe_get( 'cisco_fc_fabric_password') fabric_port = self.fabric_configs[fabric_name].safe_get( 'cisco_fc_fabric_port') zoning_vsan = self.fabric_configs[fabric_name].safe_get( 'cisco_zoning_vsan') # Get name server data from fabric and get the targets # logged in. nsinfo = None try: conn = importutils.import_object( self.configuration.cisco_sb_connector, ipaddress=fabric_ip, username=fabric_user, password=<PASSWORD>, port=fabric_port, vsan=zoning_vsan) nsinfo = conn.get_nameserver_info() LOG.debug("show fcns database info from fabric: %s", nsinfo) conn.cleanup() except exception.CiscoZoningCliException: with excutils.save_and_reraise_exception(): LOG.exception("Error getting show fcns database info.") except Exception: msg = _("Failed to get show fcns database info.") LOG.exception(msg) raise exception.FCZoneDriverException(msg) visible_targets = filter( lambda x: x in formatted_target_list, nsinfo) if visible_targets: LOG.info("Filtered targets for SAN is: %s", {fabric_name: visible_targets}) # getting rid of the ':' before returning for idx, elem in enumerate(visible_targets): visible_targets[idx] = six.text_type( visible_targets[idx]).replace(':', '') fabric_map[fabric_name] = visible_targets else: LOG.debug("No targets are in the fcns info for SAN %s", fabric_name) LOG.debug("Return SAN context output: %s", fabric_map) return fabric_map def get_active_zone_set(self, fabric_ip, fabric_user, fabric_pwd, fabric_port, zoning_vsan): """Gets active zoneset config for vsan.""" cfgmap = {} conn = None try: LOG.debug("Southbound connector: %s", self.configuration.cisco_sb_connector) conn = importutils.import_object( self.configuration.cisco_sb_connector, ipaddress=fabric_ip, username=fabric_user, password=<PASSWORD>, port=fabric_port, vsan=zoning_vsan) cfgmap = conn.get_active_zone_set() conn.cleanup() except Exception: msg = _("Failed to access active zoning configuration.") LOG.exception(msg) raise exception.FCZoneDriverException(msg) LOG.debug("Active zone set from fabric: %s", cfgmap) return cfgmap def get_zoning_status(self, fabric_ip, fabric_user, fabric_pwd, fabric_port, zoning_vsan): """Gets zoneset status and mode.""" statusmap = {} conn = None try: LOG.debug("Southbound connector: %s", self.configuration.cisco_sb_connector) conn = importutils.import_object( self.configuration.cisco_sb_connector, ipaddress=fabric_ip, username=fabric_user, password=<PASSWORD>, port=fabric_port, vsan=zoning_vsan) statusmap = conn.get_zoning_status() conn.cleanup() except Exception: msg = _("Failed to access zoneset status:%s") LOG.exception(msg) raise exception.FCZoneDriverException(msg) LOG.debug("Zoneset status from fabric: %s", statusmap) return statusmap
<filename>cinder/zonemanager/drivers/cisco/cisco_fc_zone_driver.py<gh_stars>0 # (c) Copyright 2014 Cisco Systems Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # """ Cisco Zone Driver is responsible to manage access control using FC zoning for Cisco FC fabrics. This is a concrete implementation of FCZoneDriver interface implementing add_connection and delete_connection interfaces. **Related Flags** :zone_activate: Used by: class: 'FCZoneDriver'. Defaults to True :zone_name_prefix: Used by: class: 'FCZoneDriver'. Defaults to 'openstack' """ from oslo_concurrency import lockutils from oslo_config import cfg from oslo_log import log as logging from oslo_utils import excutils from oslo_utils import importutils import six import string from cinder import exception from cinder.i18n import _ from cinder import interface from cinder.zonemanager.drivers.cisco import cisco_fabric_opts as fabric_opts from cinder.zonemanager.drivers.cisco import fc_zone_constants as ZoneConstant from cinder.zonemanager.drivers import driver_utils from cinder.zonemanager.drivers import fc_zone_driver from cinder.zonemanager import utils as zm_utils LOG = logging.getLogger(__name__) SUPPORTED_CHARS = string.ascii_letters + string.digits + '$' + '-' + '^' + '_' cisco_opts = [ cfg.StrOpt('cisco_sb_connector', default='cinder.zonemanager.drivers.cisco' '.cisco_fc_zone_client_cli.CiscoFCZoneClientCLI', help='Southbound connector for zoning operation'), ] CONF = cfg.CONF CONF.register_opts(cisco_opts, group='fc-zone-manager') @interface.fczmdriver class CiscoFCZoneDriver(fc_zone_driver.FCZoneDriver): """Cisco FC zone driver implementation. OpenStack Fibre Channel zone driver to manage FC zoning in Cisco SAN fabrics. Version history: 1.0 - Initial Cisco FC zone driver 1.1 - Added friendly zone name support """ VERSION = "1.1.0" # ThirdPartySystems wiki name CI_WIKI_NAME = "Cisco_ZM_CI" # TODO(jsbryant) Remove driver in Rocky if CI is not fixed SUPPORTED = False def __init__(self, **kwargs): super(CiscoFCZoneDriver, self).__init__(**kwargs) self.configuration = kwargs.get('configuration', None) if self.configuration: self.configuration.append_config_values(cisco_opts) # Adding a hack to handle parameters from super classes # in case configured with multi backends. fabric_names = self.configuration.safe_get('fc_fabric_names') activate = self.configuration.safe_get('cisco_zone_activate') prefix = self.configuration.safe_get('cisco_zone_name_prefix') base_san_opts = [] if not fabric_names: base_san_opts.append( cfg.StrOpt('fc_fabric_names', help='Comma separated list of fibre channel ' 'fabric names. This list of names is used to' ' retrieve other SAN credentials for connecting' ' to each SAN fabric' )) if not activate: base_san_opts.append( cfg.BoolOpt('cisco_zone_activate', default=True, help='Indicates whether zone should ' 'be activated or not')) if not prefix: base_san_opts.append( cfg.StrOpt('cisco_zone_name_prefix', default="openstack", help="A prefix to be used when naming zone")) if len(base_san_opts) > 0: CONF.register_opts(base_san_opts) self.configuration.append_config_values(base_san_opts) fabric_names = [x.strip() for x in self. configuration.fc_fabric_names.split(',')] # There can be more than one SAN in the network and we need to # get credentials for each SAN. if fabric_names: self.fabric_configs = fabric_opts.load_fabric_configurations( fabric_names) @lockutils.synchronized('cisco', 'fcfabric-', True) def add_connection(self, fabric, initiator_target_map, host_name=None, storage_system=None): """Concrete implementation of add_connection. Based on zoning policy and state of each I-T pair, list of zone members are created and pushed to the fabric to add zones. The new zones created or zones updated are activated based on isActivate flag set in cinder.conf returned by volume driver after attach operation. :param fabric: Fabric name from cinder.conf file :param initiator_target_map: Mapping of initiator to list of targets """ LOG.debug("Add connection for Fabric: %s", fabric) LOG.info("CiscoFCZoneDriver - Add connection " "for I-T map: %s", initiator_target_map) fabric_ip = self.fabric_configs[fabric].safe_get( 'cisco_fc_fabric_address') fabric_user = self.fabric_configs[fabric].safe_get( 'cisco_fc_fabric_user') fabric_pwd = self.fabric_configs[fabric].safe_get( 'cisco_fc_fabric_password') fabric_port = self.fabric_configs[fabric].safe_get( 'cisco_fc_fabric_port') zoning_policy = self.configuration.zoning_policy zoning_policy_fab = self.fabric_configs[fabric].safe_get( 'cisco_zoning_policy') if zoning_policy_fab: zoning_policy = zoning_policy_fab zoning_vsan = self.fabric_configs[fabric].safe_get('cisco_zoning_vsan') LOG.info("Zoning policy for Fabric %s", zoning_policy) statusmap_from_fabric = self.get_zoning_status( fabric_ip, fabric_user, fabric_pwd, fabric_port, zoning_vsan) if statusmap_from_fabric.get('session') == 'none': cfgmap_from_fabric = self.get_active_zone_set( fabric_ip, fabric_user, fabric_pwd, fabric_port, zoning_vsan) zone_names = [] if cfgmap_from_fabric.get('zones'): zone_names = cfgmap_from_fabric['zones'].keys() # based on zoning policy, create zone member list and # push changes to fabric. for initiator_key in initiator_target_map.keys(): zone_map = {} zone_update_map = {} initiator = initiator_key.lower() t_list = initiator_target_map[initiator_key] if zoning_policy == 'initiator-target': for t in t_list: target = t.lower() zone_members = [ zm_utils.get_formatted_wwn(initiator), zm_utils.get_formatted_wwn(target)] zone_name = ( driver_utils.get_friendly_zone_name( zoning_policy, initiator, target, host_name, storage_system, self.configuration.cisco_zone_name_prefix, SUPPORTED_CHARS)) if (len(cfgmap_from_fabric) == 0 or ( zone_name not in zone_names)): zone_map[zone_name] = zone_members else: # This is I-T zoning, skip if zone exists. LOG.info("Zone exists in I-T mode. " "Skipping zone creation %s", zone_name) elif zoning_policy == 'initiator': zone_members = [ zm_utils.get_formatted_wwn(initiator)] for t in t_list: target = t.lower() zone_members.append( zm_utils.get_formatted_wwn(target)) zone_name = ( driver_utils.get_friendly_zone_name( zoning_policy, initiator, target, host_name, storage_system, self.configuration.cisco_zone_name_prefix, SUPPORTED_CHARS)) # If zone exists, then perform an update_zone and add # new members into existing zone. if zone_name and (zone_name in zone_names): zone_members = filter( lambda x: x not in cfgmap_from_fabric['zones'][zone_name], zone_members) if zone_members: zone_update_map[zone_name] = zone_members else: zone_map[zone_name] = zone_members else: msg = _("Zoning Policy: %s, not" " recognized") % zoning_policy LOG.error(msg) raise exception.FCZoneDriverException(msg) LOG.info("Zone map to add: %(zone_map)s", {'zone_map': zone_map}) LOG.info("Zone map to update add: %(zone_update_map)s", {'zone_update_map': zone_update_map}) if zone_map or zone_update_map: conn = None try: conn = importutils.import_object( self.configuration.cisco_sb_connector, ipaddress=fabric_ip, username=fabric_user, password=<PASSWORD>, port=fabric_port, vsan=zoning_vsan) if zone_map: conn.add_zones( zone_map, self.configuration.cisco_zone_activate, zoning_vsan, cfgmap_from_fabric, statusmap_from_fabric) if zone_update_map: conn.update_zones( zone_update_map, self.configuration.cisco_zone_activate, zoning_vsan, ZoneConstant.ZONE_ADD, cfgmap_from_fabric, statusmap_from_fabric) conn.cleanup() except exception.CiscoZoningCliException as cisco_ex: msg = _("Exception: %s") % six.text_type(cisco_ex) raise exception.FCZoneDriverException(msg) except Exception: msg = _("Failed to add zoning configuration.") LOG.exception(msg) raise exception.FCZoneDriverException(msg) LOG.debug("Zones added successfully: %s", zone_map) else: LOG.debug("Zones already exist - Initiator Target Map: %s", initiator_target_map) else: LOG.debug("Zoning session exists VSAN: %s", zoning_vsan) @lockutils.synchronized('cisco', 'fcfabric-', True) def delete_connection(self, fabric, initiator_target_map, host_name=None, storage_system=None): """Concrete implementation of delete_connection. Based on zoning policy and state of each I-T pair, list of zones are created for deletion. The zones are either updated deleted based on the policy and attach/detach state of each I-T pair. :param fabric: Fabric name from cinder.conf file :param initiator_target_map: Mapping of initiator to list of targets """ LOG.debug("Delete connection for fabric: %s", fabric) LOG.info("CiscoFCZoneDriver - Delete connection for I-T map: %s", initiator_target_map) fabric_ip = self.fabric_configs[fabric].safe_get( 'cisco_fc_fabric_address') fabric_user = self.fabric_configs[fabric].safe_get( 'cisco_fc_fabric_user') fabric_pwd = self.fabric_configs[fabric].safe_get( 'cisco_fc_fabric_password') fabric_port = self.fabric_configs[fabric].safe_get( 'cisco_fc_fabric_port') zoning_policy = self.configuration.zoning_policy zoning_policy_fab = self.fabric_configs[fabric].safe_get( 'cisco_zoning_policy') if zoning_policy_fab: zoning_policy = zoning_policy_fab zoning_vsan = self.fabric_configs[fabric].safe_get('cisco_zoning_vsan') LOG.info("Zoning policy for fabric %s", zoning_policy) statusmap_from_fabric = self.get_zoning_status( fabric_ip, fabric_user, fabric_pwd, fabric_port, zoning_vsan) if statusmap_from_fabric.get('session') == 'none': cfgmap_from_fabric = self.get_active_zone_set( fabric_ip, fabric_user, fabric_pwd, fabric_port, zoning_vsan) zone_names = [] if cfgmap_from_fabric.get('zones'): zone_names = cfgmap_from_fabric['zones'].keys() # Based on zoning policy, get zone member list and push # changes to fabric. This operation could result in an update # for zone config with new member list or deleting zones from # active cfg. LOG.debug("zone config from Fabric: %s", cfgmap_from_fabric) for initiator_key in initiator_target_map.keys(): initiator = initiator_key.lower() formatted_initiator = zm_utils.get_formatted_wwn(initiator) zone_update_map = {} zones_to_delete = [] t_list = initiator_target_map[initiator_key] if zoning_policy == 'initiator-target': # In this case, zone needs to be deleted. for t in t_list: target = t.lower() zone_name = ( driver_utils.get_friendly_zone_name( zoning_policy, initiator, target, host_name, storage_system, self.configuration.cisco_zone_name_prefix, SUPPORTED_CHARS)) LOG.debug("Zone name to del: %s", zone_name) if (len(zone_names) > 0 and (zone_name in zone_names)): # delete zone. LOG.debug("Added zone to delete to list: %s", zone_name) zones_to_delete.append(zone_name) elif zoning_policy == 'initiator': zone_members = [formatted_initiator] for t in t_list: target = t.lower() zone_members.append( zm_utils.get_formatted_wwn(target)) zone_name = driver_utils.get_friendly_zone_name( zoning_policy, initiator, target, host_name, storage_system, self.configuration.cisco_zone_name_prefix, SUPPORTED_CHARS) # Check if there are zone members leftover after removal if (zone_names and (zone_name in zone_names)): filtered_members = filter( lambda x: x not in zone_members, cfgmap_from_fabric['zones'][zone_name]) # The assumption here is that initiator is always # there in the zone as it is 'initiator' policy. # If filtered list is empty, we remove that zone. # If there are other members leftover, then perform # update_zone to remove targets LOG.debug("Zone delete - I mode: filtered targets: %s", filtered_members) if filtered_members: remove_members = filter( lambda x: x in cfgmap_from_fabric['zones'][zone_name], zone_members) if remove_members: # Do not want to remove the initiator remove_members.remove(formatted_initiator) LOG.debug("Zone members to remove: %s", remove_members) zone_update_map[zone_name] = remove_members LOG.debug("Filtered zone Map to update: %s", zone_update_map) else: zones_to_delete.append(zone_name) else: LOG.info("Zoning Policy: %s, not recognized", zoning_policy) LOG.debug("Zone map to remove update: %s", zone_update_map) LOG.debug("Final Zone list to delete: %s", zones_to_delete) conn = None try: conn = importutils.import_object( self.configuration.cisco_sb_connector, ipaddress=fabric_ip, username=fabric_user, password=<PASSWORD>, port=fabric_port, vsan=zoning_vsan) # Update zone membership. if zone_update_map: conn.update_zones( zone_update_map, self.configuration.cisco_zone_activate, zoning_vsan, ZoneConstant.ZONE_REMOVE, cfgmap_from_fabric, statusmap_from_fabric) # Delete zones ~sk. if zones_to_delete: zone_name_string = '' num_zones = len(zones_to_delete) for i in range(0, num_zones): if i == 0: zone_name_string = ('%s%s' % ( zone_name_string, zones_to_delete[i])) else: zone_name_string = ('%s%s%s' % ( zone_name_string, ';', zones_to_delete[i])) conn.delete_zones(zone_name_string, self.configuration. cisco_zone_activate, zoning_vsan, cfgmap_from_fabric, statusmap_from_fabric) conn.cleanup() except Exception: msg = _("Failed to update or delete zoning configuration") LOG.exception(msg) raise exception.FCZoneDriverException(msg) LOG.debug("Zones deleted successfully: %s", zone_update_map) else: LOG.debug("Zoning session exists VSAN: %s", zoning_vsan) def get_san_context(self, target_wwn_list): """Lookup SAN context for visible end devices. Look up each SAN configured and return a map of SAN (fabric IP) to list of target WWNs visible to the fabric. """ formatted_target_list = [] fabric_map = {} fabrics = [x.strip() for x in self. configuration.fc_fabric_names.split(',')] LOG.debug("Fabric List: %s", fabrics) LOG.debug("Target wwn List: %s", target_wwn_list) if len(fabrics) > 0: for t in target_wwn_list: formatted_target_list.append( zm_utils.get_formatted_wwn(t.lower())) LOG.debug("Formatted Target wwn List: %s", formatted_target_list) for fabric_name in fabrics: fabric_ip = self.fabric_configs[fabric_name].safe_get( 'cisco_fc_fabric_address') fabric_user = self.fabric_configs[fabric_name].safe_get( 'cisco_fc_fabric_user') fabric_pwd = self.fabric_configs[fabric_name].safe_get( 'cisco_fc_fabric_password') fabric_port = self.fabric_configs[fabric_name].safe_get( 'cisco_fc_fabric_port') zoning_vsan = self.fabric_configs[fabric_name].safe_get( 'cisco_zoning_vsan') # Get name server data from fabric and get the targets # logged in. nsinfo = None try: conn = importutils.import_object( self.configuration.cisco_sb_connector, ipaddress=fabric_ip, username=fabric_user, password=<PASSWORD>, port=fabric_port, vsan=zoning_vsan) nsinfo = conn.get_nameserver_info() LOG.debug("show fcns database info from fabric: %s", nsinfo) conn.cleanup() except exception.CiscoZoningCliException: with excutils.save_and_reraise_exception(): LOG.exception("Error getting show fcns database info.") except Exception: msg = _("Failed to get show fcns database info.") LOG.exception(msg) raise exception.FCZoneDriverException(msg) visible_targets = filter( lambda x: x in formatted_target_list, nsinfo) if visible_targets: LOG.info("Filtered targets for SAN is: %s", {fabric_name: visible_targets}) # getting rid of the ':' before returning for idx, elem in enumerate(visible_targets): visible_targets[idx] = six.text_type( visible_targets[idx]).replace(':', '') fabric_map[fabric_name] = visible_targets else: LOG.debug("No targets are in the fcns info for SAN %s", fabric_name) LOG.debug("Return SAN context output: %s", fabric_map) return fabric_map def get_active_zone_set(self, fabric_ip, fabric_user, fabric_pwd, fabric_port, zoning_vsan): """Gets active zoneset config for vsan.""" cfgmap = {} conn = None try: LOG.debug("Southbound connector: %s", self.configuration.cisco_sb_connector) conn = importutils.import_object( self.configuration.cisco_sb_connector, ipaddress=fabric_ip, username=fabric_user, password=<PASSWORD>, port=fabric_port, vsan=zoning_vsan) cfgmap = conn.get_active_zone_set() conn.cleanup() except Exception: msg = _("Failed to access active zoning configuration.") LOG.exception(msg) raise exception.FCZoneDriverException(msg) LOG.debug("Active zone set from fabric: %s", cfgmap) return cfgmap def get_zoning_status(self, fabric_ip, fabric_user, fabric_pwd, fabric_port, zoning_vsan): """Gets zoneset status and mode.""" statusmap = {} conn = None try: LOG.debug("Southbound connector: %s", self.configuration.cisco_sb_connector) conn = importutils.import_object( self.configuration.cisco_sb_connector, ipaddress=fabric_ip, username=fabric_user, password=<PASSWORD>, port=fabric_port, vsan=zoning_vsan) statusmap = conn.get_zoning_status() conn.cleanup() except Exception: msg = _("Failed to access zoneset status:%s") LOG.exception(msg) raise exception.FCZoneDriverException(msg) LOG.debug("Zoneset status from fabric: %s", statusmap) return statusmap
en
0.859524
# (c) Copyright 2014 Cisco Systems Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # Cisco Zone Driver is responsible to manage access control using FC zoning for Cisco FC fabrics. This is a concrete implementation of FCZoneDriver interface implementing add_connection and delete_connection interfaces. **Related Flags** :zone_activate: Used by: class: 'FCZoneDriver'. Defaults to True :zone_name_prefix: Used by: class: 'FCZoneDriver'. Defaults to 'openstack' Cisco FC zone driver implementation. OpenStack Fibre Channel zone driver to manage FC zoning in Cisco SAN fabrics. Version history: 1.0 - Initial Cisco FC zone driver 1.1 - Added friendly zone name support # ThirdPartySystems wiki name # TODO(jsbryant) Remove driver in Rocky if CI is not fixed # Adding a hack to handle parameters from super classes # in case configured with multi backends. # There can be more than one SAN in the network and we need to # get credentials for each SAN. Concrete implementation of add_connection. Based on zoning policy and state of each I-T pair, list of zone members are created and pushed to the fabric to add zones. The new zones created or zones updated are activated based on isActivate flag set in cinder.conf returned by volume driver after attach operation. :param fabric: Fabric name from cinder.conf file :param initiator_target_map: Mapping of initiator to list of targets # based on zoning policy, create zone member list and # push changes to fabric. # This is I-T zoning, skip if zone exists. # If zone exists, then perform an update_zone and add # new members into existing zone. Concrete implementation of delete_connection. Based on zoning policy and state of each I-T pair, list of zones are created for deletion. The zones are either updated deleted based on the policy and attach/detach state of each I-T pair. :param fabric: Fabric name from cinder.conf file :param initiator_target_map: Mapping of initiator to list of targets # Based on zoning policy, get zone member list and push # changes to fabric. This operation could result in an update # for zone config with new member list or deleting zones from # active cfg. # In this case, zone needs to be deleted. # delete zone. # Check if there are zone members leftover after removal # The assumption here is that initiator is always # there in the zone as it is 'initiator' policy. # If filtered list is empty, we remove that zone. # If there are other members leftover, then perform # update_zone to remove targets # Do not want to remove the initiator # Update zone membership. # Delete zones ~sk. Lookup SAN context for visible end devices. Look up each SAN configured and return a map of SAN (fabric IP) to list of target WWNs visible to the fabric. # Get name server data from fabric and get the targets # logged in. # getting rid of the ':' before returning Gets active zoneset config for vsan. Gets zoneset status and mode.
1.942299
2
template/_base_typedef_pyi.py
Amourspirit/ooo_uno_tmpl
0
6625773
<gh_stars>0 # coding: utf-8 from _base_typedef import BaseTypeDef from _base_json import EventArgs class BaseTypeDefPyi(BaseTypeDef): def on_after_init_data(self, args: EventArgs) -> None: super().on_after_init_data(args=args)
# coding: utf-8 from _base_typedef import BaseTypeDef from _base_json import EventArgs class BaseTypeDefPyi(BaseTypeDef): def on_after_init_data(self, args: EventArgs) -> None: super().on_after_init_data(args=args)
en
0.833554
# coding: utf-8
2.205923
2
icetray/resources/test/no_such_library.py
hschwane/offline_production
1
6625774
#!/usr/bin/env python from I3Tray import * tray = I3Tray() try: from icecube import no_such_library tray.AddModule("BottomlessSource") tray.AddModule("NoSuchModule") tray.Execute(5) except: print("Good. It threw.") sys.exit(0) # indicate success. else: print("should have thrown") sys.exit(1)
#!/usr/bin/env python from I3Tray import * tray = I3Tray() try: from icecube import no_such_library tray.AddModule("BottomlessSource") tray.AddModule("NoSuchModule") tray.Execute(5) except: print("Good. It threw.") sys.exit(0) # indicate success. else: print("should have thrown") sys.exit(1)
en
0.378994
#!/usr/bin/env python # indicate success.
1.968271
2
data/wordstat.py
barzerman/barzer
1
6625775
<reponame>barzerman/barzer #!/usr/bin/python # -*- coding: utf-8 -*- import fileinput,codecs, sys, re #reads in the file in CLASS|SUBCLASS|ID|name format #and produces statements writer = codecs.getwriter('utf-8')(sys.stdout) reader = codecs.getreader('utf-8')(sys.stdin) utf8_re=re.compile(u'[^а-яА-Я]+',re.UNICODE) wordcnt={} for line in reader: if len(line)<3: continue fld=utf8_re.split(line) for i in fld: if len(i)>1 and i[0] != ' ': if not i in wordcnt: wordcnt[i]=1 else: wordcnt[i]+=1 writer = codecs.getwriter('utf-8')(sys.stdout) #handling capitalized words - discovering proper names for i in wordcnt: if len(i)>1 and i[0] != i[0].lower() and i[1] == i[1].lower(): tolc=i tolc=tolc[0].lower()+tolc[1:] cnt=wordcnt[i] if tolc not in wordcnt and cnt>1: writer.write(i) print ",",cnt if False: for i in wordcnt: if wordcnt[i]>5: writer.write(i) print ",",wordcnt[i]
#!/usr/bin/python # -*- coding: utf-8 -*- import fileinput,codecs, sys, re #reads in the file in CLASS|SUBCLASS|ID|name format #and produces statements writer = codecs.getwriter('utf-8')(sys.stdout) reader = codecs.getreader('utf-8')(sys.stdin) utf8_re=re.compile(u'[^а-яА-Я]+',re.UNICODE) wordcnt={} for line in reader: if len(line)<3: continue fld=utf8_re.split(line) for i in fld: if len(i)>1 and i[0] != ' ': if not i in wordcnt: wordcnt[i]=1 else: wordcnt[i]+=1 writer = codecs.getwriter('utf-8')(sys.stdout) #handling capitalized words - discovering proper names for i in wordcnt: if len(i)>1 and i[0] != i[0].lower() and i[1] == i[1].lower(): tolc=i tolc=tolc[0].lower()+tolc[1:] cnt=wordcnt[i] if tolc not in wordcnt and cnt>1: writer.write(i) print ",",cnt if False: for i in wordcnt: if wordcnt[i]>5: writer.write(i) print ",",wordcnt[i]
en
0.625077
#!/usr/bin/python # -*- coding: utf-8 -*- #reads in the file in CLASS|SUBCLASS|ID|name format #and produces statements #handling capitalized words - discovering proper names
3.862461
4
setup.py
plaplant/SSINS
4
6625776
from __future__ import absolute_import, division, print_function from setuptools import setup import os import sys import json sys.path.append('SSINS') def package_files(package_dir, subdirectory): # walk the input package_dir/subdirectory # return a package_data list paths = [] directory = os.path.join(package_dir, subdirectory) for (path, directories, filenames) in os.walk(directory): for filename in filenames: path = path.replace(package_dir + '/', '') paths.append(os.path.join(path, filename)) return paths data_files = package_files('SSINS', 'data') setup_args = { 'name': 'SSINS', 'author': '<NAME>', 'url': 'https://github.com/mwilensky768/SSINS', 'license': 'BSD', 'description': 'Sky-Subtracted Incoherent Noise Spectra', 'package_dir': {'SSINS': 'SSINS'}, 'packages': ['SSINS'], 'include_package_data': True, 'scripts': ['scripts/Run_HERA_SSINS.py', 'scripts/MWA_EoR_High_Flag.py', 'scripts/MWA_gpubox_to_SSINS_on_Pawsey.sh', 'scripts/MWA_vis_to_SSINS.py', 'scripts/occ_csv.py'], 'package_data': {'SSINS': data_files}, 'setup_requires': ['setuptools_scm'], 'use_scm_version': True, 'install_requires': ['pyuvdata', 'h5py', 'pyyaml'], 'zip_safe': False, } if __name__ == '__main__': setup(**setup_args)
from __future__ import absolute_import, division, print_function from setuptools import setup import os import sys import json sys.path.append('SSINS') def package_files(package_dir, subdirectory): # walk the input package_dir/subdirectory # return a package_data list paths = [] directory = os.path.join(package_dir, subdirectory) for (path, directories, filenames) in os.walk(directory): for filename in filenames: path = path.replace(package_dir + '/', '') paths.append(os.path.join(path, filename)) return paths data_files = package_files('SSINS', 'data') setup_args = { 'name': 'SSINS', 'author': '<NAME>', 'url': 'https://github.com/mwilensky768/SSINS', 'license': 'BSD', 'description': 'Sky-Subtracted Incoherent Noise Spectra', 'package_dir': {'SSINS': 'SSINS'}, 'packages': ['SSINS'], 'include_package_data': True, 'scripts': ['scripts/Run_HERA_SSINS.py', 'scripts/MWA_EoR_High_Flag.py', 'scripts/MWA_gpubox_to_SSINS_on_Pawsey.sh', 'scripts/MWA_vis_to_SSINS.py', 'scripts/occ_csv.py'], 'package_data': {'SSINS': data_files}, 'setup_requires': ['setuptools_scm'], 'use_scm_version': True, 'install_requires': ['pyuvdata', 'h5py', 'pyyaml'], 'zip_safe': False, } if __name__ == '__main__': setup(**setup_args)
en
0.343599
# walk the input package_dir/subdirectory # return a package_data list
1.949172
2
ansible/venv/lib/python2.7/site-packages/ansible/module_utils/service_now.py
gvashchenkolineate/gvashchenkolineate_infra_trytravis
17
6625777
<filename>ansible/venv/lib/python2.7/site-packages/ansible/module_utils/service_now.py # -*- coding: utf-8 -*- # Copyright: (c) 2019, Ansible Project # Copyright: (c) 2017, <NAME> <<EMAIL>> # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) from __future__ import absolute_import, division, print_function __metaclass__ = type import traceback from ansible.module_utils.basic import env_fallback, missing_required_lib # Pull in pysnow HAS_PYSNOW = False PYSNOW_IMP_ERR = None try: import pysnow HAS_PYSNOW = True except ImportError: PYSNOW_IMP_ERR = traceback.format_exc() class ServiceNowClient(object): def __init__(self, module): """ Constructor """ if not HAS_PYSNOW: module.fail_json(msg=missing_required_lib('pysnow'), exception=PYSNOW_IMP_ERR) self.module = module self.params = module.params self.client_id = self.params['client_id'] self.client_secret = self.params['client_secret'] self.username = self.params['username'] self.password = self.params['password'] self.instance = self.params['instance'] self.session = {'token': None} self.conn = None def login(self): result = dict( changed=False ) if self.params['client_id'] is not None: try: self.conn = pysnow.OAuthClient(client_id=self.client_id, client_secret=self.client_secret, token_updater=self.updater, instance=self.instance) except Exception as detail: self.module.fail_json(msg='Could not connect to ServiceNow: {0}'.format(str(detail)), **result) if not self.session['token']: # No previous token exists, Generate new. try: self.session['token'] = self.conn.generate_token(self.username, self.password) except pysnow.exceptions.TokenCreateError as detail: self.module.fail_json(msg='Unable to generate a new token: {0}'.format(str(detail)), **result) self.conn.set_token(self.session['token']) elif self.username is not None: try: self.conn = pysnow.Client(instance=self.instance, user=self.username, password=self.password) except Exception as detail: self.module.fail_json(msg='Could not connect to ServiceNow: {0}'.format(str(detail)), **result) else: snow_error = "Must specify username/password. Also client_id/client_secret if using OAuth." self.module.fail_json(msg=snow_error, **result) def updater(self, new_token): self.session['token'] = new_token self.conn = pysnow.OAuthClient(client_id=self.client_id, client_secret=self.client_secret, token_updater=self.updater, instance=self.instance) try: self.conn.set_token(self.session['token']) except pysnow.exceptions.MissingToken: snow_error = "Token is missing" self.module.fail_json(msg=snow_error) except Exception as detail: self.module.fail_json(msg='Could not refresh token: {0}'.format(str(detail))) @staticmethod def snow_argument_spec(): return dict( instance=dict(type='str', required=False, fallback=(env_fallback, ['SN_INSTANCE'])), username=dict(type='str', required=False, fallback=(env_fallback, ['SN_USERNAME'])), password=dict(type='str', required=False, no_log=True, fallback=(env_fallback, ['SN_PASSWORD'])), client_id=dict(type='str', no_log=True), client_secret=dict(type='str', no_log=True), )
<filename>ansible/venv/lib/python2.7/site-packages/ansible/module_utils/service_now.py # -*- coding: utf-8 -*- # Copyright: (c) 2019, Ansible Project # Copyright: (c) 2017, <NAME> <<EMAIL>> # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) from __future__ import absolute_import, division, print_function __metaclass__ = type import traceback from ansible.module_utils.basic import env_fallback, missing_required_lib # Pull in pysnow HAS_PYSNOW = False PYSNOW_IMP_ERR = None try: import pysnow HAS_PYSNOW = True except ImportError: PYSNOW_IMP_ERR = traceback.format_exc() class ServiceNowClient(object): def __init__(self, module): """ Constructor """ if not HAS_PYSNOW: module.fail_json(msg=missing_required_lib('pysnow'), exception=PYSNOW_IMP_ERR) self.module = module self.params = module.params self.client_id = self.params['client_id'] self.client_secret = self.params['client_secret'] self.username = self.params['username'] self.password = self.params['password'] self.instance = self.params['instance'] self.session = {'token': None} self.conn = None def login(self): result = dict( changed=False ) if self.params['client_id'] is not None: try: self.conn = pysnow.OAuthClient(client_id=self.client_id, client_secret=self.client_secret, token_updater=self.updater, instance=self.instance) except Exception as detail: self.module.fail_json(msg='Could not connect to ServiceNow: {0}'.format(str(detail)), **result) if not self.session['token']: # No previous token exists, Generate new. try: self.session['token'] = self.conn.generate_token(self.username, self.password) except pysnow.exceptions.TokenCreateError as detail: self.module.fail_json(msg='Unable to generate a new token: {0}'.format(str(detail)), **result) self.conn.set_token(self.session['token']) elif self.username is not None: try: self.conn = pysnow.Client(instance=self.instance, user=self.username, password=self.password) except Exception as detail: self.module.fail_json(msg='Could not connect to ServiceNow: {0}'.format(str(detail)), **result) else: snow_error = "Must specify username/password. Also client_id/client_secret if using OAuth." self.module.fail_json(msg=snow_error, **result) def updater(self, new_token): self.session['token'] = new_token self.conn = pysnow.OAuthClient(client_id=self.client_id, client_secret=self.client_secret, token_updater=self.updater, instance=self.instance) try: self.conn.set_token(self.session['token']) except pysnow.exceptions.MissingToken: snow_error = "Token is missing" self.module.fail_json(msg=snow_error) except Exception as detail: self.module.fail_json(msg='Could not refresh token: {0}'.format(str(detail))) @staticmethod def snow_argument_spec(): return dict( instance=dict(type='str', required=False, fallback=(env_fallback, ['SN_INSTANCE'])), username=dict(type='str', required=False, fallback=(env_fallback, ['SN_USERNAME'])), password=dict(type='str', required=False, no_log=True, fallback=(env_fallback, ['SN_PASSWORD'])), client_id=dict(type='str', no_log=True), client_secret=dict(type='str', no_log=True), )
en
0.680558
# -*- coding: utf-8 -*- # Copyright: (c) 2019, Ansible Project # Copyright: (c) 2017, <NAME> <<EMAIL>> # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) # Pull in pysnow Constructor # No previous token exists, Generate new.
2.025828
2
housekeeping/urls.py
aptivate/Arkestra
1
6625778
from django.conf.urls.defaults import * from django.contrib import admin urlpatterns = patterns('', (r"^housekeeping/statistics/", "housekeeping.statistics.stats"), # /housekeeping/repair_mptt/contacts_and_people.Entity/ (r"^housekeeping/repair_mptt/(?P<slug>[-\w\.]+)/$", "housekeeping.repair_mptt.fix"), # then, try to match /housekeeping/<task>/<execute> (r"^housekeeping/(?P<task>[^/]+)/(?P<action>[^/]+)/$", "housekeeping.tasks.tasks"), # # no match? (r"^housekeeping/", "housekeeping.tasks.tasks"), # (r"^housekeeping/clean_plugins/", "housekeeping.clean_plugins.clean"), # # # (r"^statistics/user/(?P<slug>[-\w]+)$", "housekeeping.statistics.userstats"), )
from django.conf.urls.defaults import * from django.contrib import admin urlpatterns = patterns('', (r"^housekeeping/statistics/", "housekeeping.statistics.stats"), # /housekeeping/repair_mptt/contacts_and_people.Entity/ (r"^housekeeping/repair_mptt/(?P<slug>[-\w\.]+)/$", "housekeeping.repair_mptt.fix"), # then, try to match /housekeeping/<task>/<execute> (r"^housekeeping/(?P<task>[^/]+)/(?P<action>[^/]+)/$", "housekeeping.tasks.tasks"), # # no match? (r"^housekeeping/", "housekeeping.tasks.tasks"), # (r"^housekeeping/clean_plugins/", "housekeeping.clean_plugins.clean"), # # # (r"^statistics/user/(?P<slug>[-\w]+)$", "housekeeping.statistics.userstats"), )
en
0.706029
# /housekeeping/repair_mptt/contacts_and_people.Entity/ # then, try to match /housekeeping/<task>/<execute> # # no match? # (r"^housekeeping/clean_plugins/", "housekeeping.clean_plugins.clean"), # # # (r"^statistics/user/(?P<slug>[-\w]+)$", "housekeeping.statistics.userstats"),
1.864911
2
modules/plugin_social_auth/social/apps/cherrypy_app/models.py
KallyMilton/w2p-social-auth
1
6625779
"""Flask SQLAlchemy ORM models for Social Auth""" import cherrypy from sqlalchemy import Column, Integer, String, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.schema import UniqueConstraint from sqlalchemy.ext.declarative import declarative_base from social.utils import setting_name, module_member from social.storage.sqlalchemy_orm import SQLAlchemyUserMixin, \ SQLAlchemyAssociationMixin, \ SQLAlchemyNonceMixin, \ BaseSQLAlchemyStorage from social.apps.flask_app.fields import JSONType SocialBase = declarative_base() DB_SESSION_ATTR = cherrypy.config.get(setting_name('DB_SESSION_ATTR'), 'db') UID_LENGTH = cherrypy.config.get(setting_name('UID_LENGTH'), 255) User = module_member(cherrypy.config[setting_name('USER_MODEL')]) class CherryPySocialBase(object): @classmethod def _session(cls): return getattr(cherrypy.request, DB_SESSION_ATTR) class UserSocialAuth(CherryPySocialBase, SQLAlchemyUserMixin, SocialBase): """Social Auth association model""" __tablename__ = 'social_auth_usersocialauth' __table_args__ = (UniqueConstraint('provider', 'uid'),) id = Column(Integer, primary_key=True) provider = Column(String(32)) uid = Column(String(UID_LENGTH)) extra_data = Column(JSONType) user_id = Column(Integer, ForeignKey(User.id), nullable=False, index=True) user = relationship(User, backref='social_auth') @classmethod def username_max_length(cls): return User.__table__.columns.get('username').type.length @classmethod def user_model(cls): return User class Nonce(CherryPySocialBase, SQLAlchemyNonceMixin, SocialBase): """One use numbers""" __tablename__ = 'social_auth_nonce' __table_args__ = (UniqueConstraint('server_url', 'timestamp', 'salt'),) id = Column(Integer, primary_key=True) server_url = Column(String(255)) timestamp = Column(Integer) salt = Column(String(40)) class Association(CherryPySocialBase, SQLAlchemyAssociationMixin, SocialBase): """OpenId account association""" __tablename__ = 'social_auth_association' __table_args__ = (UniqueConstraint('server_url', 'handle'),) id = Column(Integer, primary_key=True) server_url = Column(String(255)) handle = Column(String(255)) secret = Column(String(255)) # base64 encoded issued = Column(Integer) lifetime = Column(Integer) assoc_type = Column(String(64)) class CherryPyStorage(BaseSQLAlchemyStorage): user = UserSocialAuth nonce = Nonce association = Association
"""Flask SQLAlchemy ORM models for Social Auth""" import cherrypy from sqlalchemy import Column, Integer, String, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.schema import UniqueConstraint from sqlalchemy.ext.declarative import declarative_base from social.utils import setting_name, module_member from social.storage.sqlalchemy_orm import SQLAlchemyUserMixin, \ SQLAlchemyAssociationMixin, \ SQLAlchemyNonceMixin, \ BaseSQLAlchemyStorage from social.apps.flask_app.fields import JSONType SocialBase = declarative_base() DB_SESSION_ATTR = cherrypy.config.get(setting_name('DB_SESSION_ATTR'), 'db') UID_LENGTH = cherrypy.config.get(setting_name('UID_LENGTH'), 255) User = module_member(cherrypy.config[setting_name('USER_MODEL')]) class CherryPySocialBase(object): @classmethod def _session(cls): return getattr(cherrypy.request, DB_SESSION_ATTR) class UserSocialAuth(CherryPySocialBase, SQLAlchemyUserMixin, SocialBase): """Social Auth association model""" __tablename__ = 'social_auth_usersocialauth' __table_args__ = (UniqueConstraint('provider', 'uid'),) id = Column(Integer, primary_key=True) provider = Column(String(32)) uid = Column(String(UID_LENGTH)) extra_data = Column(JSONType) user_id = Column(Integer, ForeignKey(User.id), nullable=False, index=True) user = relationship(User, backref='social_auth') @classmethod def username_max_length(cls): return User.__table__.columns.get('username').type.length @classmethod def user_model(cls): return User class Nonce(CherryPySocialBase, SQLAlchemyNonceMixin, SocialBase): """One use numbers""" __tablename__ = 'social_auth_nonce' __table_args__ = (UniqueConstraint('server_url', 'timestamp', 'salt'),) id = Column(Integer, primary_key=True) server_url = Column(String(255)) timestamp = Column(Integer) salt = Column(String(40)) class Association(CherryPySocialBase, SQLAlchemyAssociationMixin, SocialBase): """OpenId account association""" __tablename__ = 'social_auth_association' __table_args__ = (UniqueConstraint('server_url', 'handle'),) id = Column(Integer, primary_key=True) server_url = Column(String(255)) handle = Column(String(255)) secret = Column(String(255)) # base64 encoded issued = Column(Integer) lifetime = Column(Integer) assoc_type = Column(String(64)) class CherryPyStorage(BaseSQLAlchemyStorage): user = UserSocialAuth nonce = Nonce association = Association
en
0.673991
Flask SQLAlchemy ORM models for Social Auth Social Auth association model One use numbers OpenId account association # base64 encoded
2.71294
3
src/sima/simo/liftlinecoupling.py
SINTEF/simapy
0
6625780
<filename>src/sima/simo/liftlinecoupling.py # This an autogenerated file # # Generated with LiftLineCoupling from __future__ import annotations from typing import Dict,Sequence,List from dmt.entity import Entity from dmt.blueprint import Blueprint from .blueprints.liftlinecoupling import LiftLineCouplingBlueprint from typing import Dict from sima.sima.scriptablevalue import ScriptableValue from sima.simo.activationfailuremode import ActivationFailureMode from sima.simo.simplecoupling import SimpleCoupling from typing import TYPE_CHECKING if TYPE_CHECKING: from sima.simo.simobodypoint import SIMOBodyPoint class LiftLineCoupling(SimpleCoupling): """ Keyword arguments ----------------- name : str (default "") description : str (default "") _id : str (default "") scriptableValues : List[ScriptableValue] endPoint1 : SIMOBodyPoint endPoint2 : SIMOBodyPoint failureMode : ActivationFailureMode Failure mode of coupling element failureTime : float Earliest possible time of failure(default 0.0) breakingStrength : float Breaking strength(default 0.0) numElements : int Number of elements(default 0) accIncluded : bool Flag for including acceleration of the line(default True) diameter : float Segment diameter(default 0.0) eMod : float Modulus of elasticity(default 0.0) emFac : int Factor of elasticity - 2 for chains - 1 for other segment types(default 1) length : float Initial, unstretched wire length(default 0.0) flexibility : float Connection flexibility(default 0.0) damping : float Material damping(default 0.0) uwia : float Unit weight in air(default 0.0) watfac : float The ratio of weight in water to weight in air(default 0.0) transverseDrag : float Transverse drag coefficient(default 0.0) longitudinalDrag : float Longitudinal drag coefficient(default 0.0) """ def __init__(self , name="", description="", _id="", failureMode=ActivationFailureMode.NONE, failureTime=0.0, breakingStrength=0.0, numElements=0, accIncluded=True, diameter=0.0, eMod=0.0, emFac=1, length=0.0, flexibility=0.0, damping=0.0, uwia=0.0, watfac=0.0, transverseDrag=0.0, longitudinalDrag=0.0, **kwargs): super().__init__(**kwargs) self.name = name self.description = description self._id = _id self.scriptableValues = list() self.endPoint1 = None self.endPoint2 = None self.failureMode = failureMode self.failureTime = failureTime self.breakingStrength = breakingStrength self.numElements = numElements self.accIncluded = accIncluded self.diameter = diameter self.eMod = eMod self.emFac = emFac self.length = length self.flexibility = flexibility self.damping = damping self.uwia = uwia self.watfac = watfac self.transverseDrag = transverseDrag self.longitudinalDrag = longitudinalDrag for key, value in kwargs.items(): if not isinstance(value, Dict): setattr(self, key, value) @property def blueprint(self) -> Blueprint: """Return blueprint that this entity represents""" return LiftLineCouplingBlueprint() @property def name(self) -> str: """""" return self.__name @name.setter def name(self, value: str): """Set name""" self.__name = str(value) @property def description(self) -> str: """""" return self.__description @description.setter def description(self, value: str): """Set description""" self.__description = str(value) @property def _id(self) -> str: """""" return self.___id @_id.setter def _id(self, value: str): """Set _id""" self.___id = str(value) @property def scriptableValues(self) -> List[ScriptableValue]: """""" return self.__scriptableValues @scriptableValues.setter def scriptableValues(self, value: List[ScriptableValue]): """Set scriptableValues""" if not isinstance(value, Sequence): raise Exception("Expected sequense, but was " , type(value)) self.__scriptableValues = value @property def endPoint1(self) -> SIMOBodyPoint: """""" return self.__endPoint1 @endPoint1.setter def endPoint1(self, value: SIMOBodyPoint): """Set endPoint1""" self.__endPoint1 = value @property def endPoint2(self) -> SIMOBodyPoint: """""" return self.__endPoint2 @endPoint2.setter def endPoint2(self, value: SIMOBodyPoint): """Set endPoint2""" self.__endPoint2 = value @property def failureMode(self) -> ActivationFailureMode: """Failure mode of coupling element""" return self.__failureMode @failureMode.setter def failureMode(self, value: ActivationFailureMode): """Set failureMode""" self.__failureMode = value @property def failureTime(self) -> float: """Earliest possible time of failure""" return self.__failureTime @failureTime.setter def failureTime(self, value: float): """Set failureTime""" self.__failureTime = float(value) @property def breakingStrength(self) -> float: """Breaking strength""" return self.__breakingStrength @breakingStrength.setter def breakingStrength(self, value: float): """Set breakingStrength""" self.__breakingStrength = float(value) @property def numElements(self) -> int: """Number of elements""" return self.__numElements @numElements.setter def numElements(self, value: int): """Set numElements""" self.__numElements = int(value) @property def accIncluded(self) -> bool: """Flag for including acceleration of the line""" return self.__accIncluded @accIncluded.setter def accIncluded(self, value: bool): """Set accIncluded""" self.__accIncluded = bool(value) @property def diameter(self) -> float: """Segment diameter""" return self.__diameter @diameter.setter def diameter(self, value: float): """Set diameter""" self.__diameter = float(value) @property def eMod(self) -> float: """Modulus of elasticity""" return self.__eMod @eMod.setter def eMod(self, value: float): """Set eMod""" self.__eMod = float(value) @property def emFac(self) -> int: """Factor of elasticity - 2 for chains - 1 for other segment types""" return self.__emFac @emFac.setter def emFac(self, value: int): """Set emFac""" self.__emFac = int(value) @property def length(self) -> float: """Initial, unstretched wire length""" return self.__length @length.setter def length(self, value: float): """Set length""" self.__length = float(value) @property def flexibility(self) -> float: """Connection flexibility""" return self.__flexibility @flexibility.setter def flexibility(self, value: float): """Set flexibility""" self.__flexibility = float(value) @property def damping(self) -> float: """Material damping""" return self.__damping @damping.setter def damping(self, value: float): """Set damping""" self.__damping = float(value) @property def uwia(self) -> float: """Unit weight in air""" return self.__uwia @uwia.setter def uwia(self, value: float): """Set uwia""" self.__uwia = float(value) @property def watfac(self) -> float: """The ratio of weight in water to weight in air""" return self.__watfac @watfac.setter def watfac(self, value: float): """Set watfac""" self.__watfac = float(value) @property def transverseDrag(self) -> float: """Transverse drag coefficient""" return self.__transverseDrag @transverseDrag.setter def transverseDrag(self, value: float): """Set transverseDrag""" self.__transverseDrag = float(value) @property def longitudinalDrag(self) -> float: """Longitudinal drag coefficient""" return self.__longitudinalDrag @longitudinalDrag.setter def longitudinalDrag(self, value: float): """Set longitudinalDrag""" self.__longitudinalDrag = float(value)
<filename>src/sima/simo/liftlinecoupling.py # This an autogenerated file # # Generated with LiftLineCoupling from __future__ import annotations from typing import Dict,Sequence,List from dmt.entity import Entity from dmt.blueprint import Blueprint from .blueprints.liftlinecoupling import LiftLineCouplingBlueprint from typing import Dict from sima.sima.scriptablevalue import ScriptableValue from sima.simo.activationfailuremode import ActivationFailureMode from sima.simo.simplecoupling import SimpleCoupling from typing import TYPE_CHECKING if TYPE_CHECKING: from sima.simo.simobodypoint import SIMOBodyPoint class LiftLineCoupling(SimpleCoupling): """ Keyword arguments ----------------- name : str (default "") description : str (default "") _id : str (default "") scriptableValues : List[ScriptableValue] endPoint1 : SIMOBodyPoint endPoint2 : SIMOBodyPoint failureMode : ActivationFailureMode Failure mode of coupling element failureTime : float Earliest possible time of failure(default 0.0) breakingStrength : float Breaking strength(default 0.0) numElements : int Number of elements(default 0) accIncluded : bool Flag for including acceleration of the line(default True) diameter : float Segment diameter(default 0.0) eMod : float Modulus of elasticity(default 0.0) emFac : int Factor of elasticity - 2 for chains - 1 for other segment types(default 1) length : float Initial, unstretched wire length(default 0.0) flexibility : float Connection flexibility(default 0.0) damping : float Material damping(default 0.0) uwia : float Unit weight in air(default 0.0) watfac : float The ratio of weight in water to weight in air(default 0.0) transverseDrag : float Transverse drag coefficient(default 0.0) longitudinalDrag : float Longitudinal drag coefficient(default 0.0) """ def __init__(self , name="", description="", _id="", failureMode=ActivationFailureMode.NONE, failureTime=0.0, breakingStrength=0.0, numElements=0, accIncluded=True, diameter=0.0, eMod=0.0, emFac=1, length=0.0, flexibility=0.0, damping=0.0, uwia=0.0, watfac=0.0, transverseDrag=0.0, longitudinalDrag=0.0, **kwargs): super().__init__(**kwargs) self.name = name self.description = description self._id = _id self.scriptableValues = list() self.endPoint1 = None self.endPoint2 = None self.failureMode = failureMode self.failureTime = failureTime self.breakingStrength = breakingStrength self.numElements = numElements self.accIncluded = accIncluded self.diameter = diameter self.eMod = eMod self.emFac = emFac self.length = length self.flexibility = flexibility self.damping = damping self.uwia = uwia self.watfac = watfac self.transverseDrag = transverseDrag self.longitudinalDrag = longitudinalDrag for key, value in kwargs.items(): if not isinstance(value, Dict): setattr(self, key, value) @property def blueprint(self) -> Blueprint: """Return blueprint that this entity represents""" return LiftLineCouplingBlueprint() @property def name(self) -> str: """""" return self.__name @name.setter def name(self, value: str): """Set name""" self.__name = str(value) @property def description(self) -> str: """""" return self.__description @description.setter def description(self, value: str): """Set description""" self.__description = str(value) @property def _id(self) -> str: """""" return self.___id @_id.setter def _id(self, value: str): """Set _id""" self.___id = str(value) @property def scriptableValues(self) -> List[ScriptableValue]: """""" return self.__scriptableValues @scriptableValues.setter def scriptableValues(self, value: List[ScriptableValue]): """Set scriptableValues""" if not isinstance(value, Sequence): raise Exception("Expected sequense, but was " , type(value)) self.__scriptableValues = value @property def endPoint1(self) -> SIMOBodyPoint: """""" return self.__endPoint1 @endPoint1.setter def endPoint1(self, value: SIMOBodyPoint): """Set endPoint1""" self.__endPoint1 = value @property def endPoint2(self) -> SIMOBodyPoint: """""" return self.__endPoint2 @endPoint2.setter def endPoint2(self, value: SIMOBodyPoint): """Set endPoint2""" self.__endPoint2 = value @property def failureMode(self) -> ActivationFailureMode: """Failure mode of coupling element""" return self.__failureMode @failureMode.setter def failureMode(self, value: ActivationFailureMode): """Set failureMode""" self.__failureMode = value @property def failureTime(self) -> float: """Earliest possible time of failure""" return self.__failureTime @failureTime.setter def failureTime(self, value: float): """Set failureTime""" self.__failureTime = float(value) @property def breakingStrength(self) -> float: """Breaking strength""" return self.__breakingStrength @breakingStrength.setter def breakingStrength(self, value: float): """Set breakingStrength""" self.__breakingStrength = float(value) @property def numElements(self) -> int: """Number of elements""" return self.__numElements @numElements.setter def numElements(self, value: int): """Set numElements""" self.__numElements = int(value) @property def accIncluded(self) -> bool: """Flag for including acceleration of the line""" return self.__accIncluded @accIncluded.setter def accIncluded(self, value: bool): """Set accIncluded""" self.__accIncluded = bool(value) @property def diameter(self) -> float: """Segment diameter""" return self.__diameter @diameter.setter def diameter(self, value: float): """Set diameter""" self.__diameter = float(value) @property def eMod(self) -> float: """Modulus of elasticity""" return self.__eMod @eMod.setter def eMod(self, value: float): """Set eMod""" self.__eMod = float(value) @property def emFac(self) -> int: """Factor of elasticity - 2 for chains - 1 for other segment types""" return self.__emFac @emFac.setter def emFac(self, value: int): """Set emFac""" self.__emFac = int(value) @property def length(self) -> float: """Initial, unstretched wire length""" return self.__length @length.setter def length(self, value: float): """Set length""" self.__length = float(value) @property def flexibility(self) -> float: """Connection flexibility""" return self.__flexibility @flexibility.setter def flexibility(self, value: float): """Set flexibility""" self.__flexibility = float(value) @property def damping(self) -> float: """Material damping""" return self.__damping @damping.setter def damping(self, value: float): """Set damping""" self.__damping = float(value) @property def uwia(self) -> float: """Unit weight in air""" return self.__uwia @uwia.setter def uwia(self, value: float): """Set uwia""" self.__uwia = float(value) @property def watfac(self) -> float: """The ratio of weight in water to weight in air""" return self.__watfac @watfac.setter def watfac(self, value: float): """Set watfac""" self.__watfac = float(value) @property def transverseDrag(self) -> float: """Transverse drag coefficient""" return self.__transverseDrag @transverseDrag.setter def transverseDrag(self, value: float): """Set transverseDrag""" self.__transverseDrag = float(value) @property def longitudinalDrag(self) -> float: """Longitudinal drag coefficient""" return self.__longitudinalDrag @longitudinalDrag.setter def longitudinalDrag(self, value: float): """Set longitudinalDrag""" self.__longitudinalDrag = float(value)
en
0.417639
# This an autogenerated file # # Generated with LiftLineCoupling Keyword arguments ----------------- name : str (default "") description : str (default "") _id : str (default "") scriptableValues : List[ScriptableValue] endPoint1 : SIMOBodyPoint endPoint2 : SIMOBodyPoint failureMode : ActivationFailureMode Failure mode of coupling element failureTime : float Earliest possible time of failure(default 0.0) breakingStrength : float Breaking strength(default 0.0) numElements : int Number of elements(default 0) accIncluded : bool Flag for including acceleration of the line(default True) diameter : float Segment diameter(default 0.0) eMod : float Modulus of elasticity(default 0.0) emFac : int Factor of elasticity - 2 for chains - 1 for other segment types(default 1) length : float Initial, unstretched wire length(default 0.0) flexibility : float Connection flexibility(default 0.0) damping : float Material damping(default 0.0) uwia : float Unit weight in air(default 0.0) watfac : float The ratio of weight in water to weight in air(default 0.0) transverseDrag : float Transverse drag coefficient(default 0.0) longitudinalDrag : float Longitudinal drag coefficient(default 0.0) Return blueprint that this entity represents Set name Set description Set _id Set scriptableValues Set endPoint1 Set endPoint2 Failure mode of coupling element Set failureMode Earliest possible time of failure Set failureTime Breaking strength Set breakingStrength Number of elements Set numElements Flag for including acceleration of the line Set accIncluded Segment diameter Set diameter Modulus of elasticity Set eMod Factor of elasticity - 2 for chains - 1 for other segment types Set emFac Initial, unstretched wire length Set length Connection flexibility Set flexibility Material damping Set damping Unit weight in air Set uwia The ratio of weight in water to weight in air Set watfac Transverse drag coefficient Set transverseDrag Longitudinal drag coefficient Set longitudinalDrag
2.182281
2
src/tests/ftest/erasurecode/ec_offline_rebuild.py
Junkrat-boommm/daos
0
6625781
#!/usr/bin/python ''' (C) Copyright 2020-2021 Intel Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent ''' from ec_utils import ErasureCodeIor from apricot import skipForTicket class EcOfflineRebuild(ErasureCodeIor): # pylint: disable=too-many-ancestors """ Test Class Description: To validate Erasure code object data after killing single server (offline rebuild). :avocado: recursive """ def __init__(self, *args, **kwargs): """Initialize a ErasureCodeIor object.""" super(EcOfflineRebuild, self).__init__(*args, **kwargs) def setUp(self): """Set up for test case.""" super(EcOfflineRebuild, self).setUp() @skipForTicket("DAOS-6450") def test_ec_offline_rebuild(self): """Jira ID: DAOS-5894. Test Description: Test Erasure code object with IOR. Use Case: Create the pool, run IOR with supported EC object type class for small and large transfer sizes. kill single server, Wait to finish rebuild, verify all IOR read data and verified. :avocado: tags=all,hw,large,ib2,full_regression :avocado: tags=ec,ec_offline_rebuild """ #Write IOR data set with different EC object and different sizes self.ior_write_dataset() # Kill the last server rank self.get_dmg_command().system_stop(True, self.server_count - 1) # Wait for rebuild to start self.pool.wait_for_rebuild(True) # Wait for rebuild to complete self.pool.wait_for_rebuild(False) #Read IOR data and verify for different EC object and different sizes #written before killing the single server self.ior_read_dataset() # Kill the another server rank self.get_dmg_command().system_stop(True, self.server_count - 2) # Wait for rebuild to start self.pool.wait_for_rebuild(True) # Wait for rebuild to complete self.pool.wait_for_rebuild(False) #Read IOR data and verify for different EC object and different sizes #written before killing the second server. #Only +2 (Parity) data will be intact so read and verify only +2 IOR #data set self.ior_read_dataset(parity=2)
#!/usr/bin/python ''' (C) Copyright 2020-2021 Intel Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent ''' from ec_utils import ErasureCodeIor from apricot import skipForTicket class EcOfflineRebuild(ErasureCodeIor): # pylint: disable=too-many-ancestors """ Test Class Description: To validate Erasure code object data after killing single server (offline rebuild). :avocado: recursive """ def __init__(self, *args, **kwargs): """Initialize a ErasureCodeIor object.""" super(EcOfflineRebuild, self).__init__(*args, **kwargs) def setUp(self): """Set up for test case.""" super(EcOfflineRebuild, self).setUp() @skipForTicket("DAOS-6450") def test_ec_offline_rebuild(self): """Jira ID: DAOS-5894. Test Description: Test Erasure code object with IOR. Use Case: Create the pool, run IOR with supported EC object type class for small and large transfer sizes. kill single server, Wait to finish rebuild, verify all IOR read data and verified. :avocado: tags=all,hw,large,ib2,full_regression :avocado: tags=ec,ec_offline_rebuild """ #Write IOR data set with different EC object and different sizes self.ior_write_dataset() # Kill the last server rank self.get_dmg_command().system_stop(True, self.server_count - 1) # Wait for rebuild to start self.pool.wait_for_rebuild(True) # Wait for rebuild to complete self.pool.wait_for_rebuild(False) #Read IOR data and verify for different EC object and different sizes #written before killing the single server self.ior_read_dataset() # Kill the another server rank self.get_dmg_command().system_stop(True, self.server_count - 2) # Wait for rebuild to start self.pool.wait_for_rebuild(True) # Wait for rebuild to complete self.pool.wait_for_rebuild(False) #Read IOR data and verify for different EC object and different sizes #written before killing the second server. #Only +2 (Parity) data will be intact so read and verify only +2 IOR #data set self.ior_read_dataset(parity=2)
en
0.681471
#!/usr/bin/python (C) Copyright 2020-2021 Intel Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent # pylint: disable=too-many-ancestors Test Class Description: To validate Erasure code object data after killing single server (offline rebuild). :avocado: recursive Initialize a ErasureCodeIor object. Set up for test case. Jira ID: DAOS-5894. Test Description: Test Erasure code object with IOR. Use Case: Create the pool, run IOR with supported EC object type class for small and large transfer sizes. kill single server, Wait to finish rebuild, verify all IOR read data and verified. :avocado: tags=all,hw,large,ib2,full_regression :avocado: tags=ec,ec_offline_rebuild #Write IOR data set with different EC object and different sizes # Kill the last server rank # Wait for rebuild to start # Wait for rebuild to complete #Read IOR data and verify for different EC object and different sizes #written before killing the single server # Kill the another server rank # Wait for rebuild to start # Wait for rebuild to complete #Read IOR data and verify for different EC object and different sizes #written before killing the second server. #Only +2 (Parity) data will be intact so read and verify only +2 IOR #data set
2.117483
2
pynab/helpers.py
idwagner/pynab
0
6625782
<filename>pynab/helpers.py<gh_stars>0 import re import click from pynab.client import YNABClient, get_credentials from pynab import exceptions RE_UUID = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$') def get_client(): try: credentials = get_credentials() client = YNABClient(credentials) except exceptions.CredentialsNotFoundException: click.echo('ERROR: Credentials not found. Set your YNAB API token as environment ' 'variable YNAB_TOKEN.') return client def is_uuid(uuid: str): """Check if string is an UUID.""" return True if RE_UUID.search(uuid) else False def match_by_name_or_id(identifier: str, data: list) -> str: RE_BY_NAME = re.compile(identifier, re.IGNORECASE) identifier = identifier.lower() exact_match = [x for x in data if identifier == x.name.lower()] match = [x for x in data if RE_BY_NAME.search(x.name)] if len(exact_match) == 1: return exact_match[0].id if len(match) == 1: return match[0].id if exact_match or match: # There were multiple matches raise exceptions.AmbiguousBudgetException return None def select_budget(identifier: str) -> str: if is_uuid(identifier): return identifier client = get_client() items = client.budgets.get_budgets() data = items.data.budgets return match_by_name_or_id(identifier, data) def select_category(budget_id, identifier: str) -> str: data = [] if is_uuid(identifier): return identifier client = get_client() items = client.categories.get_categories(budget_id=budget_id) for group in items.data.category_groups: data.extend([x for x in group.categories]) return match_by_name_or_id(identifier, data)
<filename>pynab/helpers.py<gh_stars>0 import re import click from pynab.client import YNABClient, get_credentials from pynab import exceptions RE_UUID = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$') def get_client(): try: credentials = get_credentials() client = YNABClient(credentials) except exceptions.CredentialsNotFoundException: click.echo('ERROR: Credentials not found. Set your YNAB API token as environment ' 'variable YNAB_TOKEN.') return client def is_uuid(uuid: str): """Check if string is an UUID.""" return True if RE_UUID.search(uuid) else False def match_by_name_or_id(identifier: str, data: list) -> str: RE_BY_NAME = re.compile(identifier, re.IGNORECASE) identifier = identifier.lower() exact_match = [x for x in data if identifier == x.name.lower()] match = [x for x in data if RE_BY_NAME.search(x.name)] if len(exact_match) == 1: return exact_match[0].id if len(match) == 1: return match[0].id if exact_match or match: # There were multiple matches raise exceptions.AmbiguousBudgetException return None def select_budget(identifier: str) -> str: if is_uuid(identifier): return identifier client = get_client() items = client.budgets.get_budgets() data = items.data.budgets return match_by_name_or_id(identifier, data) def select_category(budget_id, identifier: str) -> str: data = [] if is_uuid(identifier): return identifier client = get_client() items = client.categories.get_categories(budget_id=budget_id) for group in items.data.category_groups: data.extend([x for x in group.categories]) return match_by_name_or_id(identifier, data)
en
0.968603
Check if string is an UUID. # There were multiple matches
2.578122
3
py/desigal/__init__.py
biprateep/DESI-stack
1
6625783
from .redshift import redshift from .resample import resample from .normalize import normalize from .coadd_cameras import coadd_cameras from .resample import resample from .sky import get_sky from .model_ivar import model_ivar from .stack import stack_spectra
from .redshift import redshift from .resample import resample from .normalize import normalize from .coadd_cameras import coadd_cameras from .resample import resample from .sky import get_sky from .model_ivar import model_ivar from .stack import stack_spectra
none
1
1.054106
1
misc/carbon-relay/web.py
Krylon360/evernote-graphite-web
8
6625784
#!/usr/bin/env python """Copyright 2008 Orbitz WorldWide Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.""" import os, posix, time from cPickle import dumps from twisted.web.resource import Resource class CacheQueryService(Resource): isLeaf = True def __init__(self,cluster): Resource.__init__(self) self.cluster = cluster for cache in self.cluster.caches.values(): cache.cacheQueries = 0 def render_GET(self,req): metric = req.path[1:] cache = self.cluster.selectCache(metric) points = cache.get(metric,[]) print 'CacheQuery for %s returning %d points' % (metric,len(points)) cache.cacheQueries += 1 return dumps( points ) class WebConsole(Resource): isLeaf = True def __init__(self,pypes,cluster,agents): Resource.__init__(self) self.pypes = pypes self.cluster = cluster self.agents = agents self.cpuUsage = -1.0 self.memUsage = 0 self.lastCalcTime = time.time() self.lastCpuVal = 0.0 self.templates = {} for tmpl in os.listdir('templates'): if not tmpl.endswith('.tmpl'): continue self.templates[ tmpl[:-5] ] = open('templates/%s' % tmpl).read() def render_GET(self,req): if req.path == '/': return self.mainPage() if req.path == '/web.css': return open('web.css').read() def mainPage(self): if self.cpuUsage > 100 or self.cpuUsage < 0: cpuUsage = "..." else: cpuUsage = "%%%.2f" % self.cpuUsage memUsage = self.memUsage page = self.templates['main'] % locals() return page def updateUsage(self): now = time.time() t = posix.times() curCpuVal = t[0] + t[1] dt = now - self.lastCalcTime dv = curCpuVal - self.lastCpuVal self.cpuUsage = (dv / dt) * 100.0 self.lastCalcTime = now self.lastCpuVal = curCpuVal #self.memUsage = int(open('/proc/self/status').readlines()[12].split()[1])
#!/usr/bin/env python """Copyright 2008 Orbitz WorldWide Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.""" import os, posix, time from cPickle import dumps from twisted.web.resource import Resource class CacheQueryService(Resource): isLeaf = True def __init__(self,cluster): Resource.__init__(self) self.cluster = cluster for cache in self.cluster.caches.values(): cache.cacheQueries = 0 def render_GET(self,req): metric = req.path[1:] cache = self.cluster.selectCache(metric) points = cache.get(metric,[]) print 'CacheQuery for %s returning %d points' % (metric,len(points)) cache.cacheQueries += 1 return dumps( points ) class WebConsole(Resource): isLeaf = True def __init__(self,pypes,cluster,agents): Resource.__init__(self) self.pypes = pypes self.cluster = cluster self.agents = agents self.cpuUsage = -1.0 self.memUsage = 0 self.lastCalcTime = time.time() self.lastCpuVal = 0.0 self.templates = {} for tmpl in os.listdir('templates'): if not tmpl.endswith('.tmpl'): continue self.templates[ tmpl[:-5] ] = open('templates/%s' % tmpl).read() def render_GET(self,req): if req.path == '/': return self.mainPage() if req.path == '/web.css': return open('web.css').read() def mainPage(self): if self.cpuUsage > 100 or self.cpuUsage < 0: cpuUsage = "..." else: cpuUsage = "%%%.2f" % self.cpuUsage memUsage = self.memUsage page = self.templates['main'] % locals() return page def updateUsage(self): now = time.time() t = posix.times() curCpuVal = t[0] + t[1] dt = now - self.lastCalcTime dv = curCpuVal - self.lastCpuVal self.cpuUsage = (dv / dt) * 100.0 self.lastCalcTime = now self.lastCpuVal = curCpuVal #self.memUsage = int(open('/proc/self/status').readlines()[12].split()[1])
en
0.783037
#!/usr/bin/env python Copyright 2008 Orbitz WorldWide Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #self.memUsage = int(open('/proc/self/status').readlines()[12].split()[1])
1.917176
2
src/pretalx/submission/models/review.py
mberube/pretalx
0
6625785
from django.db import models from django.utils.functional import cached_property from django.utils.translation import gettext_lazy as _ from django_scopes import ScopedManager from i18nfield.fields import I18nCharField from pretalx.common.urls import EventUrls class ReviewScoreCategory(models.Model): event = models.ForeignKey( to="event.Event", related_name="score_categories", on_delete=models.CASCADE ) name = I18nCharField() weight = models.DecimalField(max_digits=4, decimal_places=1, default=1) required = models.BooleanField(default=False) active = models.BooleanField(default=True) limit_tracks = models.ManyToManyField( to="submission.Track", verbose_name=_("Limit to tracks"), blank=True, help_text=_("Leave empty to use this category for all tracks."), ) objects = ScopedManager(event="event") @classmethod def recalculate_scores(cls, event): for review in event.reviews.all(): review.save(update_score=True) class ReviewScore(models.Model): category = models.ForeignKey( to=ReviewScoreCategory, related_name="scores", on_delete=models.CASCADE ) value = models.DecimalField(max_digits=3, decimal_places=1) label = models.CharField(null=True, blank=True, max_length=100) objects = ScopedManager(event="category__event") def __str__(self): value = self.value if int(value) == value: value = int(value) if self.label: return f"{self.label} ({value})" return str(value) class Meta: ordering = ("value",) class Review(models.Model): """Reviews model the opinion of reviewers of a. :class:`~pretalx.submission.models.submission.Submission`. They can, but don't have to, include a score and a text. :param text: The review itself. May be empty. :param score: This score is calculated from all the related ``scores`` and their weights. Do not set it directly, use the ``update_score`` method instead. """ submission = models.ForeignKey( to="submission.Submission", related_name="reviews", on_delete=models.CASCADE ) user = models.ForeignKey( to="person.User", related_name="reviews", on_delete=models.CASCADE ) text = models.TextField(verbose_name=_("What do you think?"), null=True, blank=True) score = models.DecimalField( max_digits=10, decimal_places=2, verbose_name=_("Score"), null=True, blank=True ) scores = models.ManyToManyField(to=ReviewScore, related_name="reviews") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = ScopedManager(event="submission__event") def __str__(self): return f"Review(event={self.submission.event.slug}, submission={self.submission.title}, user={self.user.get_display_name}, score={self.score})" @classmethod def find_missing_reviews(cls, event, user, ignore=None): """Returns all. :class:`~pretalx.submission.models.submission.Submission` objects this :class:`~pretalx.person.models.user.User` still has to review for the given :class:`~pretalx.event.models.event.Event`. Excludes submissions this user has submitted, and takes track :class:`~pretalx.event.models.organiser.Team` permissions into account. The result is ordered by review count. :type event: :class:`~pretalx.event.models.event.Event` :type user: :class:`~pretalx.person.models.user.User` :rtype: Queryset of :class:`~pretalx.submission.models.submission.Submission` objects """ from pretalx.submission.models import SubmissionStates queryset = ( event.submissions.filter(state=SubmissionStates.SUBMITTED) .exclude(reviews__user=user) .exclude(speakers__in=[user]) .annotate(review_count=models.Count("reviews")) ) limit_tracks = user.teams.filter( models.Q(all_events=True) | models.Q(models.Q(all_events=False) & models.Q(limit_events__in=[event])), limit_tracks__isnull=False, ) if limit_tracks.exists(): tracks = set() for team in limit_tracks: tracks.update(team.limit_tracks.filter(event=event)) queryset = queryset.filter(track__in=tracks) if ignore: queryset = queryset.exclude(pk__in=ignore) # This is not randomised, because order_by("review_count", "?") sets all annotated # review_count values to 1. return queryset.order_by("review_count") @classmethod def calculate_score(cls, scores): if not scores: return None return sum(score.value * score.category.weight for score in scores) @cached_property def event(self): return self.submission.event @cached_property def display_score(self) -> str: """Helper method to get a display string of the review's score.""" if self.score is None: return "×" if int(self.score) == self.score: return str(int(self.score)) return str(self.score) def update_score(self): track = self.submission.track track_filter = models.Q(category__limit_tracks__isnull=True) if track: track_filter |= models.Q(category__limit_tracks__in=[track]) scores = ( self.scores.all() .select_related("category") .filter(track_filter, category__active=True) ) self.score = self.calculate_score(scores) def save(self, *args, update_score=True, **kwargs): if self.id and update_score: self.update_score() return super().save(*args, **kwargs) class urls(EventUrls): base = "{self.submission.orga_urls.reviews}" delete = "{base}{self.pk}/delete" class ReviewPhase(models.Model): """ReviewPhases determine reviewer access rights during a (potentially open) time frame. :param is_active: Is this phase currently active? There can be only one active phase per event. Use the ``activate`` method to activate a review phase, as it will take care of this limitation. :param position: Helper field to deal with relative positioning of review phases next to each other. """ event = models.ForeignKey( to="event.Event", related_name="review_phases", on_delete=models.CASCADE ) name = models.CharField(verbose_name=_("Name"), max_length=100) start = models.DateTimeField(verbose_name=_("Phase start"), null=True, blank=True) end = models.DateTimeField(verbose_name=_("Phase end"), null=True, blank=True) position = models.PositiveIntegerField(default=0) is_active = models.BooleanField(default=False) can_review = models.BooleanField( verbose_name=_("Reviewers can write and edit reviews"), default=True, ) can_see_other_reviews = models.CharField( verbose_name=_("Reviewers can see other reviews"), max_length=12, choices=( ("always", _("Always")), ("never", _("Never")), ("after_review", _("After reviewing the submission")), ), default="after_review", ) can_see_speaker_names = models.BooleanField( verbose_name=_("Reviewers can see speaker names"), default=True, ) can_see_reviewer_names = models.BooleanField( verbose_name=_("Reviewers can see the names of other reviewers"), default=True, ) can_change_submission_state = models.BooleanField( verbose_name=_("Reviewers can accept and reject submissions"), default=False, ) can_tag_submissions = models.CharField( verbose_name=_("Reviewers can tag submissions"), max_length=12, choices=( ("never", _("Never")), ("use_tags", _("Add and remove existing tags")), ("create_tags", _("Add, remove and create tags")), ), default="never", ) speakers_can_change_submissions = models.BooleanField( verbose_name=_("Speakers can modify their submissions before acceptance"), help_text=_( "By default, modification of submissions is locked after the CfP ends, and is re-enabled once the submission was accepted." ), default=False, ) objects = ScopedManager(event="event") class Meta: ordering = ("position",) class urls(EventUrls): base = "{self.event.orga_urls.review_settings}phase/{self.pk}/" delete = "{base}delete" up = "{base}up" down = "{base}down" activate = "{base}activate" def activate(self) -> None: """Activates this review phase and deactivates all others in this event.""" self.event.review_phases.all().update(is_active=False) self.is_active = True self.save() activate.alters_data = True
from django.db import models from django.utils.functional import cached_property from django.utils.translation import gettext_lazy as _ from django_scopes import ScopedManager from i18nfield.fields import I18nCharField from pretalx.common.urls import EventUrls class ReviewScoreCategory(models.Model): event = models.ForeignKey( to="event.Event", related_name="score_categories", on_delete=models.CASCADE ) name = I18nCharField() weight = models.DecimalField(max_digits=4, decimal_places=1, default=1) required = models.BooleanField(default=False) active = models.BooleanField(default=True) limit_tracks = models.ManyToManyField( to="submission.Track", verbose_name=_("Limit to tracks"), blank=True, help_text=_("Leave empty to use this category for all tracks."), ) objects = ScopedManager(event="event") @classmethod def recalculate_scores(cls, event): for review in event.reviews.all(): review.save(update_score=True) class ReviewScore(models.Model): category = models.ForeignKey( to=ReviewScoreCategory, related_name="scores", on_delete=models.CASCADE ) value = models.DecimalField(max_digits=3, decimal_places=1) label = models.CharField(null=True, blank=True, max_length=100) objects = ScopedManager(event="category__event") def __str__(self): value = self.value if int(value) == value: value = int(value) if self.label: return f"{self.label} ({value})" return str(value) class Meta: ordering = ("value",) class Review(models.Model): """Reviews model the opinion of reviewers of a. :class:`~pretalx.submission.models.submission.Submission`. They can, but don't have to, include a score and a text. :param text: The review itself. May be empty. :param score: This score is calculated from all the related ``scores`` and their weights. Do not set it directly, use the ``update_score`` method instead. """ submission = models.ForeignKey( to="submission.Submission", related_name="reviews", on_delete=models.CASCADE ) user = models.ForeignKey( to="person.User", related_name="reviews", on_delete=models.CASCADE ) text = models.TextField(verbose_name=_("What do you think?"), null=True, blank=True) score = models.DecimalField( max_digits=10, decimal_places=2, verbose_name=_("Score"), null=True, blank=True ) scores = models.ManyToManyField(to=ReviewScore, related_name="reviews") created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = ScopedManager(event="submission__event") def __str__(self): return f"Review(event={self.submission.event.slug}, submission={self.submission.title}, user={self.user.get_display_name}, score={self.score})" @classmethod def find_missing_reviews(cls, event, user, ignore=None): """Returns all. :class:`~pretalx.submission.models.submission.Submission` objects this :class:`~pretalx.person.models.user.User` still has to review for the given :class:`~pretalx.event.models.event.Event`. Excludes submissions this user has submitted, and takes track :class:`~pretalx.event.models.organiser.Team` permissions into account. The result is ordered by review count. :type event: :class:`~pretalx.event.models.event.Event` :type user: :class:`~pretalx.person.models.user.User` :rtype: Queryset of :class:`~pretalx.submission.models.submission.Submission` objects """ from pretalx.submission.models import SubmissionStates queryset = ( event.submissions.filter(state=SubmissionStates.SUBMITTED) .exclude(reviews__user=user) .exclude(speakers__in=[user]) .annotate(review_count=models.Count("reviews")) ) limit_tracks = user.teams.filter( models.Q(all_events=True) | models.Q(models.Q(all_events=False) & models.Q(limit_events__in=[event])), limit_tracks__isnull=False, ) if limit_tracks.exists(): tracks = set() for team in limit_tracks: tracks.update(team.limit_tracks.filter(event=event)) queryset = queryset.filter(track__in=tracks) if ignore: queryset = queryset.exclude(pk__in=ignore) # This is not randomised, because order_by("review_count", "?") sets all annotated # review_count values to 1. return queryset.order_by("review_count") @classmethod def calculate_score(cls, scores): if not scores: return None return sum(score.value * score.category.weight for score in scores) @cached_property def event(self): return self.submission.event @cached_property def display_score(self) -> str: """Helper method to get a display string of the review's score.""" if self.score is None: return "×" if int(self.score) == self.score: return str(int(self.score)) return str(self.score) def update_score(self): track = self.submission.track track_filter = models.Q(category__limit_tracks__isnull=True) if track: track_filter |= models.Q(category__limit_tracks__in=[track]) scores = ( self.scores.all() .select_related("category") .filter(track_filter, category__active=True) ) self.score = self.calculate_score(scores) def save(self, *args, update_score=True, **kwargs): if self.id and update_score: self.update_score() return super().save(*args, **kwargs) class urls(EventUrls): base = "{self.submission.orga_urls.reviews}" delete = "{base}{self.pk}/delete" class ReviewPhase(models.Model): """ReviewPhases determine reviewer access rights during a (potentially open) time frame. :param is_active: Is this phase currently active? There can be only one active phase per event. Use the ``activate`` method to activate a review phase, as it will take care of this limitation. :param position: Helper field to deal with relative positioning of review phases next to each other. """ event = models.ForeignKey( to="event.Event", related_name="review_phases", on_delete=models.CASCADE ) name = models.CharField(verbose_name=_("Name"), max_length=100) start = models.DateTimeField(verbose_name=_("Phase start"), null=True, blank=True) end = models.DateTimeField(verbose_name=_("Phase end"), null=True, blank=True) position = models.PositiveIntegerField(default=0) is_active = models.BooleanField(default=False) can_review = models.BooleanField( verbose_name=_("Reviewers can write and edit reviews"), default=True, ) can_see_other_reviews = models.CharField( verbose_name=_("Reviewers can see other reviews"), max_length=12, choices=( ("always", _("Always")), ("never", _("Never")), ("after_review", _("After reviewing the submission")), ), default="after_review", ) can_see_speaker_names = models.BooleanField( verbose_name=_("Reviewers can see speaker names"), default=True, ) can_see_reviewer_names = models.BooleanField( verbose_name=_("Reviewers can see the names of other reviewers"), default=True, ) can_change_submission_state = models.BooleanField( verbose_name=_("Reviewers can accept and reject submissions"), default=False, ) can_tag_submissions = models.CharField( verbose_name=_("Reviewers can tag submissions"), max_length=12, choices=( ("never", _("Never")), ("use_tags", _("Add and remove existing tags")), ("create_tags", _("Add, remove and create tags")), ), default="never", ) speakers_can_change_submissions = models.BooleanField( verbose_name=_("Speakers can modify their submissions before acceptance"), help_text=_( "By default, modification of submissions is locked after the CfP ends, and is re-enabled once the submission was accepted." ), default=False, ) objects = ScopedManager(event="event") class Meta: ordering = ("position",) class urls(EventUrls): base = "{self.event.orga_urls.review_settings}phase/{self.pk}/" delete = "{base}delete" up = "{base}up" down = "{base}down" activate = "{base}activate" def activate(self) -> None: """Activates this review phase and deactivates all others in this event.""" self.event.review_phases.all().update(is_active=False) self.is_active = True self.save() activate.alters_data = True
en
0.817119
Reviews model the opinion of reviewers of a. :class:`~pretalx.submission.models.submission.Submission`. They can, but don't have to, include a score and a text. :param text: The review itself. May be empty. :param score: This score is calculated from all the related ``scores`` and their weights. Do not set it directly, use the ``update_score`` method instead. Returns all. :class:`~pretalx.submission.models.submission.Submission` objects this :class:`~pretalx.person.models.user.User` still has to review for the given :class:`~pretalx.event.models.event.Event`. Excludes submissions this user has submitted, and takes track :class:`~pretalx.event.models.organiser.Team` permissions into account. The result is ordered by review count. :type event: :class:`~pretalx.event.models.event.Event` :type user: :class:`~pretalx.person.models.user.User` :rtype: Queryset of :class:`~pretalx.submission.models.submission.Submission` objects # This is not randomised, because order_by("review_count", "?") sets all annotated # review_count values to 1. Helper method to get a display string of the review's score. ReviewPhases determine reviewer access rights during a (potentially open) time frame. :param is_active: Is this phase currently active? There can be only one active phase per event. Use the ``activate`` method to activate a review phase, as it will take care of this limitation. :param position: Helper field to deal with relative positioning of review phases next to each other. Activates this review phase and deactivates all others in this event.
1.950302
2
Martel/test/testformats/delimiter.py
eoc21/biopython
3
6625786
<reponame>eoc21/biopython<filename>Martel/test/testformats/delimiter.py """Example of using Martel on a simple delimited file """ import Martel from Martel import RecordReader def delimiter(delim): assert len(delim) == 1, \ "delimiter can only be a single character long, not %s" % repr(delim) assert delim not in "\n\r", "Cannot use %s as a delimiter" % repr(delim) field = Martel.Group("field", Martel.Rep(Martel.AnyBut(delim + "\r\n"))) line = field + Martel.Rep(Martel.Str(delim) + field) + Martel.AnyEol() record = Martel.Group("record", line) format = Martel.ParseRecords("delimited", {}, record, RecordReader.CountLines, (1,)) return format tabformat = delimiter("\t") spaceformat = delimiter(" ") colonformat = delimiter(":") commaformat = delimiter(",") if __name__ == "__main__": from xml.sax import saxutils parser = colonformat.make_parser() parser.setContentHandler(saxutils.XMLGenerator()) parser.parseFile(open("/etc/passwd"))
"""Example of using Martel on a simple delimited file """ import Martel from Martel import RecordReader def delimiter(delim): assert len(delim) == 1, \ "delimiter can only be a single character long, not %s" % repr(delim) assert delim not in "\n\r", "Cannot use %s as a delimiter" % repr(delim) field = Martel.Group("field", Martel.Rep(Martel.AnyBut(delim + "\r\n"))) line = field + Martel.Rep(Martel.Str(delim) + field) + Martel.AnyEol() record = Martel.Group("record", line) format = Martel.ParseRecords("delimited", {}, record, RecordReader.CountLines, (1,)) return format tabformat = delimiter("\t") spaceformat = delimiter(" ") colonformat = delimiter(":") commaformat = delimiter(",") if __name__ == "__main__": from xml.sax import saxutils parser = colonformat.make_parser() parser.setContentHandler(saxutils.XMLGenerator()) parser.parseFile(open("/etc/passwd"))
en
0.710825
Example of using Martel on a simple delimited file
3.426341
3
wagtail_hooks.py
bobslee/django_commerce_wagtail
3
6625787
from django.contrib.admin.utils import quote from django.templatetags.static import static from django.urls import reverse from django.utils.html import format_html, format_html_join from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore import hooks from wagtail.wagtailadmin import widgets as wagtailadmin_widgets from wagtail.contrib.modeladmin.options import modeladmin_register from .admin import has_admin_perm from .models import ProductPage from .modeladmin import CommerceModelAdminGroup modeladmin_register(CommerceModelAdminGroup) @hooks.register('register_page_listing_buttons') def page_listing_buttons(page, page_perms, is_parent=False): admin_url = 'wagtailcommerce_product_modeladmin_edit' # TODO if user has_permission for (django)admin product_change if isinstance(page.specific, ProductPage) and hasattr(page, 'product'): url = reverse(admin_url, args=(quote(page.product.pk),), current_app='wagtailcommerce', ) yield wagtailadmin_widgets.PageListingButton( "product", url, classes=('icon', 'icon-fa-product-hunt'), attrs={'title': _('Edit product in the Commerce admin ')}, priority=100, ) @hooks.register('insert_editor_js') def editor_js(): js_files = [ static('wagtailcommerce/js/page-chooser-or-create.js'), ] js_includes = format_html_join( '\n', '<script src="{0}"></script>', ((filename, ) for filename in js_files) ) return js_includes @hooks.register('insert_global_admin_css') def global_admin_css(): css_files = [ static('wagtailcommerce/css/wagtailadmin/core.css') ] css_includes = format_html_join( '\n', '<link rel="stylesheet" href="{}">', ((filename, ) for filename in css_files) ) return css_includes
from django.contrib.admin.utils import quote from django.templatetags.static import static from django.urls import reverse from django.utils.html import format_html, format_html_join from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore import hooks from wagtail.wagtailadmin import widgets as wagtailadmin_widgets from wagtail.contrib.modeladmin.options import modeladmin_register from .admin import has_admin_perm from .models import ProductPage from .modeladmin import CommerceModelAdminGroup modeladmin_register(CommerceModelAdminGroup) @hooks.register('register_page_listing_buttons') def page_listing_buttons(page, page_perms, is_parent=False): admin_url = 'wagtailcommerce_product_modeladmin_edit' # TODO if user has_permission for (django)admin product_change if isinstance(page.specific, ProductPage) and hasattr(page, 'product'): url = reverse(admin_url, args=(quote(page.product.pk),), current_app='wagtailcommerce', ) yield wagtailadmin_widgets.PageListingButton( "product", url, classes=('icon', 'icon-fa-product-hunt'), attrs={'title': _('Edit product in the Commerce admin ')}, priority=100, ) @hooks.register('insert_editor_js') def editor_js(): js_files = [ static('wagtailcommerce/js/page-chooser-or-create.js'), ] js_includes = format_html_join( '\n', '<script src="{0}"></script>', ((filename, ) for filename in js_files) ) return js_includes @hooks.register('insert_global_admin_css') def global_admin_css(): css_files = [ static('wagtailcommerce/css/wagtailadmin/core.css') ] css_includes = format_html_join( '\n', '<link rel="stylesheet" href="{}">', ((filename, ) for filename in css_files) ) return css_includes
en
0.349119
# TODO if user has_permission for (django)admin product_change
2.009243
2
Bugscan_exploits-master/exp_list/exp-2625.py
csadsl/poc_exp
11
6625788
<gh_stars>10-100 #!/usr/bin/evn python #--coding:utf-8--*-- #Name:北京网达信联通用型电子采购系统多处SQL注入打包 #Refer:http://www.wooyun.org/bugs/wooyun-2010-0122276 #Author:xq17 def assign(service, arg): if service == '1caitong': return True, arg def audit(arg): urls = [ "Rat/ebid/viewInvite3.asp?InviteId=0000002852", "Rat/ebid/viewInvite4.asp?InviteId=0000002852", "Rat/ebid/viewInvite5.asp?InviteId=0000002852", "Rat/ebid/viewInvite6.asp?InviteId=0000002852", "Rat/ebid/viewInvite2.asp?InviteId=0000002852", "Rat/ebid/viewInvite1.asp?InviteId=0000002852", "Rat/EBid/ViewClarify1.asp?InviteId=11", "Rat/EBid/ViewClarify.asp?InviteId=11", "Rat/EBid/AuditForm/AuditForm_ExpertForm.asp?InviteId=11", ] data = "%27%20and%20(CHAR(126)%2BCHAR(116)%2BCHAR(101)%2BCHAR(115)%2BCHAR(116)%2BCHAR(88)%2BCHAR(81)%2BCHAR(49)%2BCHAR(55))%3E0--" for url in urls: vul = arg + url + data code, head, res, errcode, _ = curl.curl2(vul) if code!=0 and 'testXQ17' in res: security_hole(arg + url) if __name__ == '__main__': from dummy import * audit(assign('1caitong','http://tycg.jiigoo.com/')[1]) # audit(assign('1caitong','http://zhaobiao.cdjcc.com/')[1]) # audit(assign('1caitong','http://eps.myande.com/')[1]) # audit(assign('1caitong','http://caigou.irico.com.cn/')[1])
#!/usr/bin/evn python #--coding:utf-8--*-- #Name:北京网达信联通用型电子采购系统多处SQL注入打包 #Refer:http://www.wooyun.org/bugs/wooyun-2010-0122276 #Author:xq17 def assign(service, arg): if service == '1caitong': return True, arg def audit(arg): urls = [ "Rat/ebid/viewInvite3.asp?InviteId=0000002852", "Rat/ebid/viewInvite4.asp?InviteId=0000002852", "Rat/ebid/viewInvite5.asp?InviteId=0000002852", "Rat/ebid/viewInvite6.asp?InviteId=0000002852", "Rat/ebid/viewInvite2.asp?InviteId=0000002852", "Rat/ebid/viewInvite1.asp?InviteId=0000002852", "Rat/EBid/ViewClarify1.asp?InviteId=11", "Rat/EBid/ViewClarify.asp?InviteId=11", "Rat/EBid/AuditForm/AuditForm_ExpertForm.asp?InviteId=11", ] data = "%27%20and%20(CHAR(126)%2BCHAR(116)%2BCHAR(101)%2BCHAR(115)%2BCHAR(116)%2BCHAR(88)%2BCHAR(81)%2BCHAR(49)%2BCHAR(55))%3E0--" for url in urls: vul = arg + url + data code, head, res, errcode, _ = curl.curl2(vul) if code!=0 and 'testXQ17' in res: security_hole(arg + url) if __name__ == '__main__': from dummy import * audit(assign('1caitong','http://tycg.jiigoo.com/')[1]) # audit(assign('1caitong','http://zhaobiao.cdjcc.com/')[1]) # audit(assign('1caitong','http://eps.myande.com/')[1]) # audit(assign('1caitong','http://caigou.irico.com.cn/')[1])
en
0.179071
#!/usr/bin/evn python #--coding:utf-8--*-- #Name:北京网达信联通用型电子采购系统多处SQL注入打包 #Refer:http://www.wooyun.org/bugs/wooyun-2010-0122276 #Author:xq17 # audit(assign('1caitong','http://zhaobiao.cdjcc.com/')[1]) # audit(assign('1caitong','http://eps.myande.com/')[1]) # audit(assign('1caitong','http://caigou.irico.com.cn/')[1])
2.083378
2
update_readme.py
montib/rays1bench
0
6625789
import os import glob import shutil import fileinput def replace_text_in_file(file_to_search, text_to_search, results): with fileinput.FileInput(file_to_search, inplace=True) as file: for line in file: print(line.replace(text_to_search, results), end='') def parse(dirs, size, add_table_header=False): baseline_mrays = -1.0 if add_table_header: results = '\n|scene|version|time|total rays|performance|speedup|\n|--|--|--|--|--|--|\n' else: results = '' for i in dirs: os.chdir(i) # print('parsing: ' + i + '/' + str(size)) f = open('out_' + size + '.txt','rt') results += '|' + size + '|' + i[4:] + ': ' line = f.readline() results += line tokens = line.split('|') # 123.45 mrays/s mrays = float(tokens[3].split()[0]) # 123.45 if baseline_mrays < 0: baseline_mrays = mrays mrays_str = '{:.2f}'.format(mrays / baseline_mrays) if i == dirs[-1]: mrays_str = '**' + mrays_str + '**' # last value is in bold results += mrays_str + '|\n' f.close os.chdir('../..') # print('RESULTS = \n' + results + '\n') return results dirs = ['src/step1', 'src/step2', 'src/step3', 'src/step4', 'src/step5', 'src/step6', 'src/step7', 'src/step8', 'src/step9', 'src/step10', 'src/step11', 'src/step12', 'src/step13'] # all results shutil.copyfile('README_template.md', 'README.md') replace_text_in_file('README.md', '__RESULTS_MSVC2019_X64__', parse(dirs, 'large', True) + parse(dirs, 'medium', True) + parse(dirs, 'small', True)) # step1 steps_to_cmp = ['src/step1'] replace_text_in_file('README.md', '__RESULTS_MSVC2019_X64_step1__', parse(steps_to_cmp, 'large', True) + parse(steps_to_cmp, 'medium') + parse(steps_to_cmp, 'small')) # stepPREV -> stepCURRENT prev = dirs[0] for i in dirs[1:]: step_name = i[4:] to_replace = '__RESULTS_MSVC2019_X64_' + step_name + '__' steps_to_cmp = [prev, i] replace_text_in_file('README.md', to_replace, parse(steps_to_cmp, 'large', True) + parse(steps_to_cmp, 'medium') + parse(steps_to_cmp, 'small')) prev = i
import os import glob import shutil import fileinput def replace_text_in_file(file_to_search, text_to_search, results): with fileinput.FileInput(file_to_search, inplace=True) as file: for line in file: print(line.replace(text_to_search, results), end='') def parse(dirs, size, add_table_header=False): baseline_mrays = -1.0 if add_table_header: results = '\n|scene|version|time|total rays|performance|speedup|\n|--|--|--|--|--|--|\n' else: results = '' for i in dirs: os.chdir(i) # print('parsing: ' + i + '/' + str(size)) f = open('out_' + size + '.txt','rt') results += '|' + size + '|' + i[4:] + ': ' line = f.readline() results += line tokens = line.split('|') # 123.45 mrays/s mrays = float(tokens[3].split()[0]) # 123.45 if baseline_mrays < 0: baseline_mrays = mrays mrays_str = '{:.2f}'.format(mrays / baseline_mrays) if i == dirs[-1]: mrays_str = '**' + mrays_str + '**' # last value is in bold results += mrays_str + '|\n' f.close os.chdir('../..') # print('RESULTS = \n' + results + '\n') return results dirs = ['src/step1', 'src/step2', 'src/step3', 'src/step4', 'src/step5', 'src/step6', 'src/step7', 'src/step8', 'src/step9', 'src/step10', 'src/step11', 'src/step12', 'src/step13'] # all results shutil.copyfile('README_template.md', 'README.md') replace_text_in_file('README.md', '__RESULTS_MSVC2019_X64__', parse(dirs, 'large', True) + parse(dirs, 'medium', True) + parse(dirs, 'small', True)) # step1 steps_to_cmp = ['src/step1'] replace_text_in_file('README.md', '__RESULTS_MSVC2019_X64_step1__', parse(steps_to_cmp, 'large', True) + parse(steps_to_cmp, 'medium') + parse(steps_to_cmp, 'small')) # stepPREV -> stepCURRENT prev = dirs[0] for i in dirs[1:]: step_name = i[4:] to_replace = '__RESULTS_MSVC2019_X64_' + step_name + '__' steps_to_cmp = [prev, i] replace_text_in_file('README.md', to_replace, parse(steps_to_cmp, 'large', True) + parse(steps_to_cmp, 'medium') + parse(steps_to_cmp, 'small')) prev = i
en
0.422473
# print('parsing: ' + i + '/' + str(size)) # 123.45 mrays/s # 123.45 # last value is in bold # print('RESULTS = \n' + results + '\n') # all results # step1 # stepPREV -> stepCURRENT
3.249587
3
azure_monitor/tests/auto_collection/test_metrics_span_processor.py
yao-cqc/opentelemetry-azure-monitor-python
13
6625790
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import unittest from opentelemetry.sdk.trace import Span from opentelemetry.trace import SpanContext, SpanKind from opentelemetry.trace.status import Status, StatusCanonicalCode from azure_monitor.sdk.auto_collection.metrics_span_processor import ( AzureMetricsSpanProcessor, ) # pylint: disable=protected-access class TestMetricsSpanProcessor(unittest.TestCase): def test_document_collection(self): """Test the document collection.""" span_processor = AzureMetricsSpanProcessor() span_processor.is_collecting_documents = True test_span = Span( name="test", kind=SpanKind.SERVER, context=SpanContext( trace_id=36873507687745823477771305566750195431, span_id=12030755672171557338, is_remote=False, ), ) test_span.set_status(Status(StatusCanonicalCode.INTERNAL, "test")) test_span._start_time = 5000000 test_span._end_time = 15000000 span_processor.on_end(test_span) document = span_processor.documents.pop() self.assertIsNotNone(document) self.assertEqual( document.name, "Microsoft.ApplicationInsights.Request" )
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import unittest from opentelemetry.sdk.trace import Span from opentelemetry.trace import SpanContext, SpanKind from opentelemetry.trace.status import Status, StatusCanonicalCode from azure_monitor.sdk.auto_collection.metrics_span_processor import ( AzureMetricsSpanProcessor, ) # pylint: disable=protected-access class TestMetricsSpanProcessor(unittest.TestCase): def test_document_collection(self): """Test the document collection.""" span_processor = AzureMetricsSpanProcessor() span_processor.is_collecting_documents = True test_span = Span( name="test", kind=SpanKind.SERVER, context=SpanContext( trace_id=36873507687745823477771305566750195431, span_id=12030755672171557338, is_remote=False, ), ) test_span.set_status(Status(StatusCanonicalCode.INTERNAL, "test")) test_span._start_time = 5000000 test_span._end_time = 15000000 span_processor.on_end(test_span) document = span_processor.documents.pop() self.assertIsNotNone(document) self.assertEqual( document.name, "Microsoft.ApplicationInsights.Request" )
en
0.720511
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # pylint: disable=protected-access Test the document collection.
2.113647
2
votacoes/views.py
JeanSchnorr/votaluno
0
6625791
<filename>votacoes/views.py from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.contrib.auth.models import User from .models import Aluno, AvaliacaoTurma, AvaliacaoAluno, Turma, OfertaDisciplina, Conselho,UsuarioConselho, Votacao, Voto from django.shortcuts import render, redirect from datetime import datetime from .avaliacoes import * @login_required def home(request): context = {} conselhos_professor=[] conselhos_abertos = [] conselhos = request.user.conselhos_usuario.all() for conselho in conselhos: conselhos_professor.append(conselho.conselho) for conselho in Conselho.objects.filter(situacao=True): if conselho in conselhos_professor: conselhos_abertos.append(conselho) if request.user.is_superuser: context['conselhos_abertos'] = Conselho.objects.filter(situacao=True) else: context['conselhos_abertos'] = conselhos_abertos return render(request, 'home.html',context) # Views que manipulam as avaliações das turmas @login_required def avaliacoesTurmas(request): context = {} avaliacoes=[] avaliacoes_lancadas=[] ofertas = OfertaDisciplina.objects.filter(professor=request.user) for oferta in ofertas: avs = AvaliacaoTurma.objects.filter(oferta_disciplina=oferta).filter(status=True) avs_lancadas = AvaliacaoTurma.objects.filter(oferta_disciplina=oferta).filter(status=False)[:10] if len(avs_lancadas) > 0: for avaliacoesLancadas in avs_lancadas: avaliacoes_lancadas.append(avaliacoesLancadas) if len(avs) > 0: for avaliacoesDisciplina in avs: avaliacoes.append(avaliacoesDisciplina) context['avaliacoes'] = avaliacoes context['avaliacoes_lancadas'] = avaliacoes_lancadas return render(request,'avaliacoes/avaliacoesTurmas.html',context) @login_required def criarAvaliacaoTurma(request, avaliacao_id): context = {} avaliacao = AvaliacaoTurma.objects.get(id=avaliacao_id) context['avaliacao'] = avaliacao context['opcoes'] = DICT_TURMA return render(request,'avaliacoes/avaliarTurma.html', context) @login_required def lancarAvaliacaoTurma(request, avaliacao_id): soma = 0 selecionadas = request.POST.getlist('checks') for opcao in selecionadas: soma += int(opcao) avaliacao = AvaliacaoTurma.objects.get(pk=avaliacao_id) avaliacao.status = False avaliacao.avaliacao = soma avaliacao.outros_avaliacao = request.POST.get('outros') avaliacao.save() return avaliacoesTurmas(request) @login_required def visualizarAvaliacaoTurma(request, avaliacao_id): context = {} avaliacao = AvaliacaoTurma.objects.get(id=avaliacao_id) context['avaliacao'] = avaliacao context['opcoes'] = get_array_turma(avaliacao.avaliacao) return render(request,'avaliacoes/visualizarAvaliacaoTurma.html', context) #Views que manipulam as avaliações dos alunos @login_required def gerarAvaliacoesTurma(request): turma = Turma.objects.get(id=request.POST.get("turma")) bimestre = request.POST.get("bimestre") alunos = Aluno.objects.filter(turma=turma) ofertaDisciplinas_turma = OfertaDisciplina.objects.filter(turma=turma) for disciplina in ofertaDisciplinas_turma: avaliacaoTurma = AvaliacaoTurma(oferta_disciplina=disciplina,bimestre=bimestre,ano=int(datetime.now().year)) avaliacaoTurma.save() for aluno in alunos: avaliacaoAluno = AvaliacaoAluno(oferta_disciplina=disciplina,aluno=aluno,bimestre=bimestre,ano=int(datetime.now().year)) avaliacaoAluno.save() return administracao(request) @login_required def avaliacoesAlunos(request): context = {} avaliacoes=[] avaliacoes_lancadas=[] ofertas = OfertaDisciplina.objects.filter(professor=request.user) for oferta in ofertas: avs = AvaliacaoAluno.objects.filter(oferta_disciplina=oferta).filter(status=True) avs_lancadas = AvaliacaoAluno.objects.filter(oferta_disciplina=oferta).filter(status=False)[:10] if len(avs_lancadas) > 0: for avaliacoesLancadas in avs_lancadas: avaliacoes_lancadas.append(avaliacoesLancadas) if len(avs) > 0: for avaliacoesDisciplina in avs: avaliacoes.append(avaliacoesDisciplina) context['avaliacoes'] = avaliacoes context['avaliacoes_lancadas'] = avaliacoes_lancadas return render(request,'avaliacoes/avaliacoesAlunos.html',context) @login_required def criarAvaliacaoAluno(request, avaliacao_id): context = {} avaliacao = AvaliacaoAluno.objects.get(id=avaliacao_id) context['avaliacao'] = avaliacao context['opcoes'] = DICT_ALUNO return render(request,'avaliacoes/avaliarAluno.html', context) @login_required def lancarAvaliacaoAluno(request, avaliacao_id): soma = 0 selecionadas = request.POST.getlist('checks') for opcao in selecionadas: soma += int(opcao) avaliacao = AvaliacaoAluno.objects.get(pk=avaliacao_id) avaliacao.status = False avaliacao.avaliacao = soma avaliacao.outros_avaliacao = request.POST.get('outros') avaliacao.save() return avaliacoesAlunos(request) @login_required def visualizarAvaliacaoAluno(request, avaliacao_id): context = {} avaliacao = AvaliacaoAluno.objects.get(id=avaliacao_id) context['avaliacao'] = avaliacao context['opcoes'] = get_array_aluno(avaliacao.avaliacao) return render(request,'avaliacoes/visualizarAvaliacaoAluno.html', context) #Views que manipulam a administração @login_required def administracao(request): context = {} turmas = Turma.objects.all() conselhosFechados = Conselho.objects.filter(situacao=False) conselhosAbertos = Conselho.objects.filter(situacao=True) context['turmas'] = turmas context['conselhosFechados'] = conselhosFechados context['conselhosAbertos'] = conselhosAbertos return render(request,'administracao.html', context) @login_required def admin(request): return HttpResponseRedirect('/admin') #Views para Conselhos @login_required def gerarConselho(request): # Gerar conselho turma = Turma.objects.get(id=request.POST.get("turma")) data = request.POST.get("data") conselho = Conselho.objects.create( turma= turma, data= data, situacao = False, ) conselho.save() #Criar e popular lista de professores que dão aula para essa turma professores = [] for disciplina in turma.disciplinas_turma.all(): if not disciplina.professor in professores: professores.append(disciplina.professor) # Gerar relacionamento UsuarioConselho if professores: print(professores) for professor in professores: usuario_conselho = UsuarioConselho(usuario=professor,conselho=conselho) usuario_conselho.save() # Gerar votacoes dos alunos da turma deste conselho alunos = Aluno.objects.filter(turma=turma) for aluno in alunos: votacao_aluno = Votacao(aluno=aluno,conselho=conselho) votacao_aluno.save() #Gerar votos em branco para os professores deste conselho for professor in professores: voto_branco = Voto(usuario=professor,votacao=votacao_aluno) voto_branco.save() return administracao(request) @login_required def iniciarConselho(request): # Pesquisar e iniciar o conselho conselho_id = request.POST.get("conselho") conselho = Conselho.objects.get(id=conselho_id) conselho.situacao = True conselho.save() # Pesquisar e iniciar as votações dos alunos que pertencem à turma deste conselho alunos = Aluno.objects.filter(turma=conselho.turma) for aluno in alunos: votacao_aluno = Votacao.objects.get(aluno=aluno,conselho=conselho) votacao_aluno.situacao = True votacao_aluno.save() return administracao(request) @login_required def encerrrarConselho(request): # Pesquisar e encerrar o conselho conselho_id = request.POST.get("select") conselho = Conselho.objects.get(id=conselho_id) conselho.situacao = False conselho.save() # Pesquisar e encerrar as votações dos alunos que pertencem à turma deste conselho alunos = Aluno.objects.filter(turma=conselho.turma) for aluno in alunos: votacao_aluno = Votacao.objects.get(aluno=aluno,conselho=conselho) votacao_aluno.situacao = False votacao_aluno.save() return administracao(request) def exibirConselho(request, conselho_id): context = {} conselho = Conselho.objects.get(id = conselho_id) votacoes_conselho = conselho.votacoes_conselho.all() votos_usuario = request.user.votos_usuario.all() votos_conselho = [] for votacao in votacoes_conselho: for voto in votacao.votos_votacao.filter(usuario=request.user).filter(votado=False): votos_conselho.append(voto) if request.user.is_superuser: context['votacoes_conselho'] = votacoes_conselho context['conselho'] = conselho context['votos_conselho'] = votos_conselho return render(request,'votacoes/exibirConselho.html',context) #Views para Votacões def exibirVoto(request,votacao_id): context = {} votacao = Votacao.objects.get(id=votacao_id) if request.user.is_superuser: context['votos_aprovar'] = len(votacao.votos_votacao.filter(votado=True).filter(situacao="Aprovar")) context['votos_reprovar'] = len(votacao.votos_votacao.filter(votado=True).filter(situacao="Reprovar")) context['votos_abster'] = len(votacao.votos_votacao.filter(votado=True).filter(situacao="Abster")) context['votos_usuarios'] = votacao.votos_votacao.filter(votado=True) else: context['voto'] = votacao.votos_votacao.filter(usuario=request.user).filter(votado=False)[0] context['votacao'] = votacao context['conselho'] = votacao.conselho return render(request,'votacoes/voto.html',context) def gerarHistoricoAluno(id_aluno): historico = {} aluno = Aluno.objects.get(id=aluno_id) aluno.avaliacoes_aluno.all() for avaliacao in avaliacoes_aluno: a+b return historico def gerarHistoricoTurma(id_turma): historico = {} return historico def lancarVoto(request,voto_id): context = {} voto = Voto.objects.get(id=voto_id) conselho = voto.votacao.conselho alunos_conselho = conselho.turma.alunos_turma.all() voto.situacao = request.POST.get('botao') voto.votado = True voto.save() return exibirConselho(request, conselho.id) #erros def error404(request,exception): return render(request, '404.html', status=404) def error500(request): return render(request, '500.html', status=500) def faq(request): return render(request, 'faq.html')
<filename>votacoes/views.py from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.contrib.auth.models import User from .models import Aluno, AvaliacaoTurma, AvaliacaoAluno, Turma, OfertaDisciplina, Conselho,UsuarioConselho, Votacao, Voto from django.shortcuts import render, redirect from datetime import datetime from .avaliacoes import * @login_required def home(request): context = {} conselhos_professor=[] conselhos_abertos = [] conselhos = request.user.conselhos_usuario.all() for conselho in conselhos: conselhos_professor.append(conselho.conselho) for conselho in Conselho.objects.filter(situacao=True): if conselho in conselhos_professor: conselhos_abertos.append(conselho) if request.user.is_superuser: context['conselhos_abertos'] = Conselho.objects.filter(situacao=True) else: context['conselhos_abertos'] = conselhos_abertos return render(request, 'home.html',context) # Views que manipulam as avaliações das turmas @login_required def avaliacoesTurmas(request): context = {} avaliacoes=[] avaliacoes_lancadas=[] ofertas = OfertaDisciplina.objects.filter(professor=request.user) for oferta in ofertas: avs = AvaliacaoTurma.objects.filter(oferta_disciplina=oferta).filter(status=True) avs_lancadas = AvaliacaoTurma.objects.filter(oferta_disciplina=oferta).filter(status=False)[:10] if len(avs_lancadas) > 0: for avaliacoesLancadas in avs_lancadas: avaliacoes_lancadas.append(avaliacoesLancadas) if len(avs) > 0: for avaliacoesDisciplina in avs: avaliacoes.append(avaliacoesDisciplina) context['avaliacoes'] = avaliacoes context['avaliacoes_lancadas'] = avaliacoes_lancadas return render(request,'avaliacoes/avaliacoesTurmas.html',context) @login_required def criarAvaliacaoTurma(request, avaliacao_id): context = {} avaliacao = AvaliacaoTurma.objects.get(id=avaliacao_id) context['avaliacao'] = avaliacao context['opcoes'] = DICT_TURMA return render(request,'avaliacoes/avaliarTurma.html', context) @login_required def lancarAvaliacaoTurma(request, avaliacao_id): soma = 0 selecionadas = request.POST.getlist('checks') for opcao in selecionadas: soma += int(opcao) avaliacao = AvaliacaoTurma.objects.get(pk=avaliacao_id) avaliacao.status = False avaliacao.avaliacao = soma avaliacao.outros_avaliacao = request.POST.get('outros') avaliacao.save() return avaliacoesTurmas(request) @login_required def visualizarAvaliacaoTurma(request, avaliacao_id): context = {} avaliacao = AvaliacaoTurma.objects.get(id=avaliacao_id) context['avaliacao'] = avaliacao context['opcoes'] = get_array_turma(avaliacao.avaliacao) return render(request,'avaliacoes/visualizarAvaliacaoTurma.html', context) #Views que manipulam as avaliações dos alunos @login_required def gerarAvaliacoesTurma(request): turma = Turma.objects.get(id=request.POST.get("turma")) bimestre = request.POST.get("bimestre") alunos = Aluno.objects.filter(turma=turma) ofertaDisciplinas_turma = OfertaDisciplina.objects.filter(turma=turma) for disciplina in ofertaDisciplinas_turma: avaliacaoTurma = AvaliacaoTurma(oferta_disciplina=disciplina,bimestre=bimestre,ano=int(datetime.now().year)) avaliacaoTurma.save() for aluno in alunos: avaliacaoAluno = AvaliacaoAluno(oferta_disciplina=disciplina,aluno=aluno,bimestre=bimestre,ano=int(datetime.now().year)) avaliacaoAluno.save() return administracao(request) @login_required def avaliacoesAlunos(request): context = {} avaliacoes=[] avaliacoes_lancadas=[] ofertas = OfertaDisciplina.objects.filter(professor=request.user) for oferta in ofertas: avs = AvaliacaoAluno.objects.filter(oferta_disciplina=oferta).filter(status=True) avs_lancadas = AvaliacaoAluno.objects.filter(oferta_disciplina=oferta).filter(status=False)[:10] if len(avs_lancadas) > 0: for avaliacoesLancadas in avs_lancadas: avaliacoes_lancadas.append(avaliacoesLancadas) if len(avs) > 0: for avaliacoesDisciplina in avs: avaliacoes.append(avaliacoesDisciplina) context['avaliacoes'] = avaliacoes context['avaliacoes_lancadas'] = avaliacoes_lancadas return render(request,'avaliacoes/avaliacoesAlunos.html',context) @login_required def criarAvaliacaoAluno(request, avaliacao_id): context = {} avaliacao = AvaliacaoAluno.objects.get(id=avaliacao_id) context['avaliacao'] = avaliacao context['opcoes'] = DICT_ALUNO return render(request,'avaliacoes/avaliarAluno.html', context) @login_required def lancarAvaliacaoAluno(request, avaliacao_id): soma = 0 selecionadas = request.POST.getlist('checks') for opcao in selecionadas: soma += int(opcao) avaliacao = AvaliacaoAluno.objects.get(pk=avaliacao_id) avaliacao.status = False avaliacao.avaliacao = soma avaliacao.outros_avaliacao = request.POST.get('outros') avaliacao.save() return avaliacoesAlunos(request) @login_required def visualizarAvaliacaoAluno(request, avaliacao_id): context = {} avaliacao = AvaliacaoAluno.objects.get(id=avaliacao_id) context['avaliacao'] = avaliacao context['opcoes'] = get_array_aluno(avaliacao.avaliacao) return render(request,'avaliacoes/visualizarAvaliacaoAluno.html', context) #Views que manipulam a administração @login_required def administracao(request): context = {} turmas = Turma.objects.all() conselhosFechados = Conselho.objects.filter(situacao=False) conselhosAbertos = Conselho.objects.filter(situacao=True) context['turmas'] = turmas context['conselhosFechados'] = conselhosFechados context['conselhosAbertos'] = conselhosAbertos return render(request,'administracao.html', context) @login_required def admin(request): return HttpResponseRedirect('/admin') #Views para Conselhos @login_required def gerarConselho(request): # Gerar conselho turma = Turma.objects.get(id=request.POST.get("turma")) data = request.POST.get("data") conselho = Conselho.objects.create( turma= turma, data= data, situacao = False, ) conselho.save() #Criar e popular lista de professores que dão aula para essa turma professores = [] for disciplina in turma.disciplinas_turma.all(): if not disciplina.professor in professores: professores.append(disciplina.professor) # Gerar relacionamento UsuarioConselho if professores: print(professores) for professor in professores: usuario_conselho = UsuarioConselho(usuario=professor,conselho=conselho) usuario_conselho.save() # Gerar votacoes dos alunos da turma deste conselho alunos = Aluno.objects.filter(turma=turma) for aluno in alunos: votacao_aluno = Votacao(aluno=aluno,conselho=conselho) votacao_aluno.save() #Gerar votos em branco para os professores deste conselho for professor in professores: voto_branco = Voto(usuario=professor,votacao=votacao_aluno) voto_branco.save() return administracao(request) @login_required def iniciarConselho(request): # Pesquisar e iniciar o conselho conselho_id = request.POST.get("conselho") conselho = Conselho.objects.get(id=conselho_id) conselho.situacao = True conselho.save() # Pesquisar e iniciar as votações dos alunos que pertencem à turma deste conselho alunos = Aluno.objects.filter(turma=conselho.turma) for aluno in alunos: votacao_aluno = Votacao.objects.get(aluno=aluno,conselho=conselho) votacao_aluno.situacao = True votacao_aluno.save() return administracao(request) @login_required def encerrrarConselho(request): # Pesquisar e encerrar o conselho conselho_id = request.POST.get("select") conselho = Conselho.objects.get(id=conselho_id) conselho.situacao = False conselho.save() # Pesquisar e encerrar as votações dos alunos que pertencem à turma deste conselho alunos = Aluno.objects.filter(turma=conselho.turma) for aluno in alunos: votacao_aluno = Votacao.objects.get(aluno=aluno,conselho=conselho) votacao_aluno.situacao = False votacao_aluno.save() return administracao(request) def exibirConselho(request, conselho_id): context = {} conselho = Conselho.objects.get(id = conselho_id) votacoes_conselho = conselho.votacoes_conselho.all() votos_usuario = request.user.votos_usuario.all() votos_conselho = [] for votacao in votacoes_conselho: for voto in votacao.votos_votacao.filter(usuario=request.user).filter(votado=False): votos_conselho.append(voto) if request.user.is_superuser: context['votacoes_conselho'] = votacoes_conselho context['conselho'] = conselho context['votos_conselho'] = votos_conselho return render(request,'votacoes/exibirConselho.html',context) #Views para Votacões def exibirVoto(request,votacao_id): context = {} votacao = Votacao.objects.get(id=votacao_id) if request.user.is_superuser: context['votos_aprovar'] = len(votacao.votos_votacao.filter(votado=True).filter(situacao="Aprovar")) context['votos_reprovar'] = len(votacao.votos_votacao.filter(votado=True).filter(situacao="Reprovar")) context['votos_abster'] = len(votacao.votos_votacao.filter(votado=True).filter(situacao="Abster")) context['votos_usuarios'] = votacao.votos_votacao.filter(votado=True) else: context['voto'] = votacao.votos_votacao.filter(usuario=request.user).filter(votado=False)[0] context['votacao'] = votacao context['conselho'] = votacao.conselho return render(request,'votacoes/voto.html',context) def gerarHistoricoAluno(id_aluno): historico = {} aluno = Aluno.objects.get(id=aluno_id) aluno.avaliacoes_aluno.all() for avaliacao in avaliacoes_aluno: a+b return historico def gerarHistoricoTurma(id_turma): historico = {} return historico def lancarVoto(request,voto_id): context = {} voto = Voto.objects.get(id=voto_id) conselho = voto.votacao.conselho alunos_conselho = conselho.turma.alunos_turma.all() voto.situacao = request.POST.get('botao') voto.votado = True voto.save() return exibirConselho(request, conselho.id) #erros def error404(request,exception): return render(request, '404.html', status=404) def error500(request): return render(request, '500.html', status=500) def faq(request): return render(request, 'faq.html')
pt
0.954273
# Views que manipulam as avaliações das turmas #Views que manipulam as avaliações dos alunos #Views que manipulam a administração #Views para Conselhos # Gerar conselho #Criar e popular lista de professores que dão aula para essa turma # Gerar relacionamento UsuarioConselho # Gerar votacoes dos alunos da turma deste conselho #Gerar votos em branco para os professores deste conselho # Pesquisar e iniciar o conselho # Pesquisar e iniciar as votações dos alunos que pertencem à turma deste conselho # Pesquisar e encerrar o conselho # Pesquisar e encerrar as votações dos alunos que pertencem à turma deste conselho #Views para Votacões #erros
2.155288
2
clippercard/parser.py
timroesner/clippercard-python
1
6625792
""" Copyright (c) 2012-2017 (https://github.com/clippercard/clippercard-python) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import bs4 import collections import itertools import re # === Simple Objects for ClipperCard data === _profile_fields = [ 'name', 'email', 'address', 'phone' ] class Profile(collections.namedtuple('Profile', _profile_fields)): def __str__(self): return '\n'.join([ 'Name: {name}', 'Email: {email}', 'Phone: {phone}', 'Address: {address}' ]).format(**self._asdict()) _product_fields = [ 'name', # e.g. Cash value, BART HVD 60/64 'value' ] class CardProduct(collections.namedtuple('CardProduct', _product_fields)): def __str__(self): return '{name}: {value}'.format(**self._asdict()) _card_fields = [ 'serial_number', 'nickname', 'type', # Adult, Senior, Youth, Disabled Discount 'status', # Active, Inactive 'products' # a list of CardProduct ] class Card(collections.namedtuple('Card', _card_fields)): def __str__(self): lines = ['{serial_number} "{nickname}" ({type} - {status})'.format(**self._asdict())] for p in self.products: lines.append(' - {0}'.format(str(p))) return '\n'.join(lines) # === Helpers === REGEX_BLING = re.compile('^\$') REGEX_WHITESPACE = re.compile('\s+') def cleanup_whitespace(text_content): """clean up junk whitespace that comes with every table cell""" return re.sub(REGEX_WHITESPACE, ' ', text_content.strip()) def get_next_sibling_text(element): return list(element.next_siblings)[1].get_text() def get_inner_display_text(element): return list(element.next_siblings)[1].find( 'span', attrs={'class': 'displayName'} ).get_text() def find_values(soup, label_text, value_getter): values = [] for label_elem in soup.find_all('div', text=label_text): values.append(value_getter(label_elem)) return values # === Section Parsers === def parse_profile_data(account_page_content): """ Parse user profile from /ClipperCard/dashboard.jsf """ soup = bs4.BeautifulSoup(account_page_content, "html.parser") profile_data = soup.find('div', attrs={'class': 'profileData'}) fields = profile_data.find_all('div', attrs={'class': 'fieldData'}) values = [cleanup_whitespace(f.get_text()) for f in fields] return Profile( name=values[0], email=values[1], address=' '.join(values[2:5]), phone=values[5] ) def parse_card_products(card_soup): """ Parse card product names and balances from /ClipperCard/dashboard.jsf """ section_products = [] for card_section in card_soup.find_all('div', attrs={'class': 'whiteGreyCardBox'}): products = [] blings = card_section.find_all('div', text=REGEX_BLING) for value_node in blings: name = list(value_node.previous_siblings)[1].get_text().strip(':') products.append(CardProduct(name=name, value=value_node.get_text())) caltrain = card_section.find_all('div', text=re.compile('^Valid till')) for value_train in caltrain: name = list(value_train.previous_siblings)[1].get_text().strip(':') value_time = value_train.get_text() products.append(CardProduct(name=name, value=value_time)) section_products.append(products) return section_products def parse_cards(account_page_content): """ Parse card metadata and product balances from /ClipperCard/dashboard.jsf """ begin = account_page_content.index(b'<!--YOUR CLIPPER CARDS-->') end = account_page_content.index(b'<!--END YOUR CLIPPER CARDS-->') card_soup = bs4.BeautifulSoup(account_page_content[begin:end], "html.parser") serial_numbers = find_values(card_soup, 'Serial Number:', get_next_sibling_text) nicknames = find_values(card_soup, 'Card Nickname:', get_inner_display_text) types = find_values(card_soup, 'Type:', get_next_sibling_text) statuses = find_values(card_soup, 'Status:', get_next_sibling_text) products = parse_card_products(card_soup) cards = [] for sn, nn, tp, st, pd in zip(serial_numbers, nicknames, types, statuses, products): cards.append(Card(serial_number=sn, nickname=nn, type=tp, status=st, products=pd)) return cards
""" Copyright (c) 2012-2017 (https://github.com/clippercard/clippercard-python) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import bs4 import collections import itertools import re # === Simple Objects for ClipperCard data === _profile_fields = [ 'name', 'email', 'address', 'phone' ] class Profile(collections.namedtuple('Profile', _profile_fields)): def __str__(self): return '\n'.join([ 'Name: {name}', 'Email: {email}', 'Phone: {phone}', 'Address: {address}' ]).format(**self._asdict()) _product_fields = [ 'name', # e.g. Cash value, BART HVD 60/64 'value' ] class CardProduct(collections.namedtuple('CardProduct', _product_fields)): def __str__(self): return '{name}: {value}'.format(**self._asdict()) _card_fields = [ 'serial_number', 'nickname', 'type', # Adult, Senior, Youth, Disabled Discount 'status', # Active, Inactive 'products' # a list of CardProduct ] class Card(collections.namedtuple('Card', _card_fields)): def __str__(self): lines = ['{serial_number} "{nickname}" ({type} - {status})'.format(**self._asdict())] for p in self.products: lines.append(' - {0}'.format(str(p))) return '\n'.join(lines) # === Helpers === REGEX_BLING = re.compile('^\$') REGEX_WHITESPACE = re.compile('\s+') def cleanup_whitespace(text_content): """clean up junk whitespace that comes with every table cell""" return re.sub(REGEX_WHITESPACE, ' ', text_content.strip()) def get_next_sibling_text(element): return list(element.next_siblings)[1].get_text() def get_inner_display_text(element): return list(element.next_siblings)[1].find( 'span', attrs={'class': 'displayName'} ).get_text() def find_values(soup, label_text, value_getter): values = [] for label_elem in soup.find_all('div', text=label_text): values.append(value_getter(label_elem)) return values # === Section Parsers === def parse_profile_data(account_page_content): """ Parse user profile from /ClipperCard/dashboard.jsf """ soup = bs4.BeautifulSoup(account_page_content, "html.parser") profile_data = soup.find('div', attrs={'class': 'profileData'}) fields = profile_data.find_all('div', attrs={'class': 'fieldData'}) values = [cleanup_whitespace(f.get_text()) for f in fields] return Profile( name=values[0], email=values[1], address=' '.join(values[2:5]), phone=values[5] ) def parse_card_products(card_soup): """ Parse card product names and balances from /ClipperCard/dashboard.jsf """ section_products = [] for card_section in card_soup.find_all('div', attrs={'class': 'whiteGreyCardBox'}): products = [] blings = card_section.find_all('div', text=REGEX_BLING) for value_node in blings: name = list(value_node.previous_siblings)[1].get_text().strip(':') products.append(CardProduct(name=name, value=value_node.get_text())) caltrain = card_section.find_all('div', text=re.compile('^Valid till')) for value_train in caltrain: name = list(value_train.previous_siblings)[1].get_text().strip(':') value_time = value_train.get_text() products.append(CardProduct(name=name, value=value_time)) section_products.append(products) return section_products def parse_cards(account_page_content): """ Parse card metadata and product balances from /ClipperCard/dashboard.jsf """ begin = account_page_content.index(b'<!--YOUR CLIPPER CARDS-->') end = account_page_content.index(b'<!--END YOUR CLIPPER CARDS-->') card_soup = bs4.BeautifulSoup(account_page_content[begin:end], "html.parser") serial_numbers = find_values(card_soup, 'Serial Number:', get_next_sibling_text) nicknames = find_values(card_soup, 'Card Nickname:', get_inner_display_text) types = find_values(card_soup, 'Type:', get_next_sibling_text) statuses = find_values(card_soup, 'Status:', get_next_sibling_text) products = parse_card_products(card_soup) cards = [] for sn, nn, tp, st, pd in zip(serial_numbers, nicknames, types, statuses, products): cards.append(Card(serial_number=sn, nickname=nn, type=tp, status=st, products=pd)) return cards
en
0.749832
Copyright (c) 2012-2017 (https://github.com/clippercard/clippercard-python) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # === Simple Objects for ClipperCard data === # e.g. Cash value, BART HVD 60/64 # Adult, Senior, Youth, Disabled Discount # Active, Inactive # a list of CardProduct # === Helpers === clean up junk whitespace that comes with every table cell # === Section Parsers === Parse user profile from /ClipperCard/dashboard.jsf Parse card product names and balances from /ClipperCard/dashboard.jsf Parse card metadata and product balances from /ClipperCard/dashboard.jsf
2.242225
2
examples/et312-info.py
nannook206/buttshock-py
1
6625793
#!/bin/python3 # # Examples: # python3 info.py -p /dev/ttyUSB0 # import sys import fcntl import argparse from time import sleep sys.path.append("../") import buttshock.et312 def main(): modes = {0x76:"Waves", 0x77:"Stroke", 0x78:"Climb", 0x79:"Combo", 0x7a:"Intense", 0x7b:"Rhythm", 0x7c:"Audio1",0x7d:"Audio2", 0x7e:"Audio3", 0x80:"Random1", 0x81:"Random2", 0x82:"Toggle", 0x83:"Orgasm",0x84:"Torment",0x85:"Phase1",0x86:"Phase2",0x87:"Phase3", 0x88:"User1",0x89:"User2",0x8a:"User3",0x8b:"User4",0x8c:"User5",0:"None", 0x7f:"Split"} powerlevels = {1:"Low (1)",2:"Normal (2)",3:"High (3)"} parser = argparse.ArgumentParser() parser.add_argument("-p","--port",dest="port",help="Port for ET312 (default /dev/ttyUSB0)") args = parser.parse_args() port = "/dev/ttyUSB0" # lazy default if (args.port): port = args.port # Lock the serial port while we use it, wait a few seconds connected = False for _ in range(10): try: et312 = buttshock.et312.ET312SerialSync(port) if et312.port.isOpen(): fcntl.flock(et312.port.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) connected = True break except Exception as e: print(e) sleep(.2) if (not connected): print ("Failed") return try: print ("[+] connected") # no need to do a handshake unless we want to poke # print ("[+] trying handshake") # et312.perform_handshake() # print ("[+] handshake ok") print("ADC0 (current sense)\t\t: {0:#x}".format(et312.read(0x4060))) print("ADC1 (MA knob)\t\t\t: {0:#x}".format(et312.read(0x4061))) print("\tMA scaled value\t\t: %d (mode range %d-%d)" %(et312.read(0x420d),et312.read(0x4086),et312.read(0x4087))) print("ADC2 (PSU voltage)\t\t: {0:#x}".format(et312.read(0x4062))) print("ADC3 (Battery voltage)\t\t: {0:#x}".format(et312.read(0x4063))) print("\tBattery at boot\t\t: {0:.1f}%".format((et312.read(0x4203))*100/256)) print("ADC4 (Level A knob)\t\t: {0:#x}".format(et312.read(0x4064))) print("ADC5 (Level B knob)\t\t: {0:#x}".format(et312.read(0x4065))) currentmode =et312.read(0x407b) print("Power Level\t\t\t: "+powerlevels[et312.read(0x41f4)]) usermodes = et312.read(0x41f3)-0x87 print("User programs loaded\t\t: {0:#d}".format(usermodes)) for i in range (0,usermodes): startmodule = et312.read(0x8018+i) if (startmodule < 0xa0): programlookup = et312.read(0x8000+startmodule-0x60) programblockstart = 0x8040+programlookup else: programlookup = et312.read(0x8000+startmodule-0xa0) programblockstart = 0x8100+programlookup print("\tUser %d is module 0x%02x\t: 0x%04x (eeprom)"%(i+1,startmodule,programblockstart)) print("Current Mode\t\t\t: "+modes[currentmode]) if (currentmode == 0x7f): print("\tSplit Mode A\t\t: "+modes[et312.read(0x41f5)]) print("\tSplit Mode B\t\t: "+modes[et312.read(0x41f6)]) if (currentmode == 0x80): print("\tCurrent Random Mode\t: "+modes[et312.read(0x4074)]) timeleft = et312.read(0x4075) - et312.read(0x406a) if (timeleft<0): timeleft+=256 print("\tTime until change mode\t: {0:#d} seconds ".format(int(timeleft/1.91))) print("\tMode has been running\t: {0:#d} seconds".format(int((et312.read(0x4089)+et312.read(0x408a)*256)*1.048))) except Exception as e: print(e) if (et312): print("[+] resetting key") et312.reset_key() # reset cipher key so easy resync next time et312.close() if __name__ == "__main__": main()
#!/bin/python3 # # Examples: # python3 info.py -p /dev/ttyUSB0 # import sys import fcntl import argparse from time import sleep sys.path.append("../") import buttshock.et312 def main(): modes = {0x76:"Waves", 0x77:"Stroke", 0x78:"Climb", 0x79:"Combo", 0x7a:"Intense", 0x7b:"Rhythm", 0x7c:"Audio1",0x7d:"Audio2", 0x7e:"Audio3", 0x80:"Random1", 0x81:"Random2", 0x82:"Toggle", 0x83:"Orgasm",0x84:"Torment",0x85:"Phase1",0x86:"Phase2",0x87:"Phase3", 0x88:"User1",0x89:"User2",0x8a:"User3",0x8b:"User4",0x8c:"User5",0:"None", 0x7f:"Split"} powerlevels = {1:"Low (1)",2:"Normal (2)",3:"High (3)"} parser = argparse.ArgumentParser() parser.add_argument("-p","--port",dest="port",help="Port for ET312 (default /dev/ttyUSB0)") args = parser.parse_args() port = "/dev/ttyUSB0" # lazy default if (args.port): port = args.port # Lock the serial port while we use it, wait a few seconds connected = False for _ in range(10): try: et312 = buttshock.et312.ET312SerialSync(port) if et312.port.isOpen(): fcntl.flock(et312.port.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) connected = True break except Exception as e: print(e) sleep(.2) if (not connected): print ("Failed") return try: print ("[+] connected") # no need to do a handshake unless we want to poke # print ("[+] trying handshake") # et312.perform_handshake() # print ("[+] handshake ok") print("ADC0 (current sense)\t\t: {0:#x}".format(et312.read(0x4060))) print("ADC1 (MA knob)\t\t\t: {0:#x}".format(et312.read(0x4061))) print("\tMA scaled value\t\t: %d (mode range %d-%d)" %(et312.read(0x420d),et312.read(0x4086),et312.read(0x4087))) print("ADC2 (PSU voltage)\t\t: {0:#x}".format(et312.read(0x4062))) print("ADC3 (Battery voltage)\t\t: {0:#x}".format(et312.read(0x4063))) print("\tBattery at boot\t\t: {0:.1f}%".format((et312.read(0x4203))*100/256)) print("ADC4 (Level A knob)\t\t: {0:#x}".format(et312.read(0x4064))) print("ADC5 (Level B knob)\t\t: {0:#x}".format(et312.read(0x4065))) currentmode =et312.read(0x407b) print("Power Level\t\t\t: "+powerlevels[et312.read(0x41f4)]) usermodes = et312.read(0x41f3)-0x87 print("User programs loaded\t\t: {0:#d}".format(usermodes)) for i in range (0,usermodes): startmodule = et312.read(0x8018+i) if (startmodule < 0xa0): programlookup = et312.read(0x8000+startmodule-0x60) programblockstart = 0x8040+programlookup else: programlookup = et312.read(0x8000+startmodule-0xa0) programblockstart = 0x8100+programlookup print("\tUser %d is module 0x%02x\t: 0x%04x (eeprom)"%(i+1,startmodule,programblockstart)) print("Current Mode\t\t\t: "+modes[currentmode]) if (currentmode == 0x7f): print("\tSplit Mode A\t\t: "+modes[et312.read(0x41f5)]) print("\tSplit Mode B\t\t: "+modes[et312.read(0x41f6)]) if (currentmode == 0x80): print("\tCurrent Random Mode\t: "+modes[et312.read(0x4074)]) timeleft = et312.read(0x4075) - et312.read(0x406a) if (timeleft<0): timeleft+=256 print("\tTime until change mode\t: {0:#d} seconds ".format(int(timeleft/1.91))) print("\tMode has been running\t: {0:#d} seconds".format(int((et312.read(0x4089)+et312.read(0x408a)*256)*1.048))) except Exception as e: print(e) if (et312): print("[+] resetting key") et312.reset_key() # reset cipher key so easy resync next time et312.close() if __name__ == "__main__": main()
en
0.208008
#!/bin/python3 # # Examples: # python3 info.py -p /dev/ttyUSB0 # # lazy default # Lock the serial port while we use it, wait a few seconds # no need to do a handshake unless we want to poke # print ("[+] trying handshake") # et312.perform_handshake() # print ("[+] handshake ok") #x}".format(et312.read(0x4060))) #x}".format(et312.read(0x4061))) #x}".format(et312.read(0x4062))) #x}".format(et312.read(0x4063))) #x}".format(et312.read(0x4064))) #x}".format(et312.read(0x4065))) #d}".format(usermodes)) #d} seconds ".format(int(timeleft/1.91))) #d} seconds".format(int((et312.read(0x4089)+et312.read(0x408a)*256)*1.048))) # reset cipher key so easy resync next time
2.446251
2
blackjack_test.py
coolioasjulio/reinforcement-learning-playground
0
6625794
from keras.models import load_model import gym import numpy as np model = load_model('models/dqn_Blackjack-v0-43.h5') ENV_NAME = 'Blackjack-v0' # Get the environment and extract the number of actions. env = gym.make(ENV_NAME) def debug(msg, enabled): if enabled: print(msg) def play_game(debug_enabled=True): done = False score, dealer, usable = env.reset() reward = 0 debug('Start!\nScore: %s, Dealer: %s, Usable Ace: %s' % (score, dealer, bool(usable)), debug_enabled) while not done: action = np.argmax(model.predict(np.expand_dims([[score, dealer, usable]], axis=0))[0]) (score, dealer, usable), reward, done, _ = env.step(action) debug('\nAction: %s' % ('hit' if action == 1 else 'stick'), debug_enabled) debug('Score: %s, Dealer: %s, Usable Ace: %s' % (score, dealer, bool(usable)), debug_enabled) if reward < 0: debug('Lost!', debug_enabled) elif reward > 0: debug('Won!', debug_enabled) else: debug('Tie!', debug_enabled) return reward > 0, reward == 0, reward < 0 win_sum, tie_sum, lose_sum = 0, 0, 0 n_games = 1000 for i in range(n_games): result = play_game(False) win_sum += 1 if result[0] else 0 tie_sum += 1 if result[1] else 0 lose_sum += 1 if result[2] else 0 print('Win: %.2f, Tie: %.2f, Lose: %.2f' % (100 * win_sum / n_games, 100 * tie_sum / n_games, 100 * lose_sum / n_games))
from keras.models import load_model import gym import numpy as np model = load_model('models/dqn_Blackjack-v0-43.h5') ENV_NAME = 'Blackjack-v0' # Get the environment and extract the number of actions. env = gym.make(ENV_NAME) def debug(msg, enabled): if enabled: print(msg) def play_game(debug_enabled=True): done = False score, dealer, usable = env.reset() reward = 0 debug('Start!\nScore: %s, Dealer: %s, Usable Ace: %s' % (score, dealer, bool(usable)), debug_enabled) while not done: action = np.argmax(model.predict(np.expand_dims([[score, dealer, usable]], axis=0))[0]) (score, dealer, usable), reward, done, _ = env.step(action) debug('\nAction: %s' % ('hit' if action == 1 else 'stick'), debug_enabled) debug('Score: %s, Dealer: %s, Usable Ace: %s' % (score, dealer, bool(usable)), debug_enabled) if reward < 0: debug('Lost!', debug_enabled) elif reward > 0: debug('Won!', debug_enabled) else: debug('Tie!', debug_enabled) return reward > 0, reward == 0, reward < 0 win_sum, tie_sum, lose_sum = 0, 0, 0 n_games = 1000 for i in range(n_games): result = play_game(False) win_sum += 1 if result[0] else 0 tie_sum += 1 if result[1] else 0 lose_sum += 1 if result[2] else 0 print('Win: %.2f, Tie: %.2f, Lose: %.2f' % (100 * win_sum / n_games, 100 * tie_sum / n_games, 100 * lose_sum / n_games))
en
0.877973
# Get the environment and extract the number of actions.
2.480184
2
tests/__init__.py
OpenEntityMap/oem-client
0
6625795
from __future__ import absolute_import, division, print_function import logging logging.basicConfig(level=logging.DEBUG)
from __future__ import absolute_import, division, print_function import logging logging.basicConfig(level=logging.DEBUG)
none
1
1.214142
1
examples/wrappers.py
paolodelia99/py-pacman
4
6625796
<filename>examples/wrappers.py import gym import torch import numpy as np import torchvision.transforms as T from gym.spaces import Box class SkipFrame(gym.Wrapper): def __init__(self, env, skip): """Return only every `skip`-th frame""" super().__init__(env) self._skip = skip def step(self, action): """Repeat action, and sum reward""" total_reward = 0.0 done = False for i in range(self._skip): # Accumulate reward and repeat the same action obs, reward, done, info = self.env.step(action) total_reward += reward if done: break return obs, total_reward, done, info class GrayScaleObservation(gym.ObservationWrapper): def __init__(self, env): super().__init__(env) obs_shape = self.observation_space.shape[:2] self.observation_space = Box(low=0, high=255, shape=obs_shape, dtype=np.uint8) def permute_orientation(self, observation): # permute [H, W, C] array to [C, H, W] tensor observation = np.transpose(observation, (2, 0, 1)) observation = torch.tensor(observation.copy(), dtype=torch.float) return observation def observation(self, observation): observation = self.permute_orientation(observation) transform = T.Grayscale() observation = transform(observation) return observation class ResizeObservation(gym.ObservationWrapper): def __init__(self, env, shape): super().__init__(env) if isinstance(shape, int): self.shape = (shape, shape) else: self.shape = tuple(shape) obs_shape = self.shape + self.observation_space.shape[2:] self.observation_space = Box(low=0, high=255, shape=obs_shape, dtype=np.uint8) def observation(self, observation): transforms = T.Compose( [T.Resize(self.shape), T.Normalize(0, 255)] ) observation = transforms(observation).squeeze(0) return observation
<filename>examples/wrappers.py import gym import torch import numpy as np import torchvision.transforms as T from gym.spaces import Box class SkipFrame(gym.Wrapper): def __init__(self, env, skip): """Return only every `skip`-th frame""" super().__init__(env) self._skip = skip def step(self, action): """Repeat action, and sum reward""" total_reward = 0.0 done = False for i in range(self._skip): # Accumulate reward and repeat the same action obs, reward, done, info = self.env.step(action) total_reward += reward if done: break return obs, total_reward, done, info class GrayScaleObservation(gym.ObservationWrapper): def __init__(self, env): super().__init__(env) obs_shape = self.observation_space.shape[:2] self.observation_space = Box(low=0, high=255, shape=obs_shape, dtype=np.uint8) def permute_orientation(self, observation): # permute [H, W, C] array to [C, H, W] tensor observation = np.transpose(observation, (2, 0, 1)) observation = torch.tensor(observation.copy(), dtype=torch.float) return observation def observation(self, observation): observation = self.permute_orientation(observation) transform = T.Grayscale() observation = transform(observation) return observation class ResizeObservation(gym.ObservationWrapper): def __init__(self, env, shape): super().__init__(env) if isinstance(shape, int): self.shape = (shape, shape) else: self.shape = tuple(shape) obs_shape = self.shape + self.observation_space.shape[2:] self.observation_space = Box(low=0, high=255, shape=obs_shape, dtype=np.uint8) def observation(self, observation): transforms = T.Compose( [T.Resize(self.shape), T.Normalize(0, 255)] ) observation = transforms(observation).squeeze(0) return observation
en
0.71435
Return only every `skip`-th frame Repeat action, and sum reward # Accumulate reward and repeat the same action # permute [H, W, C] array to [C, H, W] tensor
2.494882
2
idseq_pipeline/commands/postprocess_functions.py
cdebourcy/idseq-pipeline
0
6625797
<filename>idseq_pipeline/commands/postprocess_functions.py import os import subprocess import json import shelve import logging import idseq_pipeline.commands.accessionid2seq_functions as accessionid2seq_functions from .common import * #pylint: disable=wildcard-import # data directories # from common import ROOT_DIR # from common import REF_DIR DEST_DIR = ROOT_DIR + '/idseq/data' # generated data go here TEMP_DIR = ROOT_DIR + '/tmp' # tmp directory with a lot of space for sorting large files # arguments from environment variables INPUT_BUCKET = os.environ.get('INPUT_BUCKET') OUTPUT_BUCKET = os.environ.get('OUTPUT_BUCKET') AWS_BATCH_JOB_ID = os.environ.get('AWS_BATCH_JOB_ID', 'local') SAMPLE_S3_INPUT_PATH = INPUT_BUCKET.rstrip('/') SAMPLE_S3_OUTPUT_PATH = OUTPUT_BUCKET.rstrip('/') sample_name = SAMPLE_S3_INPUT_PATH[5:].rstrip('/').replace('/', '-') SAMPLE_DIR = DEST_DIR + '/' + sample_name INPUT_DIR = SAMPLE_DIR + '/inputs' RESULT_DIR = SAMPLE_DIR + '/results' NT_LOC_DB = os.environ.get('NT_LOC_DB', "s3://idseq-database/20170824/blast_db/nt_loc.db") NT_DB = os.environ.get('NT_DB', "s3://idseq-database/20170824/blast_db/nt") # input files ACCESSION_ANNOTATED_FASTA = 'accessions.rapsearch2.gsnapl.fasta' GSNAP_M8_FILE = 'dedup.multihit.gsnapl.unmapped.bowtie2.lzw.cdhitdup.priceseqfilter.unmapped.star.m8' SUMMARY_MULTIHIT_GSNAPL_OUT = 'summary.multihit.gsnapl.unmapped.bowtie2.lzw.cdhitdup.priceseqfilter.unmapped.star.tab' SUMMARY_MULTIHIT_RAPSEARCH_OUT = 'summary.multihit.rapsearch2.filter.deuterostomes.taxids.gsnapl.unmapped.bowtie2.lzw.cdhitdup.priceseqfilter.unmapped.star.tab' # output files TAXID_ANNOT_FASTA = 'taxid_annot.fasta' TAXID_ANNOT_SORTED_FASTA_NT = 'taxid_annot_sorted_nt.fasta' TAXID_ANNOT_SORTED_FASTA_NR = 'taxid_annot_sorted_nr.fasta' TAXID_ANNOT_SORTED_FASTA_GENUS_NT = 'taxid_annot_sorted_genus_nt.fasta' TAXID_ANNOT_SORTED_FASTA_GENUS_NR = 'taxid_annot_sorted_genus_nr.fasta' TAXID_ANNOT_SORTED_FASTA_FAMILY_NT = 'taxid_annot_sorted_family_nt.fasta' TAXID_ANNOT_SORTED_FASTA_FAMILY_NR = 'taxid_annot_sorted_family_nr.fasta' TAXID_LOCATIONS_JSON_NT = 'taxid_locations_nt.json' TAXID_LOCATIONS_JSON_NR = 'taxid_locations_nr.json' TAXID_LOCATIONS_JSON_GENUS_NT = 'taxid_locations_genus_nt.json' TAXID_LOCATIONS_JSON_GENUS_NR = 'taxid_locations_genus_nr.json' TAXID_LOCATIONS_JSON_FAMILY_NT = 'taxid_locations_family_nt.json' TAXID_LOCATIONS_JSON_FAMILY_NR = 'taxid_locations_family_nr.json' TAXID_LOCATIONS_JSON_ALL = 'taxid_locations_combined.json' LOGS_OUT_BASENAME = 'postprocess-log' ALIGN_VIZ_DIR = 'align_viz' # target outputs by task TARGET_OUTPUTS = { "run_generate_taxid_fasta_from_hit_summaries": [os.path.join(RESULT_DIR, TAXID_ANNOT_FASTA)], "run_generate_taxid_locator__1": [ os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_NT), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_NT) ], "run_generate_taxid_locator__2": [ os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_NR), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_NR) ], "run_generate_taxid_locator__3": [ os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_GENUS_NT), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_GENUS_NT) ], "run_generate_taxid_locator__4": [ os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_GENUS_NR), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_GENUS_NR) ], "run_generate_taxid_locator__5": [ os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_FAMILY_NT), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_FAMILY_NT) ], "run_generate_taxid_locator__6": [ os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_FAMILY_NR), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_FAMILY_NR) ], "run_combine_json": [os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_ALL)], "run_generate_align_viz": [os.path.join(RESULT_DIR, "%s.summary" % ALIGN_VIZ_DIR)] } # Processing functions def remove_annotation(read_id): result = re.sub(r'NT:(.*?):', '', read_id) result = re.sub(r'NR:(.*?):', '', result) return result def parse_hits(hit_summary_files): """Return map of {NT, NR} => read_id => (hit_taxid_str, hit_level_str)""" valid_hits = {} for count_type, summary_file in hit_summary_files.items(): hits = {} with open(summary_file, "rb") as sf: for hit_line in sf: hit_line_columns = hit_line.strip().split("\t") if len(hit_line_columns) >= 3: hit_read_id = hit_line_columns[0] hit_level_str = hit_line_columns[1] hit_taxid_str = hit_line_columns[2] hits[hit_read_id] = (hit_taxid_str, hit_level_str) valid_hits[count_type] = hits return valid_hits def generate_taxid_fasta_from_hit_summaries( input_fasta_file, hit_summary_files, lineage_path, output_fasta_file): """Intermediate conversion step that includes handling of non-specific hits with artificial tax_ids. """ lineage_map = shelve.open(lineage_path) valid_hits = parse_hits(hit_summary_files) def get_valid_lineage(read_id, count_type): # If the read aligned to something, then it would be present in the # summary file for count type, and correspondingly in valid_hits[ # count_type], even if the hits disagree so much that the # "valid_hits" entry is just ("-1", "-1"). If the read didn't align # to anything, we also represent that with ("-1", "-1"). This ("-1", # "-1") gets translated to NULL_LINEAGE. hit_taxid_str, hit_level_str = valid_hits[count_type].get( read_id, ("-1", "-1")) hit_lineage = lineage_map.get(hit_taxid_str, NULL_LINEAGE) return validate_taxid_lineage(hit_lineage, hit_taxid_str, hit_level_str) input_fasta_f = open(input_fasta_file, 'rb') output_fasta_f = open(output_fasta_file, 'wb') sequence_name = input_fasta_f.readline() sequence_data = input_fasta_f.readline() while len(sequence_name) > 0 and len(sequence_data) > 0: # Example read_id: "NR::NT:CP010376.2:NB501961:14:HM7TLBGX2:1:23109 # :12720:8743/2" # Translate the read information into our custom format with fake # taxids. accession_annotated_read_id = sequence_name.rstrip().lstrip('>') read_id = accession_annotated_read_id.split(":", 4)[-1] nr_taxid_species, nr_taxid_genus, nr_taxid_family = get_valid_lineage( read_id, 'NR') nt_taxid_species, nt_taxid_genus, nt_taxid_family = get_valid_lineage( read_id, 'NT') family_str = 'family_nr:' + nr_taxid_family + ':family_nt:' + nt_taxid_family genus_str = ':genus_nr:' + nr_taxid_genus + ':genus_nt:' + nt_taxid_genus species_str = ':species_nr:' + nr_taxid_species + ':species_nt:' + nt_taxid_species new_read_name = (family_str + genus_str + species_str + ':' + accession_annotated_read_id) output_fasta_f.write(">%s\n" % new_read_name) output_fasta_f.write(sequence_data) sequence_name = input_fasta_f.readline() sequence_data = input_fasta_f.readline() input_fasta_f.close() output_fasta_f.close() def get_taxid(sequence_name, taxid_field): parts = sequence_name.replace('>', ':').split(":%s:" % taxid_field) if len(parts) <= 1: # Sequence_name empty or taxid_field not found return 'none' taxid = parts[1].split(":")[0] # Example sequence_name: ">nr:-100:nt:684552:NR::NT:LT629734.1:HWI-ST640 # :828:H917FADXX:2:1101:1424:15119/1" return taxid def get_taxid_field_num(taxid_field, input_fasta): with open(input_fasta) as f: sequence_name = f.readline() return sequence_name.replace('>', ':').split(":").index(taxid_field) + 1 def generate_taxid_locator(input_fasta, taxid_field, hit_type, output_fasta, output_json): taxid_field_num = get_taxid_field_num(taxid_field, input_fasta) # Put every 2-line fasta record on a single line with delimiter # ":lineseparator:": cmd = "awk 'NR % 2 == 1 { o=$0 ; next } { print o \":lineseparator:\" $0 }' " + input_fasta # Sort the records based on the field containing the taxids cmd += " | sort -T %s --key %s --field-separator ':' --numeric-sort" % ( TEMP_DIR, taxid_field_num) # Split every record back over 2 lines cmd += " | sed 's/:lineseparator:/\\n/g' > %s" % output_fasta subprocess.check_output(cmd, shell=True) # Make JSON file giving the byte range of the file corresponding to each # taxid taxon_sequence_locations = [] f = open(output_fasta, 'rb') sequence_name = f.readline() sequence_data = f.readline() taxid = get_taxid(sequence_name, taxid_field) first_byte = 0 end_byte = first_byte + len(sequence_name) + len(sequence_data) while len(sequence_name) > 0 and len(sequence_data) > 0: sequence_name = f.readline() sequence_data = f.readline() new_taxid = get_taxid(sequence_name, taxid_field) if new_taxid != taxid: # Note on boundary condition: when end of file is reached, then # sequence_name == '' => new_taxid == 'none' => new_taxid != taxid # so last record will be written to output correctly. taxon_sequence_locations.append({ 'taxid': int(taxid), 'first_byte': first_byte, 'last_byte': end_byte - 1, 'hit_type': hit_type }) taxid = new_taxid first_byte = end_byte end_byte = first_byte + len(sequence_name) + len(sequence_data) else: end_byte += len(sequence_name) + len(sequence_data) f.close() with open(output_json, 'wb') as f: json.dump(taxon_sequence_locations, f) def combine_json(input_json_list, output_json): output = [] for input_json in input_json_list: with open(input_json) as f: output.extend(json.load(f)) with open(output_json, 'wb') as outf: json.dump(output, outf) # Job functions def run_generate_align_viz(input_fasta, input_m8, output_dir): write_to_log("Generating alignment visualization...") nt_loc_db = fetch_reference(NT_LOC_DB) summary_file_name = accessionid2seq_functions.generate_alignment_viz_json( NT_DB, nt_loc_db, "NT", input_m8, input_fasta, output_dir) # Copy the data over cmd = "aws s3 cp --quiet %s %s/align_viz --recursive" % ( output_dir, SAMPLE_S3_OUTPUT_PATH) execute_command(cmd) cmd = "aws s3 cp --quiet %s %s/" % (summary_file_name, SAMPLE_S3_OUTPUT_PATH) execute_command(cmd) def run_generate_taxid_fasta_from_hit_summaries(input_fasta, hit_summary_files, output_fasta): write_to_log("Generating tax_id FASTA from hit summaries...") lineage_path = fetch_reference(LINEAGE_SHELF) generate_taxid_fasta_from_hit_summaries(input_fasta, hit_summary_files, lineage_path, output_fasta) logging.getLogger().info("finished job") cmd = "aws s3 cp --quiet %s %s/" % (output_fasta, SAMPLE_S3_OUTPUT_PATH) execute_command(cmd) def run_generate_taxid_locator(input_fasta, taxid_field, hit_type, output_fasta, output_json): write_to_log("Generating tax_id locator...") generate_taxid_locator(input_fasta, taxid_field, hit_type, output_fasta, output_json) logging.getLogger().info("finished job") cmd = "aws s3 cp --quiet %s %s/" % (output_fasta, SAMPLE_S3_OUTPUT_PATH) execute_command(cmd) cmd = "aws s3 cp --quiet %s %s/" % (output_json, SAMPLE_S3_OUTPUT_PATH) execute_command(cmd) def run_combine_json(input_json_list, output_json): write_to_log("Combining JSON files...") combine_json(input_json_list, output_json) logging.getLogger().info("finished job") cmd = "aws s3 cp --quiet %s %s/" % (output_json, SAMPLE_S3_OUTPUT_PATH) execute_command(cmd) def run_stage3(lazy_run=False): assert not lazy_run, "run_stage3 was called with lazy_run" # Make data directories execute_command("mkdir -p %s %s %s %s" % (SAMPLE_DIR, RESULT_DIR, REF_DIR, TEMP_DIR)) # Configure logger log_file = "%s/%s.%s.txt" % (RESULT_DIR, LOGS_OUT_BASENAME, AWS_BATCH_JOB_ID) configure_logger(log_file) print("Starting stage...") # Download input execute_command("aws s3 cp --quiet %s/%s %s/" % (SAMPLE_S3_INPUT_PATH, ACCESSION_ANNOTATED_FASTA, INPUT_DIR)) input_file = os.path.join(INPUT_DIR, ACCESSION_ANNOTATED_FASTA) # Download m8 execute_command("aws s3 cp --quiet %s/%s %s/" % (SAMPLE_S3_INPUT_PATH, GSNAP_M8_FILE, INPUT_DIR)) input_m8 = os.path.join(INPUT_DIR, GSNAP_M8_FILE) # Download hit level files hit_summary_files = { 'NT': os.path.join(INPUT_DIR, SUMMARY_MULTIHIT_GSNAPL_OUT), 'NR': os.path.join(INPUT_DIR, SUMMARY_MULTIHIT_RAPSEARCH_OUT) } for local_file in hit_summary_files.values(): execute_command("aws s3 cp --quiet %s/%s %s/" % (SAMPLE_S3_INPUT_PATH, os.path.basename(local_file), INPUT_DIR)) def s3_out_and_title(title): return {"sample_s3_output_path": SAMPLE_S3_OUTPUT_PATH, "title": title} # Ex: run_and_log(log_params, target_outputs, lazy_run, func_name, *args) # TODO: Get rid of run_and_log pattern for simplification # Generate taxid fasta log_params = s3_out_and_title( "run_generate_taxid_fasta_from_hit_summaries") run_and_log(log_params, TARGET_OUTPUTS["run_generate_taxid_fasta_from_hit_summaries"], False, run_generate_taxid_fasta_from_hit_summaries, input_file, hit_summary_files, os.path.join(RESULT_DIR, TAXID_ANNOT_FASTA)) # SPECIES level # Generate taxid locator for NT log_params = s3_out_and_title( "run_generate_taxid_locator for NT") run_and_log(log_params, TARGET_OUTPUTS["run_generate_taxid_locator__1"], False, run_generate_taxid_locator, os.path.join(RESULT_DIR, TAXID_ANNOT_FASTA), 'species_nt', 'NT', os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_NT), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_NT)) # Generate taxid locator for NR log_params = s3_out_and_title( "run_generate_taxid_locator for NR") run_and_log(log_params, TARGET_OUTPUTS["run_generate_taxid_locator__2"], False, run_generate_taxid_locator, os.path.join(RESULT_DIR, TAXID_ANNOT_FASTA), 'species_nr', 'NR', os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_NR), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_NR)) # GENUS level # Generate taxid locator for NT log_params = s3_out_and_title( "run_generate_taxid_locator for NT") run_and_log(log_params, TARGET_OUTPUTS["run_generate_taxid_locator__3"], False, run_generate_taxid_locator, os.path.join(RESULT_DIR, TAXID_ANNOT_FASTA), 'genus_nt', 'NT', os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_GENUS_NT), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_GENUS_NT)) # Generate taxid locator for NR log_params = s3_out_and_title( "run_generate_taxid_locator for NR") run_and_log(log_params, TARGET_OUTPUTS["run_generate_taxid_locator__4"], False, run_generate_taxid_locator, os.path.join(RESULT_DIR, TAXID_ANNOT_FASTA), 'genus_nr', 'NR', os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_GENUS_NR), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_GENUS_NR)) # FAMILY level # Generate taxid locator for NT log_params = s3_out_and_title( "run_generate_taxid_locator for NT") run_and_log(log_params, TARGET_OUTPUTS["run_generate_taxid_locator__5"], False, run_generate_taxid_locator, os.path.join(RESULT_DIR, TAXID_ANNOT_FASTA), 'family_nt', 'NT', os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_FAMILY_NT), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_FAMILY_NT)) # Generate taxid locator for NR log_params = s3_out_and_title( "run_generate_taxid_locator for NR") run_and_log(log_params, TARGET_OUTPUTS["run_generate_taxid_locator__6"], False, run_generate_taxid_locator, os.path.join(RESULT_DIR, TAXID_ANNOT_FASTA), 'family_nr', 'NR', os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_FAMILY_NR), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_FAMILY_NR)) # Generate alignment visualization log_params = s3_out_and_title("run_generate_align_viz") run_and_log(log_params, TARGET_OUTPUTS["run_generate_align_viz"], False, run_generate_align_viz, os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_NT), input_m8, os.path.join(RESULT_DIR, ALIGN_VIZ_DIR)) # Combine results log_params = s3_out_and_title("run_combine_json") input_files_basenames = [ TAXID_LOCATIONS_JSON_NT, TAXID_LOCATIONS_JSON_NR, TAXID_LOCATIONS_JSON_GENUS_NT, TAXID_LOCATIONS_JSON_GENUS_NR, TAXID_LOCATIONS_JSON_FAMILY_NT, TAXID_LOCATIONS_JSON_FAMILY_NR ] input_files = [os.path.join(RESULT_DIR, f) for f in input_files_basenames] run_and_log(log_params, TARGET_OUTPUTS["run_combine_json"], False, run_combine_json, input_files, os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_ALL))
<filename>idseq_pipeline/commands/postprocess_functions.py import os import subprocess import json import shelve import logging import idseq_pipeline.commands.accessionid2seq_functions as accessionid2seq_functions from .common import * #pylint: disable=wildcard-import # data directories # from common import ROOT_DIR # from common import REF_DIR DEST_DIR = ROOT_DIR + '/idseq/data' # generated data go here TEMP_DIR = ROOT_DIR + '/tmp' # tmp directory with a lot of space for sorting large files # arguments from environment variables INPUT_BUCKET = os.environ.get('INPUT_BUCKET') OUTPUT_BUCKET = os.environ.get('OUTPUT_BUCKET') AWS_BATCH_JOB_ID = os.environ.get('AWS_BATCH_JOB_ID', 'local') SAMPLE_S3_INPUT_PATH = INPUT_BUCKET.rstrip('/') SAMPLE_S3_OUTPUT_PATH = OUTPUT_BUCKET.rstrip('/') sample_name = SAMPLE_S3_INPUT_PATH[5:].rstrip('/').replace('/', '-') SAMPLE_DIR = DEST_DIR + '/' + sample_name INPUT_DIR = SAMPLE_DIR + '/inputs' RESULT_DIR = SAMPLE_DIR + '/results' NT_LOC_DB = os.environ.get('NT_LOC_DB', "s3://idseq-database/20170824/blast_db/nt_loc.db") NT_DB = os.environ.get('NT_DB', "s3://idseq-database/20170824/blast_db/nt") # input files ACCESSION_ANNOTATED_FASTA = 'accessions.rapsearch2.gsnapl.fasta' GSNAP_M8_FILE = 'dedup.multihit.gsnapl.unmapped.bowtie2.lzw.cdhitdup.priceseqfilter.unmapped.star.m8' SUMMARY_MULTIHIT_GSNAPL_OUT = 'summary.multihit.gsnapl.unmapped.bowtie2.lzw.cdhitdup.priceseqfilter.unmapped.star.tab' SUMMARY_MULTIHIT_RAPSEARCH_OUT = 'summary.multihit.rapsearch2.filter.deuterostomes.taxids.gsnapl.unmapped.bowtie2.lzw.cdhitdup.priceseqfilter.unmapped.star.tab' # output files TAXID_ANNOT_FASTA = 'taxid_annot.fasta' TAXID_ANNOT_SORTED_FASTA_NT = 'taxid_annot_sorted_nt.fasta' TAXID_ANNOT_SORTED_FASTA_NR = 'taxid_annot_sorted_nr.fasta' TAXID_ANNOT_SORTED_FASTA_GENUS_NT = 'taxid_annot_sorted_genus_nt.fasta' TAXID_ANNOT_SORTED_FASTA_GENUS_NR = 'taxid_annot_sorted_genus_nr.fasta' TAXID_ANNOT_SORTED_FASTA_FAMILY_NT = 'taxid_annot_sorted_family_nt.fasta' TAXID_ANNOT_SORTED_FASTA_FAMILY_NR = 'taxid_annot_sorted_family_nr.fasta' TAXID_LOCATIONS_JSON_NT = 'taxid_locations_nt.json' TAXID_LOCATIONS_JSON_NR = 'taxid_locations_nr.json' TAXID_LOCATIONS_JSON_GENUS_NT = 'taxid_locations_genus_nt.json' TAXID_LOCATIONS_JSON_GENUS_NR = 'taxid_locations_genus_nr.json' TAXID_LOCATIONS_JSON_FAMILY_NT = 'taxid_locations_family_nt.json' TAXID_LOCATIONS_JSON_FAMILY_NR = 'taxid_locations_family_nr.json' TAXID_LOCATIONS_JSON_ALL = 'taxid_locations_combined.json' LOGS_OUT_BASENAME = 'postprocess-log' ALIGN_VIZ_DIR = 'align_viz' # target outputs by task TARGET_OUTPUTS = { "run_generate_taxid_fasta_from_hit_summaries": [os.path.join(RESULT_DIR, TAXID_ANNOT_FASTA)], "run_generate_taxid_locator__1": [ os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_NT), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_NT) ], "run_generate_taxid_locator__2": [ os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_NR), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_NR) ], "run_generate_taxid_locator__3": [ os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_GENUS_NT), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_GENUS_NT) ], "run_generate_taxid_locator__4": [ os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_GENUS_NR), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_GENUS_NR) ], "run_generate_taxid_locator__5": [ os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_FAMILY_NT), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_FAMILY_NT) ], "run_generate_taxid_locator__6": [ os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_FAMILY_NR), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_FAMILY_NR) ], "run_combine_json": [os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_ALL)], "run_generate_align_viz": [os.path.join(RESULT_DIR, "%s.summary" % ALIGN_VIZ_DIR)] } # Processing functions def remove_annotation(read_id): result = re.sub(r'NT:(.*?):', '', read_id) result = re.sub(r'NR:(.*?):', '', result) return result def parse_hits(hit_summary_files): """Return map of {NT, NR} => read_id => (hit_taxid_str, hit_level_str)""" valid_hits = {} for count_type, summary_file in hit_summary_files.items(): hits = {} with open(summary_file, "rb") as sf: for hit_line in sf: hit_line_columns = hit_line.strip().split("\t") if len(hit_line_columns) >= 3: hit_read_id = hit_line_columns[0] hit_level_str = hit_line_columns[1] hit_taxid_str = hit_line_columns[2] hits[hit_read_id] = (hit_taxid_str, hit_level_str) valid_hits[count_type] = hits return valid_hits def generate_taxid_fasta_from_hit_summaries( input_fasta_file, hit_summary_files, lineage_path, output_fasta_file): """Intermediate conversion step that includes handling of non-specific hits with artificial tax_ids. """ lineage_map = shelve.open(lineage_path) valid_hits = parse_hits(hit_summary_files) def get_valid_lineage(read_id, count_type): # If the read aligned to something, then it would be present in the # summary file for count type, and correspondingly in valid_hits[ # count_type], even if the hits disagree so much that the # "valid_hits" entry is just ("-1", "-1"). If the read didn't align # to anything, we also represent that with ("-1", "-1"). This ("-1", # "-1") gets translated to NULL_LINEAGE. hit_taxid_str, hit_level_str = valid_hits[count_type].get( read_id, ("-1", "-1")) hit_lineage = lineage_map.get(hit_taxid_str, NULL_LINEAGE) return validate_taxid_lineage(hit_lineage, hit_taxid_str, hit_level_str) input_fasta_f = open(input_fasta_file, 'rb') output_fasta_f = open(output_fasta_file, 'wb') sequence_name = input_fasta_f.readline() sequence_data = input_fasta_f.readline() while len(sequence_name) > 0 and len(sequence_data) > 0: # Example read_id: "NR::NT:CP010376.2:NB501961:14:HM7TLBGX2:1:23109 # :12720:8743/2" # Translate the read information into our custom format with fake # taxids. accession_annotated_read_id = sequence_name.rstrip().lstrip('>') read_id = accession_annotated_read_id.split(":", 4)[-1] nr_taxid_species, nr_taxid_genus, nr_taxid_family = get_valid_lineage( read_id, 'NR') nt_taxid_species, nt_taxid_genus, nt_taxid_family = get_valid_lineage( read_id, 'NT') family_str = 'family_nr:' + nr_taxid_family + ':family_nt:' + nt_taxid_family genus_str = ':genus_nr:' + nr_taxid_genus + ':genus_nt:' + nt_taxid_genus species_str = ':species_nr:' + nr_taxid_species + ':species_nt:' + nt_taxid_species new_read_name = (family_str + genus_str + species_str + ':' + accession_annotated_read_id) output_fasta_f.write(">%s\n" % new_read_name) output_fasta_f.write(sequence_data) sequence_name = input_fasta_f.readline() sequence_data = input_fasta_f.readline() input_fasta_f.close() output_fasta_f.close() def get_taxid(sequence_name, taxid_field): parts = sequence_name.replace('>', ':').split(":%s:" % taxid_field) if len(parts) <= 1: # Sequence_name empty or taxid_field not found return 'none' taxid = parts[1].split(":")[0] # Example sequence_name: ">nr:-100:nt:684552:NR::NT:LT629734.1:HWI-ST640 # :828:H917FADXX:2:1101:1424:15119/1" return taxid def get_taxid_field_num(taxid_field, input_fasta): with open(input_fasta) as f: sequence_name = f.readline() return sequence_name.replace('>', ':').split(":").index(taxid_field) + 1 def generate_taxid_locator(input_fasta, taxid_field, hit_type, output_fasta, output_json): taxid_field_num = get_taxid_field_num(taxid_field, input_fasta) # Put every 2-line fasta record on a single line with delimiter # ":lineseparator:": cmd = "awk 'NR % 2 == 1 { o=$0 ; next } { print o \":lineseparator:\" $0 }' " + input_fasta # Sort the records based on the field containing the taxids cmd += " | sort -T %s --key %s --field-separator ':' --numeric-sort" % ( TEMP_DIR, taxid_field_num) # Split every record back over 2 lines cmd += " | sed 's/:lineseparator:/\\n/g' > %s" % output_fasta subprocess.check_output(cmd, shell=True) # Make JSON file giving the byte range of the file corresponding to each # taxid taxon_sequence_locations = [] f = open(output_fasta, 'rb') sequence_name = f.readline() sequence_data = f.readline() taxid = get_taxid(sequence_name, taxid_field) first_byte = 0 end_byte = first_byte + len(sequence_name) + len(sequence_data) while len(sequence_name) > 0 and len(sequence_data) > 0: sequence_name = f.readline() sequence_data = f.readline() new_taxid = get_taxid(sequence_name, taxid_field) if new_taxid != taxid: # Note on boundary condition: when end of file is reached, then # sequence_name == '' => new_taxid == 'none' => new_taxid != taxid # so last record will be written to output correctly. taxon_sequence_locations.append({ 'taxid': int(taxid), 'first_byte': first_byte, 'last_byte': end_byte - 1, 'hit_type': hit_type }) taxid = new_taxid first_byte = end_byte end_byte = first_byte + len(sequence_name) + len(sequence_data) else: end_byte += len(sequence_name) + len(sequence_data) f.close() with open(output_json, 'wb') as f: json.dump(taxon_sequence_locations, f) def combine_json(input_json_list, output_json): output = [] for input_json in input_json_list: with open(input_json) as f: output.extend(json.load(f)) with open(output_json, 'wb') as outf: json.dump(output, outf) # Job functions def run_generate_align_viz(input_fasta, input_m8, output_dir): write_to_log("Generating alignment visualization...") nt_loc_db = fetch_reference(NT_LOC_DB) summary_file_name = accessionid2seq_functions.generate_alignment_viz_json( NT_DB, nt_loc_db, "NT", input_m8, input_fasta, output_dir) # Copy the data over cmd = "aws s3 cp --quiet %s %s/align_viz --recursive" % ( output_dir, SAMPLE_S3_OUTPUT_PATH) execute_command(cmd) cmd = "aws s3 cp --quiet %s %s/" % (summary_file_name, SAMPLE_S3_OUTPUT_PATH) execute_command(cmd) def run_generate_taxid_fasta_from_hit_summaries(input_fasta, hit_summary_files, output_fasta): write_to_log("Generating tax_id FASTA from hit summaries...") lineage_path = fetch_reference(LINEAGE_SHELF) generate_taxid_fasta_from_hit_summaries(input_fasta, hit_summary_files, lineage_path, output_fasta) logging.getLogger().info("finished job") cmd = "aws s3 cp --quiet %s %s/" % (output_fasta, SAMPLE_S3_OUTPUT_PATH) execute_command(cmd) def run_generate_taxid_locator(input_fasta, taxid_field, hit_type, output_fasta, output_json): write_to_log("Generating tax_id locator...") generate_taxid_locator(input_fasta, taxid_field, hit_type, output_fasta, output_json) logging.getLogger().info("finished job") cmd = "aws s3 cp --quiet %s %s/" % (output_fasta, SAMPLE_S3_OUTPUT_PATH) execute_command(cmd) cmd = "aws s3 cp --quiet %s %s/" % (output_json, SAMPLE_S3_OUTPUT_PATH) execute_command(cmd) def run_combine_json(input_json_list, output_json): write_to_log("Combining JSON files...") combine_json(input_json_list, output_json) logging.getLogger().info("finished job") cmd = "aws s3 cp --quiet %s %s/" % (output_json, SAMPLE_S3_OUTPUT_PATH) execute_command(cmd) def run_stage3(lazy_run=False): assert not lazy_run, "run_stage3 was called with lazy_run" # Make data directories execute_command("mkdir -p %s %s %s %s" % (SAMPLE_DIR, RESULT_DIR, REF_DIR, TEMP_DIR)) # Configure logger log_file = "%s/%s.%s.txt" % (RESULT_DIR, LOGS_OUT_BASENAME, AWS_BATCH_JOB_ID) configure_logger(log_file) print("Starting stage...") # Download input execute_command("aws s3 cp --quiet %s/%s %s/" % (SAMPLE_S3_INPUT_PATH, ACCESSION_ANNOTATED_FASTA, INPUT_DIR)) input_file = os.path.join(INPUT_DIR, ACCESSION_ANNOTATED_FASTA) # Download m8 execute_command("aws s3 cp --quiet %s/%s %s/" % (SAMPLE_S3_INPUT_PATH, GSNAP_M8_FILE, INPUT_DIR)) input_m8 = os.path.join(INPUT_DIR, GSNAP_M8_FILE) # Download hit level files hit_summary_files = { 'NT': os.path.join(INPUT_DIR, SUMMARY_MULTIHIT_GSNAPL_OUT), 'NR': os.path.join(INPUT_DIR, SUMMARY_MULTIHIT_RAPSEARCH_OUT) } for local_file in hit_summary_files.values(): execute_command("aws s3 cp --quiet %s/%s %s/" % (SAMPLE_S3_INPUT_PATH, os.path.basename(local_file), INPUT_DIR)) def s3_out_and_title(title): return {"sample_s3_output_path": SAMPLE_S3_OUTPUT_PATH, "title": title} # Ex: run_and_log(log_params, target_outputs, lazy_run, func_name, *args) # TODO: Get rid of run_and_log pattern for simplification # Generate taxid fasta log_params = s3_out_and_title( "run_generate_taxid_fasta_from_hit_summaries") run_and_log(log_params, TARGET_OUTPUTS["run_generate_taxid_fasta_from_hit_summaries"], False, run_generate_taxid_fasta_from_hit_summaries, input_file, hit_summary_files, os.path.join(RESULT_DIR, TAXID_ANNOT_FASTA)) # SPECIES level # Generate taxid locator for NT log_params = s3_out_and_title( "run_generate_taxid_locator for NT") run_and_log(log_params, TARGET_OUTPUTS["run_generate_taxid_locator__1"], False, run_generate_taxid_locator, os.path.join(RESULT_DIR, TAXID_ANNOT_FASTA), 'species_nt', 'NT', os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_NT), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_NT)) # Generate taxid locator for NR log_params = s3_out_and_title( "run_generate_taxid_locator for NR") run_and_log(log_params, TARGET_OUTPUTS["run_generate_taxid_locator__2"], False, run_generate_taxid_locator, os.path.join(RESULT_DIR, TAXID_ANNOT_FASTA), 'species_nr', 'NR', os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_NR), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_NR)) # GENUS level # Generate taxid locator for NT log_params = s3_out_and_title( "run_generate_taxid_locator for NT") run_and_log(log_params, TARGET_OUTPUTS["run_generate_taxid_locator__3"], False, run_generate_taxid_locator, os.path.join(RESULT_DIR, TAXID_ANNOT_FASTA), 'genus_nt', 'NT', os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_GENUS_NT), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_GENUS_NT)) # Generate taxid locator for NR log_params = s3_out_and_title( "run_generate_taxid_locator for NR") run_and_log(log_params, TARGET_OUTPUTS["run_generate_taxid_locator__4"], False, run_generate_taxid_locator, os.path.join(RESULT_DIR, TAXID_ANNOT_FASTA), 'genus_nr', 'NR', os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_GENUS_NR), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_GENUS_NR)) # FAMILY level # Generate taxid locator for NT log_params = s3_out_and_title( "run_generate_taxid_locator for NT") run_and_log(log_params, TARGET_OUTPUTS["run_generate_taxid_locator__5"], False, run_generate_taxid_locator, os.path.join(RESULT_DIR, TAXID_ANNOT_FASTA), 'family_nt', 'NT', os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_FAMILY_NT), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_FAMILY_NT)) # Generate taxid locator for NR log_params = s3_out_and_title( "run_generate_taxid_locator for NR") run_and_log(log_params, TARGET_OUTPUTS["run_generate_taxid_locator__6"], False, run_generate_taxid_locator, os.path.join(RESULT_DIR, TAXID_ANNOT_FASTA), 'family_nr', 'NR', os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_FAMILY_NR), os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_FAMILY_NR)) # Generate alignment visualization log_params = s3_out_and_title("run_generate_align_viz") run_and_log(log_params, TARGET_OUTPUTS["run_generate_align_viz"], False, run_generate_align_viz, os.path.join(RESULT_DIR, TAXID_ANNOT_SORTED_FASTA_NT), input_m8, os.path.join(RESULT_DIR, ALIGN_VIZ_DIR)) # Combine results log_params = s3_out_and_title("run_combine_json") input_files_basenames = [ TAXID_LOCATIONS_JSON_NT, TAXID_LOCATIONS_JSON_NR, TAXID_LOCATIONS_JSON_GENUS_NT, TAXID_LOCATIONS_JSON_GENUS_NR, TAXID_LOCATIONS_JSON_FAMILY_NT, TAXID_LOCATIONS_JSON_FAMILY_NR ] input_files = [os.path.join(RESULT_DIR, f) for f in input_files_basenames] run_and_log(log_params, TARGET_OUTPUTS["run_combine_json"], False, run_combine_json, input_files, os.path.join(RESULT_DIR, TAXID_LOCATIONS_JSON_ALL))
en
0.786436
#pylint: disable=wildcard-import # data directories # from common import ROOT_DIR # from common import REF_DIR # generated data go here # tmp directory with a lot of space for sorting large files # arguments from environment variables # input files # output files # target outputs by task # Processing functions Return map of {NT, NR} => read_id => (hit_taxid_str, hit_level_str) Intermediate conversion step that includes handling of non-specific hits with artificial tax_ids. # If the read aligned to something, then it would be present in the # summary file for count type, and correspondingly in valid_hits[ # count_type], even if the hits disagree so much that the # "valid_hits" entry is just ("-1", "-1"). If the read didn't align # to anything, we also represent that with ("-1", "-1"). This ("-1", # "-1") gets translated to NULL_LINEAGE. # Example read_id: "NR::NT:CP010376.2:NB501961:14:HM7TLBGX2:1:23109 # :12720:8743/2" # Translate the read information into our custom format with fake # taxids. # Sequence_name empty or taxid_field not found # Example sequence_name: ">nr:-100:nt:684552:NR::NT:LT629734.1:HWI-ST640 # :828:H917FADXX:2:1101:1424:15119/1" # Put every 2-line fasta record on a single line with delimiter # ":lineseparator:": # Sort the records based on the field containing the taxids # Split every record back over 2 lines # Make JSON file giving the byte range of the file corresponding to each # taxid # Note on boundary condition: when end of file is reached, then # sequence_name == '' => new_taxid == 'none' => new_taxid != taxid # so last record will be written to output correctly. # Job functions # Copy the data over # Make data directories # Configure logger # Download input # Download m8 # Download hit level files # Ex: run_and_log(log_params, target_outputs, lazy_run, func_name, *args) # TODO: Get rid of run_and_log pattern for simplification # Generate taxid fasta # SPECIES level # Generate taxid locator for NT # Generate taxid locator for NR # GENUS level # Generate taxid locator for NT # Generate taxid locator for NR # FAMILY level # Generate taxid locator for NT # Generate taxid locator for NR # Generate alignment visualization # Combine results
2.172007
2
test/format/conftest.py
di/pip-audit
1
6625798
<reponame>di/pip-audit from typing import Dict, List import pytest from packaging.version import Version import pip_audit.service as service _TEST_VULN_DATA: Dict[service.Dependency, List[service.VulnerabilityResult]] = { service.Dependency(package="foo", version="1.0"): [ service.VulnerabilityResult( id="VULN-0", description="The first vulnerability", version_range=[ service.VersionRange(introduced=Version("0.9"), fixed=Version("1.1")), service.VersionRange(introduced=None, fixed=Version("1.4")), ], ), service.VulnerabilityResult( id="VULN-1", description="The second vulnerability", version_range=[service.VersionRange(introduced=Version("0.5"), fixed=Version("1.0"))], ), ], service.Dependency(package="bar", version="0.1"): [ service.VulnerabilityResult( id="VULN-2", description="The third vulnerability", version_range=[service.VersionRange(introduced=Version("0.1"), fixed=None)], ) ], } @pytest.fixture(autouse=True) def vuln_data(): return _TEST_VULN_DATA
from typing import Dict, List import pytest from packaging.version import Version import pip_audit.service as service _TEST_VULN_DATA: Dict[service.Dependency, List[service.VulnerabilityResult]] = { service.Dependency(package="foo", version="1.0"): [ service.VulnerabilityResult( id="VULN-0", description="The first vulnerability", version_range=[ service.VersionRange(introduced=Version("0.9"), fixed=Version("1.1")), service.VersionRange(introduced=None, fixed=Version("1.4")), ], ), service.VulnerabilityResult( id="VULN-1", description="The second vulnerability", version_range=[service.VersionRange(introduced=Version("0.5"), fixed=Version("1.0"))], ), ], service.Dependency(package="bar", version="0.1"): [ service.VulnerabilityResult( id="VULN-2", description="The third vulnerability", version_range=[service.VersionRange(introduced=Version("0.1"), fixed=None)], ) ], } @pytest.fixture(autouse=True) def vuln_data(): return _TEST_VULN_DATA
none
1
2.137778
2
Day - 3 - Binary Diagnostic/input.py
HarshRaj2717/AOC-2021-Solutions
0
6625799
<reponame>HarshRaj2717/AOC-2021-Solutions input_text = '''00100 11110 10110 10111 10101 01111 00111 11100 10000 11001 00010 01010''' input_text = list(input_text.split("\n"))
input_text = '''00100 11110 10110 10111 10101 01111 00111 11100 10000 11001 00010 01010''' input_text = list(input_text.split("\n"))
es
0.077664
00100 11110 10110 10111 10101 01111 00111 11100 10000 11001 00010 01010
2.172735
2
cookieproject/tests/test_data.py
Markussorensen/mlops_exercises
0
6625800
<filename>cookieproject/tests/test_data.py<gh_stars>0 import numpy as np import torch from torch.utils.data import DataLoader from src.data.make_dataset import MNISTDataset import hydra @hydra.main(config_path="../configs", config_name="config.yaml") def main(config): N_train = 25000 N_test = 5000 train_data = torch.load(config["folders"]["project"] + "data/processed/train.pt") test_data = torch.load(config["folders"]["project"] + "data/processed/test.pt") trainloader = DataLoader(train_data, batch_size=config["hyperparameters"]["batch_size"], shuffle=True) testloader = DataLoader(test_data, batch_size=config["hyperparameters"]["batch_size"], shuffle=True) assert len(train_data) == N_train and len(test_data) == N_test for images, labels in trainloader: assert images.shape[1] == 784 for images, labels in testloader: assert images.shape[1] == 784 represented_train_labels = set(train_data[:][1].numpy()) represented_test_labels = set(test_data[:][1].numpy()) for i in range(10): assert i in represented_train_labels assert i in represented_test_labels if __name__ == '__main__': main()
<filename>cookieproject/tests/test_data.py<gh_stars>0 import numpy as np import torch from torch.utils.data import DataLoader from src.data.make_dataset import MNISTDataset import hydra @hydra.main(config_path="../configs", config_name="config.yaml") def main(config): N_train = 25000 N_test = 5000 train_data = torch.load(config["folders"]["project"] + "data/processed/train.pt") test_data = torch.load(config["folders"]["project"] + "data/processed/test.pt") trainloader = DataLoader(train_data, batch_size=config["hyperparameters"]["batch_size"], shuffle=True) testloader = DataLoader(test_data, batch_size=config["hyperparameters"]["batch_size"], shuffle=True) assert len(train_data) == N_train and len(test_data) == N_test for images, labels in trainloader: assert images.shape[1] == 784 for images, labels in testloader: assert images.shape[1] == 784 represented_train_labels = set(train_data[:][1].numpy()) represented_test_labels = set(test_data[:][1].numpy()) for i in range(10): assert i in represented_train_labels assert i in represented_test_labels if __name__ == '__main__': main()
none
1
2.392794
2
src/diskpool/azext_diskpool/vendored_sdks/storagepool/models/_models_py3.py
wwendyc/azure-cli-extensions
1
6625801
<filename>src/diskpool/azext_diskpool/vendored_sdks/storagepool/models/_models_py3.py<gh_stars>1-10 # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime from typing import Dict, List, Optional, Union from azure.core.exceptions import HttpResponseError import msrest.serialization from ._storage_pool_management_enums import * class Acl(msrest.serialization.Model): """Access Control List (ACL) for an iSCSI Target; defines LUN masking policy. All required parameters must be populated in order to send to Azure. :param initiator_iqn: Required. iSCSI initiator IQN (iSCSI Qualified Name); example: "iqn.2005-03.org.iscsi:client". :type initiator_iqn: str :param mapped_luns: Required. List of LUN names mapped to the ACL. :type mapped_luns: list[str] """ _validation = { 'initiator_iqn': {'required': True}, 'mapped_luns': {'required': True}, } _attribute_map = { 'initiator_iqn': {'key': 'initiatorIqn', 'type': 'str'}, 'mapped_luns': {'key': 'mappedLuns', 'type': '[str]'}, } def __init__( self, *, initiator_iqn: str, mapped_luns: List[str], **kwargs ): super(Acl, self).__init__(**kwargs) self.initiator_iqn = initiator_iqn self.mapped_luns = mapped_luns class Disk(msrest.serialization.Model): """Azure Managed Disk to attach to the Disk Pool. All required parameters must be populated in order to send to Azure. :param id: Required. Unique Azure Resource ID of the Managed Disk. :type id: str """ _validation = { 'id': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, } def __init__( self, *, id: str, **kwargs ): super(Disk, self).__init__(**kwargs) self.id = id class Resource(msrest.serialization.Model): """ARM resource model definition. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__( self, **kwargs ): super(Resource, self).__init__(**kwargs) self.id = None self.name = None self.type = None class TrackedResource(Resource): """The resource model definition for a ARM tracked top level resource. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param location: Required. The geo-location where the resource lives. :type location: str """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'location': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'location': {'key': 'location', 'type': 'str'}, } def __init__( self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs ): super(TrackedResource, self).__init__(**kwargs) self.tags = tags self.location = location class DiskPool(TrackedResource): """Response for Disk Pool request. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param location: Required. The geo-location where the resource lives. :type location: str :ivar system_data: Resource metadata required by ARM RPC. :vartype system_data: ~storage_pool_management.models.SystemMetadata :ivar provisioning_state: Required. State of the operation on the resource. Possible values include: "Invalid", "Succeeded", "Failed", "Canceled", "Pending", "Creating", "Updating", "Deleting". :vartype provisioning_state: str or ~storage_pool_management.models.ProvisioningStates :param availability_zones: Required. Logical zone for Disk Pool resource; example: ["1"]. :type availability_zones: list[str] :param status: Required. Operational status of the Disk Pool. Possible values include: "Invalid", "Unknown", "Healthy", "Unhealthy", "Updating", "Running", "Stopped", "Stopped (deallocated)". :type status: str or ~storage_pool_management.models.OperationalStatus :param disks: List of Azure Managed Disks to attach to a Disk Pool. :type disks: list[~storage_pool_management.models.Disk] :param subnet_id: Required. Azure Resource ID of a Subnet for the Disk Pool. :type subnet_id: str :param additional_capabilities: List of additional capabilities for Disk Pool. :type additional_capabilities: list[str] :param name_sku_name: Sku name. :type name_sku_name: str :param tier: Sku tier. :type tier: str """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'location': {'required': True}, 'system_data': {'readonly': True}, 'provisioning_state': {'required': True, 'readonly': True}, 'availability_zones': {'required': True}, 'status': {'required': True}, 'subnet_id': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'location': {'key': 'location', 'type': 'str'}, 'system_data': {'key': 'systemData', 'type': 'SystemMetadata'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'availability_zones': {'key': 'properties.availabilityZones', 'type': '[str]'}, 'status': {'key': 'properties.status', 'type': 'str'}, 'disks': {'key': 'properties.disks', 'type': '[Disk]'}, 'subnet_id': {'key': 'properties.subnetId', 'type': 'str'}, 'additional_capabilities': {'key': 'properties.additionalCapabilities', 'type': '[str]'}, 'name_sku_name': {'key': 'sku.name', 'type': 'str'}, 'tier': {'key': 'sku.tier', 'type': 'str'}, } def __init__( self, *, location: str, availability_zones: List[str], status: Union[str, "OperationalStatus"], subnet_id: str, tags: Optional[Dict[str, str]] = None, disks: Optional[List["Disk"]] = None, additional_capabilities: Optional[List[str]] = None, name_sku_name: Optional[str] = None, tier: Optional[str] = None, **kwargs ): super(DiskPool, self).__init__(tags=tags, location=location, **kwargs) self.system_data = None self.provisioning_state = None self.availability_zones = availability_zones self.status = status self.disks = disks self.subnet_id = subnet_id self.additional_capabilities = additional_capabilities self.name_sku_name = name_sku_name self.tier = tier class DiskPoolCreate(msrest.serialization.Model): """Request payload for create or update Disk Pool request. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param sku: Required. Determines the SKU of the Disk Pool. :type sku: ~storage_pool_management.models.Sku :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param location: Required. The geo-location where the resource lives. :type location: str :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str :param availability_zones: Logical zone for Disk Pool resource; example: ["1"]. :type availability_zones: list[str] :param disks: List of Azure Managed Disks to attach to a Disk Pool. :type disks: list[~storage_pool_management.models.Disk] :param subnet_id: Required. Azure Resource ID of a Subnet for the Disk Pool. :type subnet_id: str :param additional_capabilities: List of additional capabilities for a Disk Pool. :type additional_capabilities: list[str] """ _validation = { 'sku': {'required': True}, 'location': {'required': True}, 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'subnet_id': {'required': True}, } _attribute_map = { 'sku': {'key': 'sku', 'type': 'Sku'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'location': {'key': 'location', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'availability_zones': {'key': 'properties.availabilityZones', 'type': '[str]'}, 'disks': {'key': 'properties.disks', 'type': '[Disk]'}, 'subnet_id': {'key': 'properties.subnetId', 'type': 'str'}, 'additional_capabilities': {'key': 'properties.additionalCapabilities', 'type': '[str]'}, } def __init__( self, *, sku: "Sku", location: str, subnet_id: str, tags: Optional[Dict[str, str]] = None, availability_zones: Optional[List[str]] = None, disks: Optional[List["Disk"]] = None, additional_capabilities: Optional[List[str]] = None, **kwargs ): super(DiskPoolCreate, self).__init__(**kwargs) self.sku = sku self.tags = tags self.location = location self.id = None self.name = None self.type = None self.availability_zones = availability_zones self.disks = disks self.subnet_id = subnet_id self.additional_capabilities = additional_capabilities class DiskPoolListResult(msrest.serialization.Model): """List of Disk Pools. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param value: Required. An array of Disk pool objects. :type value: list[~storage_pool_management.models.DiskPool] :ivar next_link: URI to fetch the next section of the paginated response. :vartype next_link: str """ _validation = { 'value': {'required': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[DiskPool]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, *, value: List["DiskPool"], **kwargs ): super(DiskPoolListResult, self).__init__(**kwargs) self.value = value self.next_link = None class DiskPoolUpdate(msrest.serialization.Model): """Request payload for Update Disk Pool request. :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param disks: List of Azure Managed Disks to attach to a Disk Pool. :type disks: list[~storage_pool_management.models.Disk] """ _attribute_map = { 'tags': {'key': 'tags', 'type': '{str}'}, 'disks': {'key': 'properties.disks', 'type': '[Disk]'}, } def __init__( self, *, tags: Optional[Dict[str, str]] = None, disks: Optional[List["Disk"]] = None, **kwargs ): super(DiskPoolUpdate, self).__init__(**kwargs) self.tags = tags self.disks = disks class DiskPoolZoneInfo(msrest.serialization.Model): """Disk Pool Sku Details. :param availability_zones: Logical zone for Disk Pool resource; example: ["1"]. :type availability_zones: list[str] :param additional_capabilities: List of additional capabilities for Disk Pool. :type additional_capabilities: list[str] :param sku: Determines the SKU of VM deployed for Disk Pool. :type sku: ~storage_pool_management.models.Sku """ _attribute_map = { 'availability_zones': {'key': 'availabilityZones', 'type': '[str]'}, 'additional_capabilities': {'key': 'additionalCapabilities', 'type': '[str]'}, 'sku': {'key': 'sku', 'type': 'Sku'}, } def __init__( self, *, availability_zones: Optional[List[str]] = None, additional_capabilities: Optional[List[str]] = None, sku: Optional["Sku"] = None, **kwargs ): super(DiskPoolZoneInfo, self).__init__(**kwargs) self.availability_zones = availability_zones self.additional_capabilities = additional_capabilities self.sku = sku class DiskPoolZoneListResult(msrest.serialization.Model): """List Disk Pool skus operation response. :param value: The list of Disk Pool Skus. :type value: list[~storage_pool_management.models.DiskPoolZoneInfo] :param next_link: URI to fetch the next section of the paginated response. :type next_link: str """ _attribute_map = { 'value': {'key': 'value', 'type': '[DiskPoolZoneInfo]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, *, value: Optional[List["DiskPoolZoneInfo"]] = None, next_link: Optional[str] = None, **kwargs ): super(DiskPoolZoneListResult, self).__init__(**kwargs) self.value = value self.next_link = next_link class EndpointDependency(msrest.serialization.Model): """A domain name that a service is reached at, including details of the current connection status. :param domain_name: The domain name of the dependency. :type domain_name: str :param endpoint_details: The IP Addresses and Ports used when connecting to DomainName. :type endpoint_details: list[~storage_pool_management.models.EndpointDetail] """ _attribute_map = { 'domain_name': {'key': 'domainName', 'type': 'str'}, 'endpoint_details': {'key': 'endpointDetails', 'type': '[EndpointDetail]'}, } def __init__( self, *, domain_name: Optional[str] = None, endpoint_details: Optional[List["EndpointDetail"]] = None, **kwargs ): super(EndpointDependency, self).__init__(**kwargs) self.domain_name = domain_name self.endpoint_details = endpoint_details class EndpointDetail(msrest.serialization.Model): """Current TCP connectivity information from the App Service Environment to a single endpoint. :param ip_address: An IP Address that Domain Name currently resolves to. :type ip_address: str :param port: The port an endpoint is connected to. :type port: int :param latency: The time in milliseconds it takes for a TCP connection to be created from the App Service Environment to this IpAddress at this Port. :type latency: float :param is_accessible: Whether it is possible to create a TCP connection from the App Service Environment to this IpAddress at this Port. :type is_accessible: bool """ _attribute_map = { 'ip_address': {'key': 'ipAddress', 'type': 'str'}, 'port': {'key': 'port', 'type': 'int'}, 'latency': {'key': 'latency', 'type': 'float'}, 'is_accessible': {'key': 'isAccessible', 'type': 'bool'}, } def __init__( self, *, ip_address: Optional[str] = None, port: Optional[int] = None, latency: Optional[float] = None, is_accessible: Optional[bool] = None, **kwargs ): super(EndpointDetail, self).__init__(**kwargs) self.ip_address = ip_address self.port = port self.latency = latency self.is_accessible = is_accessible class Error(msrest.serialization.Model): """The resource management error response. :param error: RP error response. :type error: ~storage_pool_management.models.ErrorResponse """ _attribute_map = { 'error': {'key': 'error', 'type': 'ErrorResponse'}, } def __init__( self, *, error: Optional["ErrorResponse"] = None, **kwargs ): super(Error, self).__init__(**kwargs) self.error = error class ErrorAdditionalInfo(msrest.serialization.Model): """The resource management error additional info. Variables are only populated by the server, and will be ignored when sending a request. :ivar type: The additional info type. :vartype type: str :ivar info: The additional info. :vartype info: object """ _validation = { 'type': {'readonly': True}, 'info': {'readonly': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'info': {'key': 'info', 'type': 'object'}, } def __init__( self, **kwargs ): super(ErrorAdditionalInfo, self).__init__(**kwargs) self.type = None self.info = None class ErrorResponse(msrest.serialization.Model): """The resource management error response. Variables are only populated by the server, and will be ignored when sending a request. :ivar code: The error code. :vartype code: str :ivar message: The error message. :vartype message: str :ivar target: The error target. :vartype target: str :ivar details: The error details. :vartype details: list[~storage_pool_management.models.ErrorResponse] :ivar additional_info: The error additional info. :vartype additional_info: list[~storage_pool_management.models.ErrorAdditionalInfo] """ _validation = { 'code': {'readonly': True}, 'message': {'readonly': True}, 'target': {'readonly': True}, 'details': {'readonly': True}, 'additional_info': {'readonly': True}, } _attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, 'target': {'key': 'target', 'type': 'str'}, 'details': {'key': 'details', 'type': '[ErrorResponse]'}, 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, } def __init__( self, **kwargs ): super(ErrorResponse, self).__init__(**kwargs) self.code = None self.message = None self.target = None self.details = None self.additional_info = None class IscsiLun(msrest.serialization.Model): """LUN to expose the Azure Managed Disk. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param name: Required. User defined name for iSCSI LUN; example: "lun0". :type name: str :param managed_disk_azure_resource_id: Required. Azure Resource ID of the Managed Disk. :type managed_disk_azure_resource_id: str :ivar lun: Specifies the Logical Unit Number of the iSCSI LUN. :vartype lun: int """ _validation = { 'name': {'required': True}, 'managed_disk_azure_resource_id': {'required': True}, 'lun': {'readonly': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'managed_disk_azure_resource_id': {'key': 'managedDiskAzureResourceId', 'type': 'str'}, 'lun': {'key': 'lun', 'type': 'int'}, } def __init__( self, *, name: str, managed_disk_azure_resource_id: str, **kwargs ): super(IscsiLun, self).__init__(**kwargs) self.name = name self.managed_disk_azure_resource_id = managed_disk_azure_resource_id self.lun = None class IscsiTarget(Resource): """Response for iSCSI Target requests. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str :ivar system_data: Resource metadata required by ARM RPC. :vartype system_data: ~storage_pool_management.models.SystemMetadata :param acl_mode: Required. Mode for Target connectivity. Possible values include: "Dynamic", "Static". :type acl_mode: str or ~storage_pool_management.models.IscsiTargetAclMode :param static_acls: Access Control List (ACL) for an iSCSI Target; defines LUN masking policy. :type static_acls: list[~storage_pool_management.models.Acl] :param luns: List of LUNs to be exposed through iSCSI Target. :type luns: list[~storage_pool_management.models.IscsiLun] :param target_iqn: Required. iSCSI Target IQN (iSCSI Qualified Name); example: "iqn.2005-03.org.iscsi:server". :type target_iqn: str :ivar provisioning_state: Required. State of the operation on the resource. Possible values include: "Invalid", "Succeeded", "Failed", "Canceled", "Pending", "Creating", "Updating", "Deleting". :vartype provisioning_state: str or ~storage_pool_management.models.ProvisioningStates :param status: Required. Operational status of the iSCSI Target. Possible values include: "Invalid", "Unknown", "Healthy", "Unhealthy", "Updating", "Running", "Stopped", "Stopped (deallocated)". :type status: str or ~storage_pool_management.models.OperationalStatus :param endpoints: List of private IPv4 addresses to connect to the iSCSI Target. :type endpoints: list[str] :param port: The port used by iSCSI Target portal group. :type port: int """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'system_data': {'readonly': True}, 'acl_mode': {'required': True}, 'target_iqn': {'required': True}, 'provisioning_state': {'required': True, 'readonly': True}, 'status': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'system_data': {'key': 'systemData', 'type': 'SystemMetadata'}, 'acl_mode': {'key': 'properties.aclMode', 'type': 'str'}, 'static_acls': {'key': 'properties.staticAcls', 'type': '[Acl]'}, 'luns': {'key': 'properties.luns', 'type': '[IscsiLun]'}, 'target_iqn': {'key': 'properties.targetIqn', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'status': {'key': 'properties.status', 'type': 'str'}, 'endpoints': {'key': 'properties.endpoints', 'type': '[str]'}, 'port': {'key': 'properties.port', 'type': 'int'}, } def __init__( self, *, acl_mode: Union[str, "IscsiTargetAclMode"], target_iqn: str, status: Union[str, "OperationalStatus"], static_acls: Optional[List["Acl"]] = None, luns: Optional[List["IscsiLun"]] = None, endpoints: Optional[List[str]] = None, port: Optional[int] = None, **kwargs ): super(IscsiTarget, self).__init__(**kwargs) self.system_data = None self.acl_mode = acl_mode self.static_acls = static_acls self.luns = luns self.target_iqn = target_iqn self.provisioning_state = None self.status = status self.endpoints = endpoints self.port = port class IscsiTargetCreate(Resource): """Payload for iSCSI Target create or update requests. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str :param acl_mode: Required. Mode for Target connectivity. Possible values include: "Dynamic", "Static". :type acl_mode: str or ~storage_pool_management.models.IscsiTargetAclMode :param target_iqn: iSCSI Target IQN (iSCSI Qualified Name); example: "iqn.2005-03.org.iscsi:server". :type target_iqn: str :param static_acls: Access Control List (ACL) for an iSCSI Target; defines LUN masking policy. :type static_acls: list[~storage_pool_management.models.Acl] :param luns: List of LUNs to be exposed through iSCSI Target. :type luns: list[~storage_pool_management.models.IscsiLun] """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'acl_mode': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'acl_mode': {'key': 'properties.aclMode', 'type': 'str'}, 'target_iqn': {'key': 'properties.targetIqn', 'type': 'str'}, 'static_acls': {'key': 'properties.staticAcls', 'type': '[Acl]'}, 'luns': {'key': 'properties.luns', 'type': '[IscsiLun]'}, } def __init__( self, *, acl_mode: Union[str, "IscsiTargetAclMode"], target_iqn: Optional[str] = None, static_acls: Optional[List["Acl"]] = None, luns: Optional[List["IscsiLun"]] = None, **kwargs ): super(IscsiTargetCreate, self).__init__(**kwargs) self.acl_mode = acl_mode self.target_iqn = target_iqn self.static_acls = static_acls self.luns = luns class IscsiTargetList(msrest.serialization.Model): """List of iSCSI Targets. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param value: Required. An array of iSCSI Targets in a Disk Pool. :type value: list[~storage_pool_management.models.IscsiTarget] :ivar next_link: URI to fetch the next section of the paginated response. :vartype next_link: str """ _validation = { 'value': {'required': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[IscsiTarget]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, *, value: List["IscsiTarget"], **kwargs ): super(IscsiTargetList, self).__init__(**kwargs) self.value = value self.next_link = None class IscsiTargetUpdate(Resource): """Payload for iSCSI Target update requests. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str :param static_acls: Access Control List (ACL) for an iSCSI Target; defines LUN masking policy. :type static_acls: list[~storage_pool_management.models.Acl] :param luns: List of LUNs to be exposed through iSCSI Target. :type luns: list[~storage_pool_management.models.IscsiLun] """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'static_acls': {'key': 'properties.staticAcls', 'type': '[Acl]'}, 'luns': {'key': 'properties.luns', 'type': '[IscsiLun]'}, } def __init__( self, *, static_acls: Optional[List["Acl"]] = None, luns: Optional[List["IscsiLun"]] = None, **kwargs ): super(IscsiTargetUpdate, self).__init__(**kwargs) self.static_acls = static_acls self.luns = luns class OutboundEnvironmentEndpoint(msrest.serialization.Model): """Endpoints accessed for a common purpose that the App Service Environment requires outbound network access to. :param category: The type of service accessed by the App Service Environment, e.g., Azure Storage, Azure SQL Database, and Azure Active Directory. :type category: str :param endpoints: The endpoints that the App Service Environment reaches the service at. :type endpoints: list[~storage_pool_management.models.EndpointDependency] """ _attribute_map = { 'category': {'key': 'category', 'type': 'str'}, 'endpoints': {'key': 'endpoints', 'type': '[EndpointDependency]'}, } def __init__( self, *, category: Optional[str] = None, endpoints: Optional[List["EndpointDependency"]] = None, **kwargs ): super(OutboundEnvironmentEndpoint, self).__init__(**kwargs) self.category = category self.endpoints = endpoints class OutboundEnvironmentEndpointList(msrest.serialization.Model): """Collection of Outbound Environment Endpoints. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param value: Required. Collection of resources. :type value: list[~storage_pool_management.models.OutboundEnvironmentEndpoint] :ivar next_link: Link to next page of resources. :vartype next_link: str """ _validation = { 'value': {'required': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[OutboundEnvironmentEndpoint]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, *, value: List["OutboundEnvironmentEndpoint"], **kwargs ): super(OutboundEnvironmentEndpointList, self).__init__(**kwargs) self.value = value self.next_link = None class ProxyResource(Resource): """The resource model definition for a ARM proxy resource. It will have everything other than required location and tags. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__( self, **kwargs ): super(ProxyResource, self).__init__(**kwargs) class Sku(msrest.serialization.Model): """Sku for ARM resource. All required parameters must be populated in order to send to Azure. :param name: Required. Sku name. :type name: str :param tier: Sku tier. :type tier: str """ _validation = { 'name': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'tier': {'key': 'tier', 'type': 'str'}, } def __init__( self, *, name: str, tier: Optional[str] = None, **kwargs ): super(Sku, self).__init__(**kwargs) self.name = name self.tier = tier class StoragePoolOperationDisplay(msrest.serialization.Model): """Metadata about an operation. All required parameters must be populated in order to send to Azure. :param provider: Required. Localized friendly form of the resource provider name. :type provider: str :param resource: Required. Localized friendly form of the resource type related to this action/operation. :type resource: str :param operation: Required. Localized friendly name for the operation, as it should be shown to the user. :type operation: str :param description: Required. Localized friendly description for the operation, as it should be shown to the user. :type description: str """ _validation = { 'provider': {'required': True}, 'resource': {'required': True}, 'operation': {'required': True}, 'description': {'required': True}, } _attribute_map = { 'provider': {'key': 'provider', 'type': 'str'}, 'resource': {'key': 'resource', 'type': 'str'}, 'operation': {'key': 'operation', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, } def __init__( self, *, provider: str, resource: str, operation: str, description: str, **kwargs ): super(StoragePoolOperationDisplay, self).__init__(**kwargs) self.provider = provider self.resource = resource self.operation = operation self.description = description class StoragePoolOperationListResult(msrest.serialization.Model): """List of operations supported by the RP. All required parameters must be populated in order to send to Azure. :param value: Required. An array of operations supported by the StoragePool RP. :type value: list[~storage_pool_management.models.StoragePoolRpOperation] :param next_link: URI to fetch the next section of the paginated response. :type next_link: str """ _validation = { 'value': {'required': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[StoragePoolRpOperation]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, *, value: List["StoragePoolRpOperation"], next_link: Optional[str] = None, **kwargs ): super(StoragePoolOperationListResult, self).__init__(**kwargs) self.value = value self.next_link = next_link class StoragePoolRpOperation(msrest.serialization.Model): """Description of a StoragePool RP Operation. All required parameters must be populated in order to send to Azure. :param name: Required. The name of the operation being performed on this particular object. :type name: str :param is_data_action: Required. Indicates whether the operation applies to data-plane. :type is_data_action: bool :param action_type: Indicates the action type. :type action_type: str :param display: Required. Additional metadata about RP operation. :type display: ~storage_pool_management.models.StoragePoolOperationDisplay :param origin: The intended executor of the operation; governs the display of the operation in the RBAC UX and the audit logs UX. :type origin: str """ _validation = { 'name': {'required': True}, 'is_data_action': {'required': True}, 'display': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, 'action_type': {'key': 'actionType', 'type': 'str'}, 'display': {'key': 'display', 'type': 'StoragePoolOperationDisplay'}, 'origin': {'key': 'origin', 'type': 'str'}, } def __init__( self, *, name: str, is_data_action: bool, display: "StoragePoolOperationDisplay", action_type: Optional[str] = None, origin: Optional[str] = None, **kwargs ): super(StoragePoolRpOperation, self).__init__(**kwargs) self.name = name self.is_data_action = is_data_action self.action_type = action_type self.display = display self.origin = origin class SystemMetadata(msrest.serialization.Model): """Metadata pertaining to creation and last modification of the resource. :param created_by: The identity that created the resource. :type created_by: str :param created_by_type: The type of identity that created the resource. Possible values include: "User", "Application", "ManagedIdentity", "Key". :type created_by_type: str or ~storage_pool_management.models.CreatedByType :param created_at: The timestamp of resource creation (UTC). :type created_at: ~datetime.datetime :param last_modified_by: The identity that last modified the resource. :type last_modified_by: str :param last_modified_by_type: The type of identity that last modified the resource. Possible values include: "User", "Application", "ManagedIdentity", "Key". :type last_modified_by_type: str or ~storage_pool_management.models.CreatedByType :param last_modified_at: The type of identity that last modified the resource. :type last_modified_at: ~datetime.datetime """ _attribute_map = { 'created_by': {'key': 'createdBy', 'type': 'str'}, 'created_by_type': {'key': 'createdByType', 'type': 'str'}, 'created_at': {'key': 'createdAt', 'type': 'iso-8601'}, 'last_modified_by': {'key': 'lastModifiedBy', 'type': 'str'}, 'last_modified_by_type': {'key': 'lastModifiedByType', 'type': 'str'}, 'last_modified_at': {'key': 'lastModifiedAt', 'type': 'iso-8601'}, } def __init__( self, *, created_by: Optional[str] = None, created_by_type: Optional[Union[str, "CreatedByType"]] = None, created_at: Optional[datetime.datetime] = None, last_modified_by: Optional[str] = None, last_modified_by_type: Optional[Union[str, "CreatedByType"]] = None, last_modified_at: Optional[datetime.datetime] = None, **kwargs ): super(SystemMetadata, self).__init__(**kwargs) self.created_by = created_by self.created_by_type = created_by_type self.created_at = created_at self.last_modified_by = last_modified_by self.last_modified_by_type = last_modified_by_type self.last_modified_at = last_modified_at
<filename>src/diskpool/azext_diskpool/vendored_sdks/storagepool/models/_models_py3.py<gh_stars>1-10 # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- import datetime from typing import Dict, List, Optional, Union from azure.core.exceptions import HttpResponseError import msrest.serialization from ._storage_pool_management_enums import * class Acl(msrest.serialization.Model): """Access Control List (ACL) for an iSCSI Target; defines LUN masking policy. All required parameters must be populated in order to send to Azure. :param initiator_iqn: Required. iSCSI initiator IQN (iSCSI Qualified Name); example: "iqn.2005-03.org.iscsi:client". :type initiator_iqn: str :param mapped_luns: Required. List of LUN names mapped to the ACL. :type mapped_luns: list[str] """ _validation = { 'initiator_iqn': {'required': True}, 'mapped_luns': {'required': True}, } _attribute_map = { 'initiator_iqn': {'key': 'initiatorIqn', 'type': 'str'}, 'mapped_luns': {'key': 'mappedLuns', 'type': '[str]'}, } def __init__( self, *, initiator_iqn: str, mapped_luns: List[str], **kwargs ): super(Acl, self).__init__(**kwargs) self.initiator_iqn = initiator_iqn self.mapped_luns = mapped_luns class Disk(msrest.serialization.Model): """Azure Managed Disk to attach to the Disk Pool. All required parameters must be populated in order to send to Azure. :param id: Required. Unique Azure Resource ID of the Managed Disk. :type id: str """ _validation = { 'id': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, } def __init__( self, *, id: str, **kwargs ): super(Disk, self).__init__(**kwargs) self.id = id class Resource(msrest.serialization.Model): """ARM resource model definition. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__( self, **kwargs ): super(Resource, self).__init__(**kwargs) self.id = None self.name = None self.type = None class TrackedResource(Resource): """The resource model definition for a ARM tracked top level resource. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param location: Required. The geo-location where the resource lives. :type location: str """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'location': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'location': {'key': 'location', 'type': 'str'}, } def __init__( self, *, location: str, tags: Optional[Dict[str, str]] = None, **kwargs ): super(TrackedResource, self).__init__(**kwargs) self.tags = tags self.location = location class DiskPool(TrackedResource): """Response for Disk Pool request. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param location: Required. The geo-location where the resource lives. :type location: str :ivar system_data: Resource metadata required by ARM RPC. :vartype system_data: ~storage_pool_management.models.SystemMetadata :ivar provisioning_state: Required. State of the operation on the resource. Possible values include: "Invalid", "Succeeded", "Failed", "Canceled", "Pending", "Creating", "Updating", "Deleting". :vartype provisioning_state: str or ~storage_pool_management.models.ProvisioningStates :param availability_zones: Required. Logical zone for Disk Pool resource; example: ["1"]. :type availability_zones: list[str] :param status: Required. Operational status of the Disk Pool. Possible values include: "Invalid", "Unknown", "Healthy", "Unhealthy", "Updating", "Running", "Stopped", "Stopped (deallocated)". :type status: str or ~storage_pool_management.models.OperationalStatus :param disks: List of Azure Managed Disks to attach to a Disk Pool. :type disks: list[~storage_pool_management.models.Disk] :param subnet_id: Required. Azure Resource ID of a Subnet for the Disk Pool. :type subnet_id: str :param additional_capabilities: List of additional capabilities for Disk Pool. :type additional_capabilities: list[str] :param name_sku_name: Sku name. :type name_sku_name: str :param tier: Sku tier. :type tier: str """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'location': {'required': True}, 'system_data': {'readonly': True}, 'provisioning_state': {'required': True, 'readonly': True}, 'availability_zones': {'required': True}, 'status': {'required': True}, 'subnet_id': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'location': {'key': 'location', 'type': 'str'}, 'system_data': {'key': 'systemData', 'type': 'SystemMetadata'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'availability_zones': {'key': 'properties.availabilityZones', 'type': '[str]'}, 'status': {'key': 'properties.status', 'type': 'str'}, 'disks': {'key': 'properties.disks', 'type': '[Disk]'}, 'subnet_id': {'key': 'properties.subnetId', 'type': 'str'}, 'additional_capabilities': {'key': 'properties.additionalCapabilities', 'type': '[str]'}, 'name_sku_name': {'key': 'sku.name', 'type': 'str'}, 'tier': {'key': 'sku.tier', 'type': 'str'}, } def __init__( self, *, location: str, availability_zones: List[str], status: Union[str, "OperationalStatus"], subnet_id: str, tags: Optional[Dict[str, str]] = None, disks: Optional[List["Disk"]] = None, additional_capabilities: Optional[List[str]] = None, name_sku_name: Optional[str] = None, tier: Optional[str] = None, **kwargs ): super(DiskPool, self).__init__(tags=tags, location=location, **kwargs) self.system_data = None self.provisioning_state = None self.availability_zones = availability_zones self.status = status self.disks = disks self.subnet_id = subnet_id self.additional_capabilities = additional_capabilities self.name_sku_name = name_sku_name self.tier = tier class DiskPoolCreate(msrest.serialization.Model): """Request payload for create or update Disk Pool request. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param sku: Required. Determines the SKU of the Disk Pool. :type sku: ~storage_pool_management.models.Sku :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param location: Required. The geo-location where the resource lives. :type location: str :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str :param availability_zones: Logical zone for Disk Pool resource; example: ["1"]. :type availability_zones: list[str] :param disks: List of Azure Managed Disks to attach to a Disk Pool. :type disks: list[~storage_pool_management.models.Disk] :param subnet_id: Required. Azure Resource ID of a Subnet for the Disk Pool. :type subnet_id: str :param additional_capabilities: List of additional capabilities for a Disk Pool. :type additional_capabilities: list[str] """ _validation = { 'sku': {'required': True}, 'location': {'required': True}, 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'subnet_id': {'required': True}, } _attribute_map = { 'sku': {'key': 'sku', 'type': 'Sku'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'location': {'key': 'location', 'type': 'str'}, 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'availability_zones': {'key': 'properties.availabilityZones', 'type': '[str]'}, 'disks': {'key': 'properties.disks', 'type': '[Disk]'}, 'subnet_id': {'key': 'properties.subnetId', 'type': 'str'}, 'additional_capabilities': {'key': 'properties.additionalCapabilities', 'type': '[str]'}, } def __init__( self, *, sku: "Sku", location: str, subnet_id: str, tags: Optional[Dict[str, str]] = None, availability_zones: Optional[List[str]] = None, disks: Optional[List["Disk"]] = None, additional_capabilities: Optional[List[str]] = None, **kwargs ): super(DiskPoolCreate, self).__init__(**kwargs) self.sku = sku self.tags = tags self.location = location self.id = None self.name = None self.type = None self.availability_zones = availability_zones self.disks = disks self.subnet_id = subnet_id self.additional_capabilities = additional_capabilities class DiskPoolListResult(msrest.serialization.Model): """List of Disk Pools. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param value: Required. An array of Disk pool objects. :type value: list[~storage_pool_management.models.DiskPool] :ivar next_link: URI to fetch the next section of the paginated response. :vartype next_link: str """ _validation = { 'value': {'required': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[DiskPool]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, *, value: List["DiskPool"], **kwargs ): super(DiskPoolListResult, self).__init__(**kwargs) self.value = value self.next_link = None class DiskPoolUpdate(msrest.serialization.Model): """Request payload for Update Disk Pool request. :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param disks: List of Azure Managed Disks to attach to a Disk Pool. :type disks: list[~storage_pool_management.models.Disk] """ _attribute_map = { 'tags': {'key': 'tags', 'type': '{str}'}, 'disks': {'key': 'properties.disks', 'type': '[Disk]'}, } def __init__( self, *, tags: Optional[Dict[str, str]] = None, disks: Optional[List["Disk"]] = None, **kwargs ): super(DiskPoolUpdate, self).__init__(**kwargs) self.tags = tags self.disks = disks class DiskPoolZoneInfo(msrest.serialization.Model): """Disk Pool Sku Details. :param availability_zones: Logical zone for Disk Pool resource; example: ["1"]. :type availability_zones: list[str] :param additional_capabilities: List of additional capabilities for Disk Pool. :type additional_capabilities: list[str] :param sku: Determines the SKU of VM deployed for Disk Pool. :type sku: ~storage_pool_management.models.Sku """ _attribute_map = { 'availability_zones': {'key': 'availabilityZones', 'type': '[str]'}, 'additional_capabilities': {'key': 'additionalCapabilities', 'type': '[str]'}, 'sku': {'key': 'sku', 'type': 'Sku'}, } def __init__( self, *, availability_zones: Optional[List[str]] = None, additional_capabilities: Optional[List[str]] = None, sku: Optional["Sku"] = None, **kwargs ): super(DiskPoolZoneInfo, self).__init__(**kwargs) self.availability_zones = availability_zones self.additional_capabilities = additional_capabilities self.sku = sku class DiskPoolZoneListResult(msrest.serialization.Model): """List Disk Pool skus operation response. :param value: The list of Disk Pool Skus. :type value: list[~storage_pool_management.models.DiskPoolZoneInfo] :param next_link: URI to fetch the next section of the paginated response. :type next_link: str """ _attribute_map = { 'value': {'key': 'value', 'type': '[DiskPoolZoneInfo]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, *, value: Optional[List["DiskPoolZoneInfo"]] = None, next_link: Optional[str] = None, **kwargs ): super(DiskPoolZoneListResult, self).__init__(**kwargs) self.value = value self.next_link = next_link class EndpointDependency(msrest.serialization.Model): """A domain name that a service is reached at, including details of the current connection status. :param domain_name: The domain name of the dependency. :type domain_name: str :param endpoint_details: The IP Addresses and Ports used when connecting to DomainName. :type endpoint_details: list[~storage_pool_management.models.EndpointDetail] """ _attribute_map = { 'domain_name': {'key': 'domainName', 'type': 'str'}, 'endpoint_details': {'key': 'endpointDetails', 'type': '[EndpointDetail]'}, } def __init__( self, *, domain_name: Optional[str] = None, endpoint_details: Optional[List["EndpointDetail"]] = None, **kwargs ): super(EndpointDependency, self).__init__(**kwargs) self.domain_name = domain_name self.endpoint_details = endpoint_details class EndpointDetail(msrest.serialization.Model): """Current TCP connectivity information from the App Service Environment to a single endpoint. :param ip_address: An IP Address that Domain Name currently resolves to. :type ip_address: str :param port: The port an endpoint is connected to. :type port: int :param latency: The time in milliseconds it takes for a TCP connection to be created from the App Service Environment to this IpAddress at this Port. :type latency: float :param is_accessible: Whether it is possible to create a TCP connection from the App Service Environment to this IpAddress at this Port. :type is_accessible: bool """ _attribute_map = { 'ip_address': {'key': 'ipAddress', 'type': 'str'}, 'port': {'key': 'port', 'type': 'int'}, 'latency': {'key': 'latency', 'type': 'float'}, 'is_accessible': {'key': 'isAccessible', 'type': 'bool'}, } def __init__( self, *, ip_address: Optional[str] = None, port: Optional[int] = None, latency: Optional[float] = None, is_accessible: Optional[bool] = None, **kwargs ): super(EndpointDetail, self).__init__(**kwargs) self.ip_address = ip_address self.port = port self.latency = latency self.is_accessible = is_accessible class Error(msrest.serialization.Model): """The resource management error response. :param error: RP error response. :type error: ~storage_pool_management.models.ErrorResponse """ _attribute_map = { 'error': {'key': 'error', 'type': 'ErrorResponse'}, } def __init__( self, *, error: Optional["ErrorResponse"] = None, **kwargs ): super(Error, self).__init__(**kwargs) self.error = error class ErrorAdditionalInfo(msrest.serialization.Model): """The resource management error additional info. Variables are only populated by the server, and will be ignored when sending a request. :ivar type: The additional info type. :vartype type: str :ivar info: The additional info. :vartype info: object """ _validation = { 'type': {'readonly': True}, 'info': {'readonly': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'info': {'key': 'info', 'type': 'object'}, } def __init__( self, **kwargs ): super(ErrorAdditionalInfo, self).__init__(**kwargs) self.type = None self.info = None class ErrorResponse(msrest.serialization.Model): """The resource management error response. Variables are only populated by the server, and will be ignored when sending a request. :ivar code: The error code. :vartype code: str :ivar message: The error message. :vartype message: str :ivar target: The error target. :vartype target: str :ivar details: The error details. :vartype details: list[~storage_pool_management.models.ErrorResponse] :ivar additional_info: The error additional info. :vartype additional_info: list[~storage_pool_management.models.ErrorAdditionalInfo] """ _validation = { 'code': {'readonly': True}, 'message': {'readonly': True}, 'target': {'readonly': True}, 'details': {'readonly': True}, 'additional_info': {'readonly': True}, } _attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, 'target': {'key': 'target', 'type': 'str'}, 'details': {'key': 'details', 'type': '[ErrorResponse]'}, 'additional_info': {'key': 'additionalInfo', 'type': '[ErrorAdditionalInfo]'}, } def __init__( self, **kwargs ): super(ErrorResponse, self).__init__(**kwargs) self.code = None self.message = None self.target = None self.details = None self.additional_info = None class IscsiLun(msrest.serialization.Model): """LUN to expose the Azure Managed Disk. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param name: Required. User defined name for iSCSI LUN; example: "lun0". :type name: str :param managed_disk_azure_resource_id: Required. Azure Resource ID of the Managed Disk. :type managed_disk_azure_resource_id: str :ivar lun: Specifies the Logical Unit Number of the iSCSI LUN. :vartype lun: int """ _validation = { 'name': {'required': True}, 'managed_disk_azure_resource_id': {'required': True}, 'lun': {'readonly': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'managed_disk_azure_resource_id': {'key': 'managedDiskAzureResourceId', 'type': 'str'}, 'lun': {'key': 'lun', 'type': 'int'}, } def __init__( self, *, name: str, managed_disk_azure_resource_id: str, **kwargs ): super(IscsiLun, self).__init__(**kwargs) self.name = name self.managed_disk_azure_resource_id = managed_disk_azure_resource_id self.lun = None class IscsiTarget(Resource): """Response for iSCSI Target requests. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str :ivar system_data: Resource metadata required by ARM RPC. :vartype system_data: ~storage_pool_management.models.SystemMetadata :param acl_mode: Required. Mode for Target connectivity. Possible values include: "Dynamic", "Static". :type acl_mode: str or ~storage_pool_management.models.IscsiTargetAclMode :param static_acls: Access Control List (ACL) for an iSCSI Target; defines LUN masking policy. :type static_acls: list[~storage_pool_management.models.Acl] :param luns: List of LUNs to be exposed through iSCSI Target. :type luns: list[~storage_pool_management.models.IscsiLun] :param target_iqn: Required. iSCSI Target IQN (iSCSI Qualified Name); example: "iqn.2005-03.org.iscsi:server". :type target_iqn: str :ivar provisioning_state: Required. State of the operation on the resource. Possible values include: "Invalid", "Succeeded", "Failed", "Canceled", "Pending", "Creating", "Updating", "Deleting". :vartype provisioning_state: str or ~storage_pool_management.models.ProvisioningStates :param status: Required. Operational status of the iSCSI Target. Possible values include: "Invalid", "Unknown", "Healthy", "Unhealthy", "Updating", "Running", "Stopped", "Stopped (deallocated)". :type status: str or ~storage_pool_management.models.OperationalStatus :param endpoints: List of private IPv4 addresses to connect to the iSCSI Target. :type endpoints: list[str] :param port: The port used by iSCSI Target portal group. :type port: int """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'system_data': {'readonly': True}, 'acl_mode': {'required': True}, 'target_iqn': {'required': True}, 'provisioning_state': {'required': True, 'readonly': True}, 'status': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'system_data': {'key': 'systemData', 'type': 'SystemMetadata'}, 'acl_mode': {'key': 'properties.aclMode', 'type': 'str'}, 'static_acls': {'key': 'properties.staticAcls', 'type': '[Acl]'}, 'luns': {'key': 'properties.luns', 'type': '[IscsiLun]'}, 'target_iqn': {'key': 'properties.targetIqn', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'status': {'key': 'properties.status', 'type': 'str'}, 'endpoints': {'key': 'properties.endpoints', 'type': '[str]'}, 'port': {'key': 'properties.port', 'type': 'int'}, } def __init__( self, *, acl_mode: Union[str, "IscsiTargetAclMode"], target_iqn: str, status: Union[str, "OperationalStatus"], static_acls: Optional[List["Acl"]] = None, luns: Optional[List["IscsiLun"]] = None, endpoints: Optional[List[str]] = None, port: Optional[int] = None, **kwargs ): super(IscsiTarget, self).__init__(**kwargs) self.system_data = None self.acl_mode = acl_mode self.static_acls = static_acls self.luns = luns self.target_iqn = target_iqn self.provisioning_state = None self.status = status self.endpoints = endpoints self.port = port class IscsiTargetCreate(Resource): """Payload for iSCSI Target create or update requests. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str :param acl_mode: Required. Mode for Target connectivity. Possible values include: "Dynamic", "Static". :type acl_mode: str or ~storage_pool_management.models.IscsiTargetAclMode :param target_iqn: iSCSI Target IQN (iSCSI Qualified Name); example: "iqn.2005-03.org.iscsi:server". :type target_iqn: str :param static_acls: Access Control List (ACL) for an iSCSI Target; defines LUN masking policy. :type static_acls: list[~storage_pool_management.models.Acl] :param luns: List of LUNs to be exposed through iSCSI Target. :type luns: list[~storage_pool_management.models.IscsiLun] """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'acl_mode': {'required': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'acl_mode': {'key': 'properties.aclMode', 'type': 'str'}, 'target_iqn': {'key': 'properties.targetIqn', 'type': 'str'}, 'static_acls': {'key': 'properties.staticAcls', 'type': '[Acl]'}, 'luns': {'key': 'properties.luns', 'type': '[IscsiLun]'}, } def __init__( self, *, acl_mode: Union[str, "IscsiTargetAclMode"], target_iqn: Optional[str] = None, static_acls: Optional[List["Acl"]] = None, luns: Optional[List["IscsiLun"]] = None, **kwargs ): super(IscsiTargetCreate, self).__init__(**kwargs) self.acl_mode = acl_mode self.target_iqn = target_iqn self.static_acls = static_acls self.luns = luns class IscsiTargetList(msrest.serialization.Model): """List of iSCSI Targets. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param value: Required. An array of iSCSI Targets in a Disk Pool. :type value: list[~storage_pool_management.models.IscsiTarget] :ivar next_link: URI to fetch the next section of the paginated response. :vartype next_link: str """ _validation = { 'value': {'required': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[IscsiTarget]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, *, value: List["IscsiTarget"], **kwargs ): super(IscsiTargetList, self).__init__(**kwargs) self.value = value self.next_link = None class IscsiTargetUpdate(Resource): """Payload for iSCSI Target update requests. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str :param static_acls: Access Control List (ACL) for an iSCSI Target; defines LUN masking policy. :type static_acls: list[~storage_pool_management.models.Acl] :param luns: List of LUNs to be exposed through iSCSI Target. :type luns: list[~storage_pool_management.models.IscsiLun] """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'static_acls': {'key': 'properties.staticAcls', 'type': '[Acl]'}, 'luns': {'key': 'properties.luns', 'type': '[IscsiLun]'}, } def __init__( self, *, static_acls: Optional[List["Acl"]] = None, luns: Optional[List["IscsiLun"]] = None, **kwargs ): super(IscsiTargetUpdate, self).__init__(**kwargs) self.static_acls = static_acls self.luns = luns class OutboundEnvironmentEndpoint(msrest.serialization.Model): """Endpoints accessed for a common purpose that the App Service Environment requires outbound network access to. :param category: The type of service accessed by the App Service Environment, e.g., Azure Storage, Azure SQL Database, and Azure Active Directory. :type category: str :param endpoints: The endpoints that the App Service Environment reaches the service at. :type endpoints: list[~storage_pool_management.models.EndpointDependency] """ _attribute_map = { 'category': {'key': 'category', 'type': 'str'}, 'endpoints': {'key': 'endpoints', 'type': '[EndpointDependency]'}, } def __init__( self, *, category: Optional[str] = None, endpoints: Optional[List["EndpointDependency"]] = None, **kwargs ): super(OutboundEnvironmentEndpoint, self).__init__(**kwargs) self.category = category self.endpoints = endpoints class OutboundEnvironmentEndpointList(msrest.serialization.Model): """Collection of Outbound Environment Endpoints. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param value: Required. Collection of resources. :type value: list[~storage_pool_management.models.OutboundEnvironmentEndpoint] :ivar next_link: Link to next page of resources. :vartype next_link: str """ _validation = { 'value': {'required': True}, 'next_link': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[OutboundEnvironmentEndpoint]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, *, value: List["OutboundEnvironmentEndpoint"], **kwargs ): super(OutboundEnvironmentEndpointList, self).__init__(**kwargs) self.value = value self.next_link = None class ProxyResource(Resource): """The resource model definition for a ARM proxy resource. It will have everything other than required location and tags. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__( self, **kwargs ): super(ProxyResource, self).__init__(**kwargs) class Sku(msrest.serialization.Model): """Sku for ARM resource. All required parameters must be populated in order to send to Azure. :param name: Required. Sku name. :type name: str :param tier: Sku tier. :type tier: str """ _validation = { 'name': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'tier': {'key': 'tier', 'type': 'str'}, } def __init__( self, *, name: str, tier: Optional[str] = None, **kwargs ): super(Sku, self).__init__(**kwargs) self.name = name self.tier = tier class StoragePoolOperationDisplay(msrest.serialization.Model): """Metadata about an operation. All required parameters must be populated in order to send to Azure. :param provider: Required. Localized friendly form of the resource provider name. :type provider: str :param resource: Required. Localized friendly form of the resource type related to this action/operation. :type resource: str :param operation: Required. Localized friendly name for the operation, as it should be shown to the user. :type operation: str :param description: Required. Localized friendly description for the operation, as it should be shown to the user. :type description: str """ _validation = { 'provider': {'required': True}, 'resource': {'required': True}, 'operation': {'required': True}, 'description': {'required': True}, } _attribute_map = { 'provider': {'key': 'provider', 'type': 'str'}, 'resource': {'key': 'resource', 'type': 'str'}, 'operation': {'key': 'operation', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, } def __init__( self, *, provider: str, resource: str, operation: str, description: str, **kwargs ): super(StoragePoolOperationDisplay, self).__init__(**kwargs) self.provider = provider self.resource = resource self.operation = operation self.description = description class StoragePoolOperationListResult(msrest.serialization.Model): """List of operations supported by the RP. All required parameters must be populated in order to send to Azure. :param value: Required. An array of operations supported by the StoragePool RP. :type value: list[~storage_pool_management.models.StoragePoolRpOperation] :param next_link: URI to fetch the next section of the paginated response. :type next_link: str """ _validation = { 'value': {'required': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[StoragePoolRpOperation]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } def __init__( self, *, value: List["StoragePoolRpOperation"], next_link: Optional[str] = None, **kwargs ): super(StoragePoolOperationListResult, self).__init__(**kwargs) self.value = value self.next_link = next_link class StoragePoolRpOperation(msrest.serialization.Model): """Description of a StoragePool RP Operation. All required parameters must be populated in order to send to Azure. :param name: Required. The name of the operation being performed on this particular object. :type name: str :param is_data_action: Required. Indicates whether the operation applies to data-plane. :type is_data_action: bool :param action_type: Indicates the action type. :type action_type: str :param display: Required. Additional metadata about RP operation. :type display: ~storage_pool_management.models.StoragePoolOperationDisplay :param origin: The intended executor of the operation; governs the display of the operation in the RBAC UX and the audit logs UX. :type origin: str """ _validation = { 'name': {'required': True}, 'is_data_action': {'required': True}, 'display': {'required': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'is_data_action': {'key': 'isDataAction', 'type': 'bool'}, 'action_type': {'key': 'actionType', 'type': 'str'}, 'display': {'key': 'display', 'type': 'StoragePoolOperationDisplay'}, 'origin': {'key': 'origin', 'type': 'str'}, } def __init__( self, *, name: str, is_data_action: bool, display: "StoragePoolOperationDisplay", action_type: Optional[str] = None, origin: Optional[str] = None, **kwargs ): super(StoragePoolRpOperation, self).__init__(**kwargs) self.name = name self.is_data_action = is_data_action self.action_type = action_type self.display = display self.origin = origin class SystemMetadata(msrest.serialization.Model): """Metadata pertaining to creation and last modification of the resource. :param created_by: The identity that created the resource. :type created_by: str :param created_by_type: The type of identity that created the resource. Possible values include: "User", "Application", "ManagedIdentity", "Key". :type created_by_type: str or ~storage_pool_management.models.CreatedByType :param created_at: The timestamp of resource creation (UTC). :type created_at: ~datetime.datetime :param last_modified_by: The identity that last modified the resource. :type last_modified_by: str :param last_modified_by_type: The type of identity that last modified the resource. Possible values include: "User", "Application", "ManagedIdentity", "Key". :type last_modified_by_type: str or ~storage_pool_management.models.CreatedByType :param last_modified_at: The type of identity that last modified the resource. :type last_modified_at: ~datetime.datetime """ _attribute_map = { 'created_by': {'key': 'createdBy', 'type': 'str'}, 'created_by_type': {'key': 'createdByType', 'type': 'str'}, 'created_at': {'key': 'createdAt', 'type': 'iso-8601'}, 'last_modified_by': {'key': 'lastModifiedBy', 'type': 'str'}, 'last_modified_by_type': {'key': 'lastModifiedByType', 'type': 'str'}, 'last_modified_at': {'key': 'lastModifiedAt', 'type': 'iso-8601'}, } def __init__( self, *, created_by: Optional[str] = None, created_by_type: Optional[Union[str, "CreatedByType"]] = None, created_at: Optional[datetime.datetime] = None, last_modified_by: Optional[str] = None, last_modified_by_type: Optional[Union[str, "CreatedByType"]] = None, last_modified_at: Optional[datetime.datetime] = None, **kwargs ): super(SystemMetadata, self).__init__(**kwargs) self.created_by = created_by self.created_by_type = created_by_type self.created_at = created_at self.last_modified_by = last_modified_by self.last_modified_by_type = last_modified_by_type self.last_modified_at = last_modified_at
en
0.692329
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- Access Control List (ACL) for an iSCSI Target; defines LUN masking policy. All required parameters must be populated in order to send to Azure. :param initiator_iqn: Required. iSCSI initiator IQN (iSCSI Qualified Name); example: "iqn.2005-03.org.iscsi:client". :type initiator_iqn: str :param mapped_luns: Required. List of LUN names mapped to the ACL. :type mapped_luns: list[str] Azure Managed Disk to attach to the Disk Pool. All required parameters must be populated in order to send to Azure. :param id: Required. Unique Azure Resource ID of the Managed Disk. :type id: str ARM resource model definition. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str The resource model definition for a ARM tracked top level resource. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param location: Required. The geo-location where the resource lives. :type location: str Response for Disk Pool request. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param location: Required. The geo-location where the resource lives. :type location: str :ivar system_data: Resource metadata required by ARM RPC. :vartype system_data: ~storage_pool_management.models.SystemMetadata :ivar provisioning_state: Required. State of the operation on the resource. Possible values include: "Invalid", "Succeeded", "Failed", "Canceled", "Pending", "Creating", "Updating", "Deleting". :vartype provisioning_state: str or ~storage_pool_management.models.ProvisioningStates :param availability_zones: Required. Logical zone for Disk Pool resource; example: ["1"]. :type availability_zones: list[str] :param status: Required. Operational status of the Disk Pool. Possible values include: "Invalid", "Unknown", "Healthy", "Unhealthy", "Updating", "Running", "Stopped", "Stopped (deallocated)". :type status: str or ~storage_pool_management.models.OperationalStatus :param disks: List of Azure Managed Disks to attach to a Disk Pool. :type disks: list[~storage_pool_management.models.Disk] :param subnet_id: Required. Azure Resource ID of a Subnet for the Disk Pool. :type subnet_id: str :param additional_capabilities: List of additional capabilities for Disk Pool. :type additional_capabilities: list[str] :param name_sku_name: Sku name. :type name_sku_name: str :param tier: Sku tier. :type tier: str Request payload for create or update Disk Pool request. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param sku: Required. Determines the SKU of the Disk Pool. :type sku: ~storage_pool_management.models.Sku :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param location: Required. The geo-location where the resource lives. :type location: str :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str :param availability_zones: Logical zone for Disk Pool resource; example: ["1"]. :type availability_zones: list[str] :param disks: List of Azure Managed Disks to attach to a Disk Pool. :type disks: list[~storage_pool_management.models.Disk] :param subnet_id: Required. Azure Resource ID of a Subnet for the Disk Pool. :type subnet_id: str :param additional_capabilities: List of additional capabilities for a Disk Pool. :type additional_capabilities: list[str] List of Disk Pools. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param value: Required. An array of Disk pool objects. :type value: list[~storage_pool_management.models.DiskPool] :ivar next_link: URI to fetch the next section of the paginated response. :vartype next_link: str Request payload for Update Disk Pool request. :param tags: A set of tags. Resource tags. :type tags: dict[str, str] :param disks: List of Azure Managed Disks to attach to a Disk Pool. :type disks: list[~storage_pool_management.models.Disk] Disk Pool Sku Details. :param availability_zones: Logical zone for Disk Pool resource; example: ["1"]. :type availability_zones: list[str] :param additional_capabilities: List of additional capabilities for Disk Pool. :type additional_capabilities: list[str] :param sku: Determines the SKU of VM deployed for Disk Pool. :type sku: ~storage_pool_management.models.Sku List Disk Pool skus operation response. :param value: The list of Disk Pool Skus. :type value: list[~storage_pool_management.models.DiskPoolZoneInfo] :param next_link: URI to fetch the next section of the paginated response. :type next_link: str A domain name that a service is reached at, including details of the current connection status. :param domain_name: The domain name of the dependency. :type domain_name: str :param endpoint_details: The IP Addresses and Ports used when connecting to DomainName. :type endpoint_details: list[~storage_pool_management.models.EndpointDetail] Current TCP connectivity information from the App Service Environment to a single endpoint. :param ip_address: An IP Address that Domain Name currently resolves to. :type ip_address: str :param port: The port an endpoint is connected to. :type port: int :param latency: The time in milliseconds it takes for a TCP connection to be created from the App Service Environment to this IpAddress at this Port. :type latency: float :param is_accessible: Whether it is possible to create a TCP connection from the App Service Environment to this IpAddress at this Port. :type is_accessible: bool The resource management error response. :param error: RP error response. :type error: ~storage_pool_management.models.ErrorResponse The resource management error additional info. Variables are only populated by the server, and will be ignored when sending a request. :ivar type: The additional info type. :vartype type: str :ivar info: The additional info. :vartype info: object The resource management error response. Variables are only populated by the server, and will be ignored when sending a request. :ivar code: The error code. :vartype code: str :ivar message: The error message. :vartype message: str :ivar target: The error target. :vartype target: str :ivar details: The error details. :vartype details: list[~storage_pool_management.models.ErrorResponse] :ivar additional_info: The error additional info. :vartype additional_info: list[~storage_pool_management.models.ErrorAdditionalInfo] LUN to expose the Azure Managed Disk. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param name: Required. User defined name for iSCSI LUN; example: "lun0". :type name: str :param managed_disk_azure_resource_id: Required. Azure Resource ID of the Managed Disk. :type managed_disk_azure_resource_id: str :ivar lun: Specifies the Logical Unit Number of the iSCSI LUN. :vartype lun: int Response for iSCSI Target requests. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str :ivar system_data: Resource metadata required by ARM RPC. :vartype system_data: ~storage_pool_management.models.SystemMetadata :param acl_mode: Required. Mode for Target connectivity. Possible values include: "Dynamic", "Static". :type acl_mode: str or ~storage_pool_management.models.IscsiTargetAclMode :param static_acls: Access Control List (ACL) for an iSCSI Target; defines LUN masking policy. :type static_acls: list[~storage_pool_management.models.Acl] :param luns: List of LUNs to be exposed through iSCSI Target. :type luns: list[~storage_pool_management.models.IscsiLun] :param target_iqn: Required. iSCSI Target IQN (iSCSI Qualified Name); example: "iqn.2005-03.org.iscsi:server". :type target_iqn: str :ivar provisioning_state: Required. State of the operation on the resource. Possible values include: "Invalid", "Succeeded", "Failed", "Canceled", "Pending", "Creating", "Updating", "Deleting". :vartype provisioning_state: str or ~storage_pool_management.models.ProvisioningStates :param status: Required. Operational status of the iSCSI Target. Possible values include: "Invalid", "Unknown", "Healthy", "Unhealthy", "Updating", "Running", "Stopped", "Stopped (deallocated)". :type status: str or ~storage_pool_management.models.OperationalStatus :param endpoints: List of private IPv4 addresses to connect to the iSCSI Target. :type endpoints: list[str] :param port: The port used by iSCSI Target portal group. :type port: int Payload for iSCSI Target create or update requests. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str :param acl_mode: Required. Mode for Target connectivity. Possible values include: "Dynamic", "Static". :type acl_mode: str or ~storage_pool_management.models.IscsiTargetAclMode :param target_iqn: iSCSI Target IQN (iSCSI Qualified Name); example: "iqn.2005-03.org.iscsi:server". :type target_iqn: str :param static_acls: Access Control List (ACL) for an iSCSI Target; defines LUN masking policy. :type static_acls: list[~storage_pool_management.models.Acl] :param luns: List of LUNs to be exposed through iSCSI Target. :type luns: list[~storage_pool_management.models.IscsiLun] List of iSCSI Targets. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param value: Required. An array of iSCSI Targets in a Disk Pool. :type value: list[~storage_pool_management.models.IscsiTarget] :ivar next_link: URI to fetch the next section of the paginated response. :vartype next_link: str Payload for iSCSI Target update requests. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str :param static_acls: Access Control List (ACL) for an iSCSI Target; defines LUN masking policy. :type static_acls: list[~storage_pool_management.models.Acl] :param luns: List of LUNs to be exposed through iSCSI Target. :type luns: list[~storage_pool_management.models.IscsiLun] Endpoints accessed for a common purpose that the App Service Environment requires outbound network access to. :param category: The type of service accessed by the App Service Environment, e.g., Azure Storage, Azure SQL Database, and Azure Active Directory. :type category: str :param endpoints: The endpoints that the App Service Environment reaches the service at. :type endpoints: list[~storage_pool_management.models.EndpointDependency] Collection of Outbound Environment Endpoints. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param value: Required. Collection of resources. :type value: list[~storage_pool_management.models.OutboundEnvironmentEndpoint] :ivar next_link: Link to next page of resources. :vartype next_link: str The resource model definition for a ARM proxy resource. It will have everything other than required location and tags. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}. :vartype id: str :ivar name: The name of the resource. :vartype name: str :ivar type: The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. :vartype type: str Sku for ARM resource. All required parameters must be populated in order to send to Azure. :param name: Required. Sku name. :type name: str :param tier: Sku tier. :type tier: str Metadata about an operation. All required parameters must be populated in order to send to Azure. :param provider: Required. Localized friendly form of the resource provider name. :type provider: str :param resource: Required. Localized friendly form of the resource type related to this action/operation. :type resource: str :param operation: Required. Localized friendly name for the operation, as it should be shown to the user. :type operation: str :param description: Required. Localized friendly description for the operation, as it should be shown to the user. :type description: str List of operations supported by the RP. All required parameters must be populated in order to send to Azure. :param value: Required. An array of operations supported by the StoragePool RP. :type value: list[~storage_pool_management.models.StoragePoolRpOperation] :param next_link: URI to fetch the next section of the paginated response. :type next_link: str Description of a StoragePool RP Operation. All required parameters must be populated in order to send to Azure. :param name: Required. The name of the operation being performed on this particular object. :type name: str :param is_data_action: Required. Indicates whether the operation applies to data-plane. :type is_data_action: bool :param action_type: Indicates the action type. :type action_type: str :param display: Required. Additional metadata about RP operation. :type display: ~storage_pool_management.models.StoragePoolOperationDisplay :param origin: The intended executor of the operation; governs the display of the operation in the RBAC UX and the audit logs UX. :type origin: str Metadata pertaining to creation and last modification of the resource. :param created_by: The identity that created the resource. :type created_by: str :param created_by_type: The type of identity that created the resource. Possible values include: "User", "Application", "ManagedIdentity", "Key". :type created_by_type: str or ~storage_pool_management.models.CreatedByType :param created_at: The timestamp of resource creation (UTC). :type created_at: ~datetime.datetime :param last_modified_by: The identity that last modified the resource. :type last_modified_by: str :param last_modified_by_type: The type of identity that last modified the resource. Possible values include: "User", "Application", "ManagedIdentity", "Key". :type last_modified_by_type: str or ~storage_pool_management.models.CreatedByType :param last_modified_at: The type of identity that last modified the resource. :type last_modified_at: ~datetime.datetime
1.829022
2
src/spn/structure/leaves/histogram/Moment.py
tkrons/SPFlow_topdownrules
199
6625802
<gh_stars>100-1000 """ Created on April 15, 2018 @author: <NAME> @author: <NAME> """ import numpy as np from spn.algorithms.stats.Moments import add_node_moment from spn.structure.StatisticalTypes import MetaType from spn.structure.leaves.histogram.Histograms import Histogram import logging logger = logging.getLogger(__name__) def histogram_moment(node, order=1): exp = 0 for i in range(len(node.breaks) - 1): a = node.breaks[i] b = node.breaks[i + 1] d = node.densities[i] if node.meta_type == MetaType.DISCRETE: sum_x = a ** order else: sum_x = (b ** (order + 1) - a ** (order + 1)) / (order + 1) exp += d * sum_x return exp def add_histogram_moment_support(): add_node_moment(Histogram, histogram_moment)
""" Created on April 15, 2018 @author: <NAME> @author: <NAME> """ import numpy as np from spn.algorithms.stats.Moments import add_node_moment from spn.structure.StatisticalTypes import MetaType from spn.structure.leaves.histogram.Histograms import Histogram import logging logger = logging.getLogger(__name__) def histogram_moment(node, order=1): exp = 0 for i in range(len(node.breaks) - 1): a = node.breaks[i] b = node.breaks[i + 1] d = node.densities[i] if node.meta_type == MetaType.DISCRETE: sum_x = a ** order else: sum_x = (b ** (order + 1) - a ** (order + 1)) / (order + 1) exp += d * sum_x return exp def add_histogram_moment_support(): add_node_moment(Histogram, histogram_moment)
en
0.771292
Created on April 15, 2018 @author: <NAME> @author: <NAME>
2.86622
3
tests/test_Actuation.py
landrs-toolkit/PySOSA
1
6625803
<reponame>landrs-toolkit/PySOSA import unittest from PySOSA import Actuation from PySOSA import FeatureOfInterest class MyTestCase(unittest.TestCase): def test_add_featureOfInterest(self): """ creates an FOI object and test add feature of interest to Actuation """ a1 = Actuation("Actuation 1", "switch on thermometer") feature = FeatureOfInterest("Feature 1", "temperature") a1.add_featureOfInterest(feature) if __name__ == '__main__': unittest.main()
import unittest from PySOSA import Actuation from PySOSA import FeatureOfInterest class MyTestCase(unittest.TestCase): def test_add_featureOfInterest(self): """ creates an FOI object and test add feature of interest to Actuation """ a1 = Actuation("Actuation 1", "switch on thermometer") feature = FeatureOfInterest("Feature 1", "temperature") a1.add_featureOfInterest(feature) if __name__ == '__main__': unittest.main()
en
0.775985
creates an FOI object and test add feature of interest to Actuation
3.062022
3
app/main.py
chiatk/tforty-api
0
6625804
<reponame>chiatk/tforty-api<gh_stars>0 from fastapi import FastAPI from fastapi.staticfiles import StaticFiles from fastapi.middleware.cors import CORSMiddleware from .routes.user import user from .routes.campaign import campaign from .routes.perk import perk from .routes.donation import donation app = FastAPI() app.mount("/media", StaticFiles(directory="assets"), name="assets") origins = ["*"] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.get('/') def main(): return { "message": "Welcome to the api" } app.include_router(user) app.include_router(campaign) app.include_router(perk) app.include_router(donation)
from fastapi import FastAPI from fastapi.staticfiles import StaticFiles from fastapi.middleware.cors import CORSMiddleware from .routes.user import user from .routes.campaign import campaign from .routes.perk import perk from .routes.donation import donation app = FastAPI() app.mount("/media", StaticFiles(directory="assets"), name="assets") origins = ["*"] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.get('/') def main(): return { "message": "Welcome to the api" } app.include_router(user) app.include_router(campaign) app.include_router(perk) app.include_router(donation)
none
1
1.966469
2
statsmodels/datasets/scotland/data.py
yarikoptic/statsmodels
1
6625805
"""Taxation Powers Vote for the Scottish Parliament 1997 dataset.""" __docformat__ = 'restructuredtext' COPYRIGHT = """Used with express permission from the original author, who retains all rights.""" TITLE = "Taxation Powers Vote for the Scottish Parliamant 1997" SOURCE = """ <NAME>'s `Generalized Linear Models: A Unified Approach` http://jgill.wustl.edu/research/books.html """ DESCRSHORT = """Taxation Powers' Yes Vote for Scottish Parliamanet-1997""" DESCRLONG = """ This data is based on the example in Gill and describes the proportion of voters who voted Yes to grant the Scottish Parliament taxation powers. The data are divided into 32 council districts. This example's explanatory variables include the amount of council tax collected in pounds sterling as of April 1997 per two adults before adjustments, the female percentage of total claims for unemployment benefits as of January, 1998, the standardized mortality rate (UK is 100), the percentage of labor force participation, regional GDP, the percentage of children aged 5 to 15, and an interaction term between female unemployment and the council tax. The original source files and variable information are included in /scotland/src/ """ NOTE = """:: Number of Observations - 32 (1 for each Scottish district) Number of Variables - 8 Variable name definitions:: YES - Proportion voting yes to granting taxation powers to the Scottish parliament. COUTAX - Amount of council tax collected in pounds steling as of April '97 UNEMPF - Female percentage of total unemployment benefits claims as of January 1998 MOR - The standardized mortality rate (UK is 100) ACT - Labor force participation (Short for active) GDP - GDP per county AGE - Percentage of children aged 5 to 15 in the county COUTAX_FEMALEUNEMP - Interaction between COUTAX and UNEMPF Council district names are included in the data file, though are not returned by load. """ import numpy as np from statsmodels.datasets import utils as du from os.path import dirname, abspath def load(): """ Load the Scotvote data and returns a Dataset instance. Returns ------- Dataset instance: See DATASET_PROPOSAL.txt for more information. """ data = _get_data() return du.process_recarray(data, endog_idx=0, dtype=float) def load_pandas(): """ Load the Scotvote data and returns a Dataset instance. Returns ------- Dataset instance: See DATASET_PROPOSAL.txt for more information. """ data = _get_data() return du.process_recarray_pandas(data, endog_idx=0, dtype=float) def _get_data(): filepath = dirname(abspath(__file__)) with open(filepath + '/scotvote.csv',"rb") as f: data = np.recfromtxt(f, delimiter=",", names=True, dtype=float, usecols=(1,2,3,4,5,6,7,8)) return data
"""Taxation Powers Vote for the Scottish Parliament 1997 dataset.""" __docformat__ = 'restructuredtext' COPYRIGHT = """Used with express permission from the original author, who retains all rights.""" TITLE = "Taxation Powers Vote for the Scottish Parliamant 1997" SOURCE = """ <NAME>'s `Generalized Linear Models: A Unified Approach` http://jgill.wustl.edu/research/books.html """ DESCRSHORT = """Taxation Powers' Yes Vote for Scottish Parliamanet-1997""" DESCRLONG = """ This data is based on the example in Gill and describes the proportion of voters who voted Yes to grant the Scottish Parliament taxation powers. The data are divided into 32 council districts. This example's explanatory variables include the amount of council tax collected in pounds sterling as of April 1997 per two adults before adjustments, the female percentage of total claims for unemployment benefits as of January, 1998, the standardized mortality rate (UK is 100), the percentage of labor force participation, regional GDP, the percentage of children aged 5 to 15, and an interaction term between female unemployment and the council tax. The original source files and variable information are included in /scotland/src/ """ NOTE = """:: Number of Observations - 32 (1 for each Scottish district) Number of Variables - 8 Variable name definitions:: YES - Proportion voting yes to granting taxation powers to the Scottish parliament. COUTAX - Amount of council tax collected in pounds steling as of April '97 UNEMPF - Female percentage of total unemployment benefits claims as of January 1998 MOR - The standardized mortality rate (UK is 100) ACT - Labor force participation (Short for active) GDP - GDP per county AGE - Percentage of children aged 5 to 15 in the county COUTAX_FEMALEUNEMP - Interaction between COUTAX and UNEMPF Council district names are included in the data file, though are not returned by load. """ import numpy as np from statsmodels.datasets import utils as du from os.path import dirname, abspath def load(): """ Load the Scotvote data and returns a Dataset instance. Returns ------- Dataset instance: See DATASET_PROPOSAL.txt for more information. """ data = _get_data() return du.process_recarray(data, endog_idx=0, dtype=float) def load_pandas(): """ Load the Scotvote data and returns a Dataset instance. Returns ------- Dataset instance: See DATASET_PROPOSAL.txt for more information. """ data = _get_data() return du.process_recarray_pandas(data, endog_idx=0, dtype=float) def _get_data(): filepath = dirname(abspath(__file__)) with open(filepath + '/scotvote.csv',"rb") as f: data = np.recfromtxt(f, delimiter=",", names=True, dtype=float, usecols=(1,2,3,4,5,6,7,8)) return data
en
0.899116
Taxation Powers Vote for the Scottish Parliament 1997 dataset. Used with express permission from the original author, who retains all rights. <NAME>'s `Generalized Linear Models: A Unified Approach` http://jgill.wustl.edu/research/books.html Taxation Powers' Yes Vote for Scottish Parliamanet-1997 This data is based on the example in Gill and describes the proportion of voters who voted Yes to grant the Scottish Parliament taxation powers. The data are divided into 32 council districts. This example's explanatory variables include the amount of council tax collected in pounds sterling as of April 1997 per two adults before adjustments, the female percentage of total claims for unemployment benefits as of January, 1998, the standardized mortality rate (UK is 100), the percentage of labor force participation, regional GDP, the percentage of children aged 5 to 15, and an interaction term between female unemployment and the council tax. The original source files and variable information are included in /scotland/src/ :: Number of Observations - 32 (1 for each Scottish district) Number of Variables - 8 Variable name definitions:: YES - Proportion voting yes to granting taxation powers to the Scottish parliament. COUTAX - Amount of council tax collected in pounds steling as of April '97 UNEMPF - Female percentage of total unemployment benefits claims as of January 1998 MOR - The standardized mortality rate (UK is 100) ACT - Labor force participation (Short for active) GDP - GDP per county AGE - Percentage of children aged 5 to 15 in the county COUTAX_FEMALEUNEMP - Interaction between COUTAX and UNEMPF Council district names are included in the data file, though are not returned by load. Load the Scotvote data and returns a Dataset instance. Returns ------- Dataset instance: See DATASET_PROPOSAL.txt for more information. Load the Scotvote data and returns a Dataset instance. Returns ------- Dataset instance: See DATASET_PROPOSAL.txt for more information.
2.483541
2
Lib/strategies/zscore_trend.py
DylanScotney/cryptocurrency_backtesting
0
6625806
<reponame>DylanScotney/cryptocurrency_backtesting from matplotlib import pyplot as plt import pandas as pd from .abstract_MA import movingAverageTrader from ..types.zscore import zScore class zScoreTrader(movingAverageTrader): """ A class that backtests a z score and MA based trading algorithm which attempts to capitalise on the over compensation of moves in the cryptocurrency market. Returns are stored under df['returns']. Refer to base class, movingAverageTrading for more details. Uses a (typically longer) moving average to determine the overall trend. Only longs (shorts) trades will be executed if asset is in uptrend (downtrend). A second (typically shorter) lookback period is used to determine the zscore of the asset and execute trading logic. Initialisation: - df: pandas dataframe containing asset price history - asset_symbol: header of asset price history in df - slow_MA: period of a moving average that is used to to determine the trend - zscore_period: lookback period for calculating z score - bandwidth: bandwidth of zscore values on which trading logic is executed. - fast_MA: A MA period shorter than slow_MA that will determine trend. If not specified period=0 (i.e. spotprice is used) Members: - self.df: df (see initialisation) - self.sym: asset_symbol (see initialisation) - self.trading_fee: tradine_fee (see initialisation) - self.position: (Position) Custom position object to handle trade positions. - self.fastMA: (moving average) custom moving average type object that handles moving average of series. - self.slowMA: moving average with longer period than self.fastMA. - self.zscore: (zScore) custom zScore object that handles z score of corresponding series. - self.bandwidth: (float) bandwidth for trading logic - self.opentimes: (list, int) holds indeces of trade opening times - self.closetimes: (list, int) holds indeces of trade closing times Notes: - Currently designed to only open one positon at a time """ def __init__(self, df, asset_symbol, MA_type, slow_MA, zscore_period, bandwidth, fast_MA=1, trading_fee=0.0): if not isinstance(zscore_period, int) or zscore_period <= 0: raise ValueError("Z score period must be positive integer") args = (df, asset_symbol, MA_type, slow_MA) kwargs = {"fast_MA": fast_MA, "trading_fee": trading_fee} super(zScoreTrader, self).__init__(*args, **kwargs) self.zscore = zScore(df[self.sym], zscore_period) self.bandwith = bandwidth self.opentimes = [] self.closetimes = [] def trade(self, plot=False): """ Executes all trades from the earliest value that the SMA can be determined. Inputs: - plot: (bool) optional arg to plot trading results """ self.opentimes = [] self.closetimes = [] for t in range(self.slowMA.period, self.df.shape[0]): slowMA_t = self.slowMA.getValue(t) fastMA_t = self.fastMA.getValue(t) Z_t = self.zscore.getValue(t) Z_t_1 = self.zscore.getValue(t-1) if fastMA_t > slowMA_t: uptrend = True else: uptrend = False # Open position logic # ----------------------------------------------------------------- if uptrend and self.position.position == 0: if Z_t > -self.bandwith and Z_t_1 < -self.bandwith: self.openPosition(t, 'L') self.opentimes.append(t) if not uptrend and self.position.position == 0: if Z_t < self.bandwith and Z_t_1 > self.bandwith: self.openPosition(t, 'S') self.opentimes.append(t) # ----------------------------------------------------------------- # Close position logic # ----------------------------------------------------------------- if self.position.position == 1 and Z_t > 0 and Z_t_1 < 0: self.closePosition(t) self.closetimes.append(t) if self.position.position == -1 and Z_t < 0 and Z_t_1 > 0: self.closePosition(t) self.closetimes.append(t) # ----------------------------------------------------------------- if plot: self.plotTrading() return self.df['returns'].cumsum().iloc[-1] def plotTrading(self): """ Plots the executed trading. 3x1 subplots: subplot 1: asset price w/ longer MA to dictate trend and shorter MA to determine moves via zscore subplot 2: Z score with specified bandwidths subplot 3: Cumulative returns Notes: - All three plots have green and red verticle lines indicating opening and closing positions - Will only open longs in uptrend (spotprice > longer MA) and only enter shorts in downtrend (spotprice < longer MA) """ bw = self.bandwith t0 = self.slowMA.period T = self.df.shape[0] zscore_MA = (self.df[self.sym] .rolling(window=self.zscore.period) .mean()) plt.subplot(311) self.df.loc[t0:T, self.sym].plot(label=self.sym) self.slowMA.values.loc[t0:T].plot(label=self.slowMA.name) zscore_MA.loc[t0:T].plot(label=self.zscore.name) if self.fastMA.period > 1: self.fastMA.values.loc[t0:T].plot(label=self.fastMA.name) plt.ylabel('{}/BTC'.format(self.sym)) [plt.axvline(x, c='g', lw=0.5, ls='--') for x in self.opentimes] [plt.axvline(x, c='r', lw=0.5, ls='--') for x in self.closetimes] plt.legend() plt.subplot(312) self.zscore.values.loc[t0:T].plot() plt.plot([t0, T], [bw, bw], c='k', ls='--', lw=0.5) plt.plot([t0, T], [-bw, -bw], c='k', ls='--', lw=0.5) plt.plot([t0, T], [0, 0], c='k', ls='--', lw=0.5) [plt.axvline(x, c='g', lw=0.5, ls='--') for x in self.opentimes] [plt.axvline(x, c='r', lw=0.5, ls='--') for x in self.closetimes] plt.ylabel('Z Score') plt.subplot(313) returns = self.df.loc[t0:T, 'returns'].cumsum()*100 returns.plot() plt.ylabel('Returns (%)') plt.xlabel('Hours') plt.show()
from matplotlib import pyplot as plt import pandas as pd from .abstract_MA import movingAverageTrader from ..types.zscore import zScore class zScoreTrader(movingAverageTrader): """ A class that backtests a z score and MA based trading algorithm which attempts to capitalise on the over compensation of moves in the cryptocurrency market. Returns are stored under df['returns']. Refer to base class, movingAverageTrading for more details. Uses a (typically longer) moving average to determine the overall trend. Only longs (shorts) trades will be executed if asset is in uptrend (downtrend). A second (typically shorter) lookback period is used to determine the zscore of the asset and execute trading logic. Initialisation: - df: pandas dataframe containing asset price history - asset_symbol: header of asset price history in df - slow_MA: period of a moving average that is used to to determine the trend - zscore_period: lookback period for calculating z score - bandwidth: bandwidth of zscore values on which trading logic is executed. - fast_MA: A MA period shorter than slow_MA that will determine trend. If not specified period=0 (i.e. spotprice is used) Members: - self.df: df (see initialisation) - self.sym: asset_symbol (see initialisation) - self.trading_fee: tradine_fee (see initialisation) - self.position: (Position) Custom position object to handle trade positions. - self.fastMA: (moving average) custom moving average type object that handles moving average of series. - self.slowMA: moving average with longer period than self.fastMA. - self.zscore: (zScore) custom zScore object that handles z score of corresponding series. - self.bandwidth: (float) bandwidth for trading logic - self.opentimes: (list, int) holds indeces of trade opening times - self.closetimes: (list, int) holds indeces of trade closing times Notes: - Currently designed to only open one positon at a time """ def __init__(self, df, asset_symbol, MA_type, slow_MA, zscore_period, bandwidth, fast_MA=1, trading_fee=0.0): if not isinstance(zscore_period, int) or zscore_period <= 0: raise ValueError("Z score period must be positive integer") args = (df, asset_symbol, MA_type, slow_MA) kwargs = {"fast_MA": fast_MA, "trading_fee": trading_fee} super(zScoreTrader, self).__init__(*args, **kwargs) self.zscore = zScore(df[self.sym], zscore_period) self.bandwith = bandwidth self.opentimes = [] self.closetimes = [] def trade(self, plot=False): """ Executes all trades from the earliest value that the SMA can be determined. Inputs: - plot: (bool) optional arg to plot trading results """ self.opentimes = [] self.closetimes = [] for t in range(self.slowMA.period, self.df.shape[0]): slowMA_t = self.slowMA.getValue(t) fastMA_t = self.fastMA.getValue(t) Z_t = self.zscore.getValue(t) Z_t_1 = self.zscore.getValue(t-1) if fastMA_t > slowMA_t: uptrend = True else: uptrend = False # Open position logic # ----------------------------------------------------------------- if uptrend and self.position.position == 0: if Z_t > -self.bandwith and Z_t_1 < -self.bandwith: self.openPosition(t, 'L') self.opentimes.append(t) if not uptrend and self.position.position == 0: if Z_t < self.bandwith and Z_t_1 > self.bandwith: self.openPosition(t, 'S') self.opentimes.append(t) # ----------------------------------------------------------------- # Close position logic # ----------------------------------------------------------------- if self.position.position == 1 and Z_t > 0 and Z_t_1 < 0: self.closePosition(t) self.closetimes.append(t) if self.position.position == -1 and Z_t < 0 and Z_t_1 > 0: self.closePosition(t) self.closetimes.append(t) # ----------------------------------------------------------------- if plot: self.plotTrading() return self.df['returns'].cumsum().iloc[-1] def plotTrading(self): """ Plots the executed trading. 3x1 subplots: subplot 1: asset price w/ longer MA to dictate trend and shorter MA to determine moves via zscore subplot 2: Z score with specified bandwidths subplot 3: Cumulative returns Notes: - All three plots have green and red verticle lines indicating opening and closing positions - Will only open longs in uptrend (spotprice > longer MA) and only enter shorts in downtrend (spotprice < longer MA) """ bw = self.bandwith t0 = self.slowMA.period T = self.df.shape[0] zscore_MA = (self.df[self.sym] .rolling(window=self.zscore.period) .mean()) plt.subplot(311) self.df.loc[t0:T, self.sym].plot(label=self.sym) self.slowMA.values.loc[t0:T].plot(label=self.slowMA.name) zscore_MA.loc[t0:T].plot(label=self.zscore.name) if self.fastMA.period > 1: self.fastMA.values.loc[t0:T].plot(label=self.fastMA.name) plt.ylabel('{}/BTC'.format(self.sym)) [plt.axvline(x, c='g', lw=0.5, ls='--') for x in self.opentimes] [plt.axvline(x, c='r', lw=0.5, ls='--') for x in self.closetimes] plt.legend() plt.subplot(312) self.zscore.values.loc[t0:T].plot() plt.plot([t0, T], [bw, bw], c='k', ls='--', lw=0.5) plt.plot([t0, T], [-bw, -bw], c='k', ls='--', lw=0.5) plt.plot([t0, T], [0, 0], c='k', ls='--', lw=0.5) [plt.axvline(x, c='g', lw=0.5, ls='--') for x in self.opentimes] [plt.axvline(x, c='r', lw=0.5, ls='--') for x in self.closetimes] plt.ylabel('Z Score') plt.subplot(313) returns = self.df.loc[t0:T, 'returns'].cumsum()*100 returns.plot() plt.ylabel('Returns (%)') plt.xlabel('Hours') plt.show()
en
0.732089
A class that backtests a z score and MA based trading algorithm which attempts to capitalise on the over compensation of moves in the cryptocurrency market. Returns are stored under df['returns']. Refer to base class, movingAverageTrading for more details. Uses a (typically longer) moving average to determine the overall trend. Only longs (shorts) trades will be executed if asset is in uptrend (downtrend). A second (typically shorter) lookback period is used to determine the zscore of the asset and execute trading logic. Initialisation: - df: pandas dataframe containing asset price history - asset_symbol: header of asset price history in df - slow_MA: period of a moving average that is used to to determine the trend - zscore_period: lookback period for calculating z score - bandwidth: bandwidth of zscore values on which trading logic is executed. - fast_MA: A MA period shorter than slow_MA that will determine trend. If not specified period=0 (i.e. spotprice is used) Members: - self.df: df (see initialisation) - self.sym: asset_symbol (see initialisation) - self.trading_fee: tradine_fee (see initialisation) - self.position: (Position) Custom position object to handle trade positions. - self.fastMA: (moving average) custom moving average type object that handles moving average of series. - self.slowMA: moving average with longer period than self.fastMA. - self.zscore: (zScore) custom zScore object that handles z score of corresponding series. - self.bandwidth: (float) bandwidth for trading logic - self.opentimes: (list, int) holds indeces of trade opening times - self.closetimes: (list, int) holds indeces of trade closing times Notes: - Currently designed to only open one positon at a time Executes all trades from the earliest value that the SMA can be determined. Inputs: - plot: (bool) optional arg to plot trading results # Open position logic # ----------------------------------------------------------------- # ----------------------------------------------------------------- # Close position logic # ----------------------------------------------------------------- # ----------------------------------------------------------------- Plots the executed trading. 3x1 subplots: subplot 1: asset price w/ longer MA to dictate trend and shorter MA to determine moves via zscore subplot 2: Z score with specified bandwidths subplot 3: Cumulative returns Notes: - All three plots have green and red verticle lines indicating opening and closing positions - Will only open longs in uptrend (spotprice > longer MA) and only enter shorts in downtrend (spotprice < longer MA)
3.169036
3
utilities/statistics_utilities/episode_statistics.py
bootml/agent
0
6625807
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'cnheider' import numpy as np class EpisodeStatistics(object): def __init__(self): super().__init__() durations = [] signals = [] def moving_average(self, window_size=100): signal_ma = np.mean(self.signals[-window_size:]) duration_ma = np.mean(self.durations[-window_size:]) return signal_ma, duration_ma
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'cnheider' import numpy as np class EpisodeStatistics(object): def __init__(self): super().__init__() durations = [] signals = [] def moving_average(self, window_size=100): signal_ma = np.mean(self.signals[-window_size:]) duration_ma = np.mean(self.durations[-window_size:]) return signal_ma, duration_ma
en
0.308914
#!/usr/bin/env python3 # -*- coding: utf-8 -*-
2.667539
3
LSTM/lstm_model.py
dannytse/crypto-priceanalysis
1
6625808
import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers as layers from keras.models import Sequential from keras.layers import Activation, Dense, Dropout, LSTM import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from sklearn.metrics import mean_absolute_error def lstm(features, labels, dropout, neurons, dense_units, technicals): ''' batch_size = tf.shape(features)[0] n_outputs = tf.shape(labels)[1] initial_state = tf.zeros([batch_size, num_layers * cell_size]) # RNN cells = layers.StackedRNNCells([layers.GRUCell(cell_size) for _ in range(num_layers)]) rnn_layer = layers.RNN(cells) rnn_output = rnn_layer(features, initial_state=initial_state) # Dropout dropout = layers.Dropout(rate=dropout) dropout_output = dropout(rnn_output) # Dense Layers dense_layer = layers.Dense(dense_units, activation=tf.nn.selu) dense_layer_output = dense_layer(dropout_output) final = layers.Dense(n_outputs,activation=tf.sigmoid) final_output = final(dense_layer_output) ''' n_outputs = tf.shape(labels)[1] # cells = layers.StackedRNNCells([layers.LSTMCell(cell_size) for _ in range(num_layers)]) model = tf.keras.Sequential() model.add(layers.LSTM(neurons, input_shape=(features.shape[1], features.shape[2]))) # model.add(layers.LSTM(neurons, input_shape=(22, 27))) model.add(layers.Dropout(rate=dropout)) model.add(layers.Activation(activation=tf.sigmoid)) model.add(layers.Dense(dense_units, activation=tf.nn.selu)) model.add(layers.Dense(n_outputs,activation=tf.sigmoid)) model.compile(optimizer='adam', loss='mse') return model ''' def lstm(features, labels, dropout, num_layers, cell_size, dense_units, technicals): batch_size = tf.shape(features)[0] n_outputs = tf.shape(labels)[1] initial_state = tf.zeros([batch_size, num_layers * cell_size]) # RNN cells = layers.StackedRNNCells([layers.LSTMCell(cell_size) for _ in range(num_layers)]) rnn_output = layers.RNN(cells, features)(initial_state=initial_state) # Dropout dropout = layers.Dropout(rnn_output[:,-1], keep_prob=1-dropout) # Dense Layers dense_layer = layers.Dense(dropout, dense_units, activation=tf.nn.selu) preds = tf.layers.Dense(dense_layer,n_outputs,activation=tf.sigmoid) return preds '''
import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers as layers from keras.models import Sequential from keras.layers import Activation, Dense, Dropout, LSTM import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from sklearn.metrics import mean_absolute_error def lstm(features, labels, dropout, neurons, dense_units, technicals): ''' batch_size = tf.shape(features)[0] n_outputs = tf.shape(labels)[1] initial_state = tf.zeros([batch_size, num_layers * cell_size]) # RNN cells = layers.StackedRNNCells([layers.GRUCell(cell_size) for _ in range(num_layers)]) rnn_layer = layers.RNN(cells) rnn_output = rnn_layer(features, initial_state=initial_state) # Dropout dropout = layers.Dropout(rate=dropout) dropout_output = dropout(rnn_output) # Dense Layers dense_layer = layers.Dense(dense_units, activation=tf.nn.selu) dense_layer_output = dense_layer(dropout_output) final = layers.Dense(n_outputs,activation=tf.sigmoid) final_output = final(dense_layer_output) ''' n_outputs = tf.shape(labels)[1] # cells = layers.StackedRNNCells([layers.LSTMCell(cell_size) for _ in range(num_layers)]) model = tf.keras.Sequential() model.add(layers.LSTM(neurons, input_shape=(features.shape[1], features.shape[2]))) # model.add(layers.LSTM(neurons, input_shape=(22, 27))) model.add(layers.Dropout(rate=dropout)) model.add(layers.Activation(activation=tf.sigmoid)) model.add(layers.Dense(dense_units, activation=tf.nn.selu)) model.add(layers.Dense(n_outputs,activation=tf.sigmoid)) model.compile(optimizer='adam', loss='mse') return model ''' def lstm(features, labels, dropout, num_layers, cell_size, dense_units, technicals): batch_size = tf.shape(features)[0] n_outputs = tf.shape(labels)[1] initial_state = tf.zeros([batch_size, num_layers * cell_size]) # RNN cells = layers.StackedRNNCells([layers.LSTMCell(cell_size) for _ in range(num_layers)]) rnn_output = layers.RNN(cells, features)(initial_state=initial_state) # Dropout dropout = layers.Dropout(rnn_output[:,-1], keep_prob=1-dropout) # Dense Layers dense_layer = layers.Dense(dropout, dense_units, activation=tf.nn.selu) preds = tf.layers.Dense(dense_layer,n_outputs,activation=tf.sigmoid) return preds '''
en
0.539719
batch_size = tf.shape(features)[0] n_outputs = tf.shape(labels)[1] initial_state = tf.zeros([batch_size, num_layers * cell_size]) # RNN cells = layers.StackedRNNCells([layers.GRUCell(cell_size) for _ in range(num_layers)]) rnn_layer = layers.RNN(cells) rnn_output = rnn_layer(features, initial_state=initial_state) # Dropout dropout = layers.Dropout(rate=dropout) dropout_output = dropout(rnn_output) # Dense Layers dense_layer = layers.Dense(dense_units, activation=tf.nn.selu) dense_layer_output = dense_layer(dropout_output) final = layers.Dense(n_outputs,activation=tf.sigmoid) final_output = final(dense_layer_output) # cells = layers.StackedRNNCells([layers.LSTMCell(cell_size) for _ in range(num_layers)]) # model.add(layers.LSTM(neurons, input_shape=(22, 27))) def lstm(features, labels, dropout, num_layers, cell_size, dense_units, technicals): batch_size = tf.shape(features)[0] n_outputs = tf.shape(labels)[1] initial_state = tf.zeros([batch_size, num_layers * cell_size]) # RNN cells = layers.StackedRNNCells([layers.LSTMCell(cell_size) for _ in range(num_layers)]) rnn_output = layers.RNN(cells, features)(initial_state=initial_state) # Dropout dropout = layers.Dropout(rnn_output[:,-1], keep_prob=1-dropout) # Dense Layers dense_layer = layers.Dense(dropout, dense_units, activation=tf.nn.selu) preds = tf.layers.Dense(dense_layer,n_outputs,activation=tf.sigmoid) return preds
3.019412
3
dask/array/optimization.py
callumanoble/dask
0
6625809
<reponame>callumanoble/dask<filename>dask/array/optimization.py from itertools import zip_longest from operator import getitem import numpy as np from .core import getter, getter_nofancy, getter_inline from ..blockwise import optimize_blockwise, fuse_roots from ..core import flatten, reverse_dict from ..optimization import fuse, inline_functions from ..utils import ensure_dict from ..highlevelgraph import HighLevelGraph from numbers import Integral # All get* functions the optimizations know about GETTERS = (getter, getter_nofancy, getter_inline, getitem) # These get* functions aren't ever completely removed from the graph, # even if the index should be a no-op by numpy semantics. Some array-like's # don't completely follow semantics, making indexing always necessary. GETNOREMOVE = (getter, getter_nofancy) def optimize( dsk, keys, fuse_keys=None, fast_functions=None, inline_functions_fast_functions=(getter_inline,), rename_fused_keys=True, **kwargs ): """Optimize dask for array computation 1. Cull tasks not necessary to evaluate keys 2. Remove full slicing, e.g. x[:] 3. Inline fast functions like getitem and np.transpose """ if not isinstance(keys, (list, set)): keys = [keys] keys = list(flatten(keys)) if not isinstance(dsk, HighLevelGraph): dsk = HighLevelGraph.from_collections(id(dsk), dsk, dependencies=()) dsk = optimize_blockwise(dsk, keys=keys) dsk = fuse_roots(dsk, keys=keys) dsk = dsk.cull(set(keys)) dependencies = dsk.get_all_dependencies() dsk = ensure_dict(dsk) # Low level task optimizations if fast_functions is not None: inline_functions_fast_functions = fast_functions hold = hold_keys(dsk, dependencies) dsk, dependencies = fuse( dsk, hold + keys + (fuse_keys or []), dependencies, rename_keys=rename_fused_keys, ) if inline_functions_fast_functions: dsk = inline_functions( dsk, keys, dependencies=dependencies, fast_functions=inline_functions_fast_functions, ) return optimize_slices(dsk) def hold_keys(dsk, dependencies): """Find keys to avoid fusion We don't want to fuse data present in the graph because it is easier to serialize as a raw value. We don't want to fuse chains after getitem/GETTERS because we want to move around only small pieces of data, rather than the underlying arrays. """ dependents = reverse_dict(dependencies) data = {k for k, v in dsk.items() if type(v) not in (tuple, str)} hold_keys = list(data) for dat in data: deps = dependents[dat] for dep in deps: task = dsk[dep] # If the task is a get* function, we walk up the chain, and stop # when there's either more than one dependent, or the dependent is # no longer a get* function or an alias. We then add the final # key to the list of keys not to fuse. if type(task) is tuple and task and task[0] in GETTERS: try: while len(dependents[dep]) == 1: new_dep = next(iter(dependents[dep])) new_task = dsk[new_dep] # If the task is a get* or an alias, continue up the # linear chain if new_task[0] in GETTERS or new_task in dsk: dep = new_dep else: break except (IndexError, TypeError): pass hold_keys.append(dep) return hold_keys def optimize_slices(dsk): """Optimize slices 1. Fuse repeated slices, like x[5:][2:6] -> x[7:11] 2. Remove full slices, like x[:] -> x See also: fuse_slice_dict """ fancy_ind_types = (list, np.ndarray) dsk = dsk.copy() for k, v in dsk.items(): if type(v) is tuple and v[0] in GETTERS and len(v) in (3, 5): if len(v) == 3: get, a, a_index = v # getter defaults to asarray=True, getitem is semantically False a_asarray = get is not getitem a_lock = None else: get, a, a_index, a_asarray, a_lock = v while type(a) is tuple and a[0] in GETTERS and len(a) in (3, 5): if len(a) == 3: f2, b, b_index = a b_asarray = f2 is not getitem b_lock = None else: f2, b, b_index, b_asarray, b_lock = a if a_lock and a_lock is not b_lock: break if (type(a_index) is tuple) != (type(b_index) is tuple): break if type(a_index) is tuple: indices = b_index + a_index if len(a_index) != len(b_index) and any(i is None for i in indices): break if f2 is getter_nofancy and any( isinstance(i, fancy_ind_types) for i in indices ): break elif f2 is getter_nofancy and ( type(a_index) in fancy_ind_types or type(b_index) in fancy_ind_types ): break try: c_index = fuse_slice(b_index, a_index) # rely on fact that nested gets never decrease in # strictness e.g. `(getter_nofancy, (getter, ...))` never # happens get = getter if f2 is getter_inline else f2 except NotImplementedError: break a, a_index, a_lock = b, c_index, b_lock a_asarray |= b_asarray # Skip the get call if not from from_array and nothing to do if get not in GETNOREMOVE and ( ( type(a_index) is slice and not a_index.start and a_index.stop is None and a_index.step is None ) or ( type(a_index) is tuple and all( type(s) is slice and not s.start and s.stop is None and s.step is None for s in a_index ) ) ): dsk[k] = a elif get is getitem or (a_asarray and not a_lock): # default settings are fine, drop the extra parameters Since we # always fallback to inner `get` functions, `get is getitem` # can only occur if all gets are getitem, meaning all # parameters must be getitem defaults. dsk[k] = (get, a, a_index) else: dsk[k] = (get, a, a_index, a_asarray, a_lock) return dsk def normalize_slice(s): """Replace Nones in slices with integers >>> normalize_slice(slice(None, None, None)) slice(0, None, 1) """ start, stop, step = s.start, s.stop, s.step if start is None: start = 0 if step is None: step = 1 if start < 0 or step < 0 or stop is not None and stop < 0: raise NotImplementedError() return slice(start, stop, step) def check_for_nonfusible_fancy_indexing(fancy, normal): # Check for fancy indexing and normal indexing, where the fancy # indexed dimensions != normal indexed dimensions with integers. E.g.: # disallow things like: # x[:, [1, 2], :][0, :, :] -> x[0, [1, 2], :] or # x[0, :, :][:, [1, 2], :] -> x[0, [1, 2], :] for f, n in zip_longest(fancy, normal, fillvalue=slice(None)): if type(f) is not list and isinstance(n, Integral): raise NotImplementedError( "Can't handle normal indexing with " "integers and fancy indexing if the " "integers and fancy indices don't " "align with the same dimensions." ) def fuse_slice(a, b): """Fuse stacked slices together Fuse a pair of repeated slices into a single slice: >>> fuse_slice(slice(1000, 2000), slice(10, 15)) slice(1010, 1015, None) This also works for tuples of slices >>> fuse_slice((slice(100, 200), slice(100, 200, 10)), ... (slice(10, 15), [5, 2])) (slice(110, 115, None), [150, 120]) And a variety of other interesting cases >>> fuse_slice(slice(1000, 2000), 10) # integers 1010 >>> fuse_slice(slice(1000, 2000, 5), slice(10, 20, 2)) slice(1050, 1100, 10) >>> fuse_slice(slice(1000, 2000, 5), [1, 2, 3]) # lists [1005, 1010, 1015] >>> fuse_slice(None, slice(None, None)) # doctest: +SKIP None """ # None only works if the second side is a full slice if a is None and isinstance(b, slice) and b == slice(None, None): return None # Replace None with 0 and one in start and step if isinstance(a, slice): a = normalize_slice(a) if isinstance(b, slice): b = normalize_slice(b) if isinstance(a, slice) and isinstance(b, Integral): if b < 0: raise NotImplementedError() return a.start + b * a.step if isinstance(a, slice) and isinstance(b, slice): start = a.start + a.step * b.start if b.stop is not None: stop = a.start + a.step * b.stop else: stop = None if a.stop is not None: if stop is not None: stop = min(a.stop, stop) else: stop = a.stop step = a.step * b.step if step == 1: step = None return slice(start, stop, step) if isinstance(b, list): return [fuse_slice(a, bb) for bb in b] if isinstance(a, list) and isinstance(b, (Integral, slice)): return a[b] if isinstance(a, tuple) and not isinstance(b, tuple): b = (b,) # If given two tuples walk through both, being mindful of uneven sizes # and newaxes if isinstance(a, tuple) and isinstance(b, tuple): # Check for non-fusible cases with fancy-indexing a_has_lists = any(isinstance(item, list) for item in a) b_has_lists = any(isinstance(item, list) for item in b) if a_has_lists and b_has_lists: raise NotImplementedError("Can't handle multiple list indexing") elif a_has_lists: check_for_nonfusible_fancy_indexing(a, b) elif b_has_lists: check_for_nonfusible_fancy_indexing(b, a) j = 0 result = list() for i in range(len(a)): # axis ceased to exist or we're out of b if isinstance(a[i], Integral) or j == len(b): result.append(a[i]) continue while b[j] is None: # insert any Nones on the rhs result.append(None) j += 1 result.append(fuse_slice(a[i], b[j])) # Common case j += 1 while j < len(b): # anything leftover on the right? result.append(b[j]) j += 1 return tuple(result) raise NotImplementedError()
from itertools import zip_longest from operator import getitem import numpy as np from .core import getter, getter_nofancy, getter_inline from ..blockwise import optimize_blockwise, fuse_roots from ..core import flatten, reverse_dict from ..optimization import fuse, inline_functions from ..utils import ensure_dict from ..highlevelgraph import HighLevelGraph from numbers import Integral # All get* functions the optimizations know about GETTERS = (getter, getter_nofancy, getter_inline, getitem) # These get* functions aren't ever completely removed from the graph, # even if the index should be a no-op by numpy semantics. Some array-like's # don't completely follow semantics, making indexing always necessary. GETNOREMOVE = (getter, getter_nofancy) def optimize( dsk, keys, fuse_keys=None, fast_functions=None, inline_functions_fast_functions=(getter_inline,), rename_fused_keys=True, **kwargs ): """Optimize dask for array computation 1. Cull tasks not necessary to evaluate keys 2. Remove full slicing, e.g. x[:] 3. Inline fast functions like getitem and np.transpose """ if not isinstance(keys, (list, set)): keys = [keys] keys = list(flatten(keys)) if not isinstance(dsk, HighLevelGraph): dsk = HighLevelGraph.from_collections(id(dsk), dsk, dependencies=()) dsk = optimize_blockwise(dsk, keys=keys) dsk = fuse_roots(dsk, keys=keys) dsk = dsk.cull(set(keys)) dependencies = dsk.get_all_dependencies() dsk = ensure_dict(dsk) # Low level task optimizations if fast_functions is not None: inline_functions_fast_functions = fast_functions hold = hold_keys(dsk, dependencies) dsk, dependencies = fuse( dsk, hold + keys + (fuse_keys or []), dependencies, rename_keys=rename_fused_keys, ) if inline_functions_fast_functions: dsk = inline_functions( dsk, keys, dependencies=dependencies, fast_functions=inline_functions_fast_functions, ) return optimize_slices(dsk) def hold_keys(dsk, dependencies): """Find keys to avoid fusion We don't want to fuse data present in the graph because it is easier to serialize as a raw value. We don't want to fuse chains after getitem/GETTERS because we want to move around only small pieces of data, rather than the underlying arrays. """ dependents = reverse_dict(dependencies) data = {k for k, v in dsk.items() if type(v) not in (tuple, str)} hold_keys = list(data) for dat in data: deps = dependents[dat] for dep in deps: task = dsk[dep] # If the task is a get* function, we walk up the chain, and stop # when there's either more than one dependent, or the dependent is # no longer a get* function or an alias. We then add the final # key to the list of keys not to fuse. if type(task) is tuple and task and task[0] in GETTERS: try: while len(dependents[dep]) == 1: new_dep = next(iter(dependents[dep])) new_task = dsk[new_dep] # If the task is a get* or an alias, continue up the # linear chain if new_task[0] in GETTERS or new_task in dsk: dep = new_dep else: break except (IndexError, TypeError): pass hold_keys.append(dep) return hold_keys def optimize_slices(dsk): """Optimize slices 1. Fuse repeated slices, like x[5:][2:6] -> x[7:11] 2. Remove full slices, like x[:] -> x See also: fuse_slice_dict """ fancy_ind_types = (list, np.ndarray) dsk = dsk.copy() for k, v in dsk.items(): if type(v) is tuple and v[0] in GETTERS and len(v) in (3, 5): if len(v) == 3: get, a, a_index = v # getter defaults to asarray=True, getitem is semantically False a_asarray = get is not getitem a_lock = None else: get, a, a_index, a_asarray, a_lock = v while type(a) is tuple and a[0] in GETTERS and len(a) in (3, 5): if len(a) == 3: f2, b, b_index = a b_asarray = f2 is not getitem b_lock = None else: f2, b, b_index, b_asarray, b_lock = a if a_lock and a_lock is not b_lock: break if (type(a_index) is tuple) != (type(b_index) is tuple): break if type(a_index) is tuple: indices = b_index + a_index if len(a_index) != len(b_index) and any(i is None for i in indices): break if f2 is getter_nofancy and any( isinstance(i, fancy_ind_types) for i in indices ): break elif f2 is getter_nofancy and ( type(a_index) in fancy_ind_types or type(b_index) in fancy_ind_types ): break try: c_index = fuse_slice(b_index, a_index) # rely on fact that nested gets never decrease in # strictness e.g. `(getter_nofancy, (getter, ...))` never # happens get = getter if f2 is getter_inline else f2 except NotImplementedError: break a, a_index, a_lock = b, c_index, b_lock a_asarray |= b_asarray # Skip the get call if not from from_array and nothing to do if get not in GETNOREMOVE and ( ( type(a_index) is slice and not a_index.start and a_index.stop is None and a_index.step is None ) or ( type(a_index) is tuple and all( type(s) is slice and not s.start and s.stop is None and s.step is None for s in a_index ) ) ): dsk[k] = a elif get is getitem or (a_asarray and not a_lock): # default settings are fine, drop the extra parameters Since we # always fallback to inner `get` functions, `get is getitem` # can only occur if all gets are getitem, meaning all # parameters must be getitem defaults. dsk[k] = (get, a, a_index) else: dsk[k] = (get, a, a_index, a_asarray, a_lock) return dsk def normalize_slice(s): """Replace Nones in slices with integers >>> normalize_slice(slice(None, None, None)) slice(0, None, 1) """ start, stop, step = s.start, s.stop, s.step if start is None: start = 0 if step is None: step = 1 if start < 0 or step < 0 or stop is not None and stop < 0: raise NotImplementedError() return slice(start, stop, step) def check_for_nonfusible_fancy_indexing(fancy, normal): # Check for fancy indexing and normal indexing, where the fancy # indexed dimensions != normal indexed dimensions with integers. E.g.: # disallow things like: # x[:, [1, 2], :][0, :, :] -> x[0, [1, 2], :] or # x[0, :, :][:, [1, 2], :] -> x[0, [1, 2], :] for f, n in zip_longest(fancy, normal, fillvalue=slice(None)): if type(f) is not list and isinstance(n, Integral): raise NotImplementedError( "Can't handle normal indexing with " "integers and fancy indexing if the " "integers and fancy indices don't " "align with the same dimensions." ) def fuse_slice(a, b): """Fuse stacked slices together Fuse a pair of repeated slices into a single slice: >>> fuse_slice(slice(1000, 2000), slice(10, 15)) slice(1010, 1015, None) This also works for tuples of slices >>> fuse_slice((slice(100, 200), slice(100, 200, 10)), ... (slice(10, 15), [5, 2])) (slice(110, 115, None), [150, 120]) And a variety of other interesting cases >>> fuse_slice(slice(1000, 2000), 10) # integers 1010 >>> fuse_slice(slice(1000, 2000, 5), slice(10, 20, 2)) slice(1050, 1100, 10) >>> fuse_slice(slice(1000, 2000, 5), [1, 2, 3]) # lists [1005, 1010, 1015] >>> fuse_slice(None, slice(None, None)) # doctest: +SKIP None """ # None only works if the second side is a full slice if a is None and isinstance(b, slice) and b == slice(None, None): return None # Replace None with 0 and one in start and step if isinstance(a, slice): a = normalize_slice(a) if isinstance(b, slice): b = normalize_slice(b) if isinstance(a, slice) and isinstance(b, Integral): if b < 0: raise NotImplementedError() return a.start + b * a.step if isinstance(a, slice) and isinstance(b, slice): start = a.start + a.step * b.start if b.stop is not None: stop = a.start + a.step * b.stop else: stop = None if a.stop is not None: if stop is not None: stop = min(a.stop, stop) else: stop = a.stop step = a.step * b.step if step == 1: step = None return slice(start, stop, step) if isinstance(b, list): return [fuse_slice(a, bb) for bb in b] if isinstance(a, list) and isinstance(b, (Integral, slice)): return a[b] if isinstance(a, tuple) and not isinstance(b, tuple): b = (b,) # If given two tuples walk through both, being mindful of uneven sizes # and newaxes if isinstance(a, tuple) and isinstance(b, tuple): # Check for non-fusible cases with fancy-indexing a_has_lists = any(isinstance(item, list) for item in a) b_has_lists = any(isinstance(item, list) for item in b) if a_has_lists and b_has_lists: raise NotImplementedError("Can't handle multiple list indexing") elif a_has_lists: check_for_nonfusible_fancy_indexing(a, b) elif b_has_lists: check_for_nonfusible_fancy_indexing(b, a) j = 0 result = list() for i in range(len(a)): # axis ceased to exist or we're out of b if isinstance(a[i], Integral) or j == len(b): result.append(a[i]) continue while b[j] is None: # insert any Nones on the rhs result.append(None) j += 1 result.append(fuse_slice(a[i], b[j])) # Common case j += 1 while j < len(b): # anything leftover on the right? result.append(b[j]) j += 1 return tuple(result) raise NotImplementedError()
en
0.788073
# All get* functions the optimizations know about # These get* functions aren't ever completely removed from the graph, # even if the index should be a no-op by numpy semantics. Some array-like's # don't completely follow semantics, making indexing always necessary. Optimize dask for array computation 1. Cull tasks not necessary to evaluate keys 2. Remove full slicing, e.g. x[:] 3. Inline fast functions like getitem and np.transpose # Low level task optimizations Find keys to avoid fusion We don't want to fuse data present in the graph because it is easier to serialize as a raw value. We don't want to fuse chains after getitem/GETTERS because we want to move around only small pieces of data, rather than the underlying arrays. # If the task is a get* function, we walk up the chain, and stop # when there's either more than one dependent, or the dependent is # no longer a get* function or an alias. We then add the final # key to the list of keys not to fuse. # If the task is a get* or an alias, continue up the # linear chain Optimize slices 1. Fuse repeated slices, like x[5:][2:6] -> x[7:11] 2. Remove full slices, like x[:] -> x See also: fuse_slice_dict # getter defaults to asarray=True, getitem is semantically False # rely on fact that nested gets never decrease in # strictness e.g. `(getter_nofancy, (getter, ...))` never # happens # Skip the get call if not from from_array and nothing to do # default settings are fine, drop the extra parameters Since we # always fallback to inner `get` functions, `get is getitem` # can only occur if all gets are getitem, meaning all # parameters must be getitem defaults. Replace Nones in slices with integers >>> normalize_slice(slice(None, None, None)) slice(0, None, 1) # Check for fancy indexing and normal indexing, where the fancy # indexed dimensions != normal indexed dimensions with integers. E.g.: # disallow things like: # x[:, [1, 2], :][0, :, :] -> x[0, [1, 2], :] or # x[0, :, :][:, [1, 2], :] -> x[0, [1, 2], :] Fuse stacked slices together Fuse a pair of repeated slices into a single slice: >>> fuse_slice(slice(1000, 2000), slice(10, 15)) slice(1010, 1015, None) This also works for tuples of slices >>> fuse_slice((slice(100, 200), slice(100, 200, 10)), ... (slice(10, 15), [5, 2])) (slice(110, 115, None), [150, 120]) And a variety of other interesting cases >>> fuse_slice(slice(1000, 2000), 10) # integers 1010 >>> fuse_slice(slice(1000, 2000, 5), slice(10, 20, 2)) slice(1050, 1100, 10) >>> fuse_slice(slice(1000, 2000, 5), [1, 2, 3]) # lists [1005, 1010, 1015] >>> fuse_slice(None, slice(None, None)) # doctest: +SKIP None # None only works if the second side is a full slice # Replace None with 0 and one in start and step # If given two tuples walk through both, being mindful of uneven sizes # and newaxes # Check for non-fusible cases with fancy-indexing # axis ceased to exist or we're out of b # insert any Nones on the rhs # Common case # anything leftover on the right?
2.07661
2
cle/backends/elf/source_manager.py
yuzeming/cle
0
6625810
<filename>cle/backends/elf/source_manager.py import logging import os from elftools.dwarf.dwarfinfo import DWARFInfo from elftools.elf.elffile import ELFFile from elftools.dwarf.lineprogram import LineProgramEntry, LineState l = logging.getLogger(__name__) class SourceInfoEntry(object): def __init__(self, fn:str, line:int, col:int, addr: int) -> None: self.fn = fn self.line = line self.col = col self.addr = addr def __repr__(self) -> str: return "%s %d %d: %x" % (self.fn, self.line, self.col, self.addr) class SourceManager(object): raw_state = [] # type: list[SourceInfoEntry] file_list = set() offset = 0 def __init__(self, dwarf_info: DWARFInfo, binary_path:str) -> None: binary_dir = os.path.dirname(binary_path) for cu in dwarf_info.iter_CUs(): l.info('Found a compile unit at offset %s, length %s' % (cu.cu_offset, cu['unit_length'])) line_program = dwarf_info.line_program_for_CU(cu) if line_program is None: l.info("DWARF info is missing a line program for this CU") continue lp_header = line_program.header file_entries = lp_header["file_entry"] file_list = ["_NONE_"] for file_entry in file_entries: dir_index = file_entry["dir_index"] if dir_index == 0: file_list.append(os.path.join( binary_dir, file_entry.name.decode() )) else: file_list.append(os.path.join( lp_header["include_directory"][dir_index - 1], file_entry.name ).decode()) lp_entries = line_program.get_entries() for lp_entry in lp_entries: s = lp_entry.state if not s or s.file == 0 or not s.is_stmt: continue self.raw_state.append(SourceInfoEntry(file_list[s.file], s.line, s.column, s.address)) self.file_list.add(file_list[s.file]) def map_to_address(self, fn: str, line: int, col: int or None=None): return [s.addr+self.offset for s in self.raw_state if s.fn == fn and s.line == line and (col is None or s.col == col)] def map_to_source(self, addr:None): ret = [s for s in self.raw_state if s.addr+self.offset == addr] if len(ret) == 1: return (ret[0].fn, ret[0].line, ret[0].col) return None def get_breakpoint_line_list(self, fn:str): return list(set([s.line for s in self.raw_state if s.fn == fn]))
<filename>cle/backends/elf/source_manager.py import logging import os from elftools.dwarf.dwarfinfo import DWARFInfo from elftools.elf.elffile import ELFFile from elftools.dwarf.lineprogram import LineProgramEntry, LineState l = logging.getLogger(__name__) class SourceInfoEntry(object): def __init__(self, fn:str, line:int, col:int, addr: int) -> None: self.fn = fn self.line = line self.col = col self.addr = addr def __repr__(self) -> str: return "%s %d %d: %x" % (self.fn, self.line, self.col, self.addr) class SourceManager(object): raw_state = [] # type: list[SourceInfoEntry] file_list = set() offset = 0 def __init__(self, dwarf_info: DWARFInfo, binary_path:str) -> None: binary_dir = os.path.dirname(binary_path) for cu in dwarf_info.iter_CUs(): l.info('Found a compile unit at offset %s, length %s' % (cu.cu_offset, cu['unit_length'])) line_program = dwarf_info.line_program_for_CU(cu) if line_program is None: l.info("DWARF info is missing a line program for this CU") continue lp_header = line_program.header file_entries = lp_header["file_entry"] file_list = ["_NONE_"] for file_entry in file_entries: dir_index = file_entry["dir_index"] if dir_index == 0: file_list.append(os.path.join( binary_dir, file_entry.name.decode() )) else: file_list.append(os.path.join( lp_header["include_directory"][dir_index - 1], file_entry.name ).decode()) lp_entries = line_program.get_entries() for lp_entry in lp_entries: s = lp_entry.state if not s or s.file == 0 or not s.is_stmt: continue self.raw_state.append(SourceInfoEntry(file_list[s.file], s.line, s.column, s.address)) self.file_list.add(file_list[s.file]) def map_to_address(self, fn: str, line: int, col: int or None=None): return [s.addr+self.offset for s in self.raw_state if s.fn == fn and s.line == line and (col is None or s.col == col)] def map_to_source(self, addr:None): ret = [s for s in self.raw_state if s.addr+self.offset == addr] if len(ret) == 1: return (ret[0].fn, ret[0].line, ret[0].col) return None def get_breakpoint_line_list(self, fn:str): return list(set([s.line for s in self.raw_state if s.fn == fn]))
en
0.257364
# type: list[SourceInfoEntry]
2.348353
2
python/testData/intentions/PythonDemorganLawIntentionTest/complex.py
jnthn/intellij-community
2
6625811
<reponame>jnthn/intellij-community<gh_stars>1-10 a = True b = False c = True d = False #before intention if a and b and c or<caret> d: print "before"
a = True b = False c = True d = False #before intention if a and b and c or<caret> d: print "before"
en
0.639194
#before intention
2.633858
3
collatz.py
danj7/Collatz-Mapper
0
6625812
import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches import matplotlib.animation as anim import sys def collatz_mapper(amax, bmax, div=2, nlim=20): """ Returns a Numpy array with the Collatz Map. Utilizes ints to build the map. Parameters ---------- amax: int Maximum positive 'a' value of the map (horizontal axis). The map goes from -amax to amax. bmax: int Maximum positive 'b' value of the map (vertical axis). The map goes from -bmax to bmax. div: int Divisor for the generalized Collatz Problem. nlim: int Maximimum number of integers to search for convergence. """ a_range = range(-amax, amax) b_range = range(-bmax,bmax) d = div collatz_map = np.zeros((len(b_range), len(a_range))) n_currs = range(1,nlim+1) n_min_init = 999999 #initialization value for n_min, so that it is bigger than n_curr n_max = 1000000000 calc_steps = 10 max_mini_steps = 100 #maximum steps in collatz sequence to check for convergence escape_value = np.pi #value given to list of fixed points if number of steps exceded. for a in a_range: for b in b_range: min_fix = [] for n_curr in n_currs: #print('a, b, n = ',a, b, n_curr) step = 1 escaped = False for _ in range(calc_steps): if n_curr%d == 0: if n_curr == 0: n_min = 0 break else: n_curr = n_curr // d else: n_curr = a*n_curr + b n_min = n_curr + n_min_init while n_min != n_curr: #print('n_curr=', n_curr, ', n_min=', n_min) n_min = min(n_min, n_curr) if n_curr%d == 0: if n_curr == 0: n_min = 0 break else: n_curr = n_curr // d else: n_curr = a*n_curr + b step += 1 if step > max_mini_steps or abs(n_curr) > n_max: #print('escaped') escaped = True break if escaped: min_fix.append(escape_value) escaped = False else: min_fix.append(n_min) #adding point to map min_fix_setlist = list(set(min_fix)) if np.pi in min_fix_setlist: if [np.pi]==min_fix_setlist: collatz_map[b + bmax, a + amax] = 0 else: collatz_map[b + bmax, a + amax] = 1 else: if len(min_fix_setlist) == 1: collatz_map[b + bmax, a + amax] = 3 else: collatz_map[b + bmax, a + amax] = 2 # return collatz_map # def collatz_plotter(col_map, div = 0, cmap='inferno', legend=True): """ Plots the collatz map. Parameters ---------- colmap: numpy array Contains the map. div: int Used as figure number and for filename if empty. save_fig: boolean Declares whether to save the figure or not. savename: string Name of the file where figure will be saved. cmap: string or colormap Set by default to 'inferno'. """ if div==0: fig = plt.figure() div = '' else: fig = plt.figure(div) ax=fig.add_subplot(1,1,1) values = np.unique(col_map) image = plt.imshow(col_map, cmap=cmap) colors = [image.cmap(image.norm(value)) for value in values] labels = ['no convergence', 'convergence for some', 'convergence for all at diff', 'convergence for all at same'] patches = [mpatches.Patch(color=colors[i], label=labels[i]) for i in range(len(values))] if legend: plt.legend(handles=patches, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) if div!=0: plt.title('divisor = '+str(div)) plt.axis('off') plt.show() # def collatz_animation(amax, bmax, div): """ Returns an animation object and saves it as Gif. """ pass # if __name__ == '__main__': int_parameters = [] for arg in sys.argv[1:]: int_parameters.append(int(arg)) if all([type(elem)==int for elem in int_parameters]): amax, bmax, div, nlim = int_parameters[:4] else: amax, bmax, div, nlim = eval(input('enter all ints with commas: amax, bmax, div, nlim\n')) #amax, bmax, div, nlim = 1024, 1024, 2, 20 print('parameters: amax=', amax, ', bmax=',bmax, ', div=',div, ', nlim=',nlim) collatz_map = collatz_mapper(amax, bmax, div, nlim) #Save collatz map to file filename = 'collatz_map_a'+str(amax)+'_b'+str(bmax)+'_div'+str(div)+'.colmap' with open(filename, 'w') as file: for row in range(2*amax): for column in range(2*bmax): file.write(str(collatz_map[row,column])+'\t') file.write('\n') # collatz_plotter(collatz_map, div)
import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches import matplotlib.animation as anim import sys def collatz_mapper(amax, bmax, div=2, nlim=20): """ Returns a Numpy array with the Collatz Map. Utilizes ints to build the map. Parameters ---------- amax: int Maximum positive 'a' value of the map (horizontal axis). The map goes from -amax to amax. bmax: int Maximum positive 'b' value of the map (vertical axis). The map goes from -bmax to bmax. div: int Divisor for the generalized Collatz Problem. nlim: int Maximimum number of integers to search for convergence. """ a_range = range(-amax, amax) b_range = range(-bmax,bmax) d = div collatz_map = np.zeros((len(b_range), len(a_range))) n_currs = range(1,nlim+1) n_min_init = 999999 #initialization value for n_min, so that it is bigger than n_curr n_max = 1000000000 calc_steps = 10 max_mini_steps = 100 #maximum steps in collatz sequence to check for convergence escape_value = np.pi #value given to list of fixed points if number of steps exceded. for a in a_range: for b in b_range: min_fix = [] for n_curr in n_currs: #print('a, b, n = ',a, b, n_curr) step = 1 escaped = False for _ in range(calc_steps): if n_curr%d == 0: if n_curr == 0: n_min = 0 break else: n_curr = n_curr // d else: n_curr = a*n_curr + b n_min = n_curr + n_min_init while n_min != n_curr: #print('n_curr=', n_curr, ', n_min=', n_min) n_min = min(n_min, n_curr) if n_curr%d == 0: if n_curr == 0: n_min = 0 break else: n_curr = n_curr // d else: n_curr = a*n_curr + b step += 1 if step > max_mini_steps or abs(n_curr) > n_max: #print('escaped') escaped = True break if escaped: min_fix.append(escape_value) escaped = False else: min_fix.append(n_min) #adding point to map min_fix_setlist = list(set(min_fix)) if np.pi in min_fix_setlist: if [np.pi]==min_fix_setlist: collatz_map[b + bmax, a + amax] = 0 else: collatz_map[b + bmax, a + amax] = 1 else: if len(min_fix_setlist) == 1: collatz_map[b + bmax, a + amax] = 3 else: collatz_map[b + bmax, a + amax] = 2 # return collatz_map # def collatz_plotter(col_map, div = 0, cmap='inferno', legend=True): """ Plots the collatz map. Parameters ---------- colmap: numpy array Contains the map. div: int Used as figure number and for filename if empty. save_fig: boolean Declares whether to save the figure or not. savename: string Name of the file where figure will be saved. cmap: string or colormap Set by default to 'inferno'. """ if div==0: fig = plt.figure() div = '' else: fig = plt.figure(div) ax=fig.add_subplot(1,1,1) values = np.unique(col_map) image = plt.imshow(col_map, cmap=cmap) colors = [image.cmap(image.norm(value)) for value in values] labels = ['no convergence', 'convergence for some', 'convergence for all at diff', 'convergence for all at same'] patches = [mpatches.Patch(color=colors[i], label=labels[i]) for i in range(len(values))] if legend: plt.legend(handles=patches, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) if div!=0: plt.title('divisor = '+str(div)) plt.axis('off') plt.show() # def collatz_animation(amax, bmax, div): """ Returns an animation object and saves it as Gif. """ pass # if __name__ == '__main__': int_parameters = [] for arg in sys.argv[1:]: int_parameters.append(int(arg)) if all([type(elem)==int for elem in int_parameters]): amax, bmax, div, nlim = int_parameters[:4] else: amax, bmax, div, nlim = eval(input('enter all ints with commas: amax, bmax, div, nlim\n')) #amax, bmax, div, nlim = 1024, 1024, 2, 20 print('parameters: amax=', amax, ', bmax=',bmax, ', div=',div, ', nlim=',nlim) collatz_map = collatz_mapper(amax, bmax, div, nlim) #Save collatz map to file filename = 'collatz_map_a'+str(amax)+'_b'+str(bmax)+'_div'+str(div)+'.colmap' with open(filename, 'w') as file: for row in range(2*amax): for column in range(2*bmax): file.write(str(collatz_map[row,column])+'\t') file.write('\n') # collatz_plotter(collatz_map, div)
en
0.571819
Returns a Numpy array with the Collatz Map. Utilizes ints to build the map. Parameters ---------- amax: int Maximum positive 'a' value of the map (horizontal axis). The map goes from -amax to amax. bmax: int Maximum positive 'b' value of the map (vertical axis). The map goes from -bmax to bmax. div: int Divisor for the generalized Collatz Problem. nlim: int Maximimum number of integers to search for convergence. #initialization value for n_min, so that it is bigger than n_curr #maximum steps in collatz sequence to check for convergence #value given to list of fixed points if number of steps exceded. #print('a, b, n = ',a, b, n_curr) #print('n_curr=', n_curr, ', n_min=', n_min) #print('escaped') #adding point to map # # Plots the collatz map. Parameters ---------- colmap: numpy array Contains the map. div: int Used as figure number and for filename if empty. save_fig: boolean Declares whether to save the figure or not. savename: string Name of the file where figure will be saved. cmap: string or colormap Set by default to 'inferno'. # Returns an animation object and saves it as Gif. # #amax, bmax, div, nlim = 1024, 1024, 2, 20 #Save collatz map to file #
3.368936
3
web/api/maestro_api/db/mongo.py
Farfetch/maestro
21
6625813
from mongoengine import connect from maestro_api.db.repo.user import UserRepository from maestro_api.db.models.user import UserRole def init_db(flask_app=None): connect(**flask_app.config["MONGODB_SETTINGS"]) def init_db_data(flask_app): "Init DB initial data" if flask_app.config["OAUTH_ENABLED"] is False: user_repo = UserRepository() user_repo.create_or_update( name="Anonymous", email=flask_app.config["MOCK_AUTH_ANONYMOUS_USER_EMAIL"], role=UserRole.ADMIN.value, )
from mongoengine import connect from maestro_api.db.repo.user import UserRepository from maestro_api.db.models.user import UserRole def init_db(flask_app=None): connect(**flask_app.config["MONGODB_SETTINGS"]) def init_db_data(flask_app): "Init DB initial data" if flask_app.config["OAUTH_ENABLED"] is False: user_repo = UserRepository() user_repo.create_or_update( name="Anonymous", email=flask_app.config["MOCK_AUTH_ANONYMOUS_USER_EMAIL"], role=UserRole.ADMIN.value, )
none
1
2.074078
2
src/azure-cli/azure/cli/command_modules/acr/_docker_utils.py
WCollins3/azure-cli
1
6625814
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- try: from urllib.parse import urlencode, urlparse, urlunparse except ImportError: from urllib import urlencode from urlparse import urlparse, urlunparse import time from json import loads from base64 import b64encode import requests from requests import RequestException from requests.utils import to_native_string from msrest.http_logger import log_request, log_response from knack.util import CLIError from knack.prompting import prompt, prompt_pass, NoTTYException from knack.log import get_logger from azure.cli.core.util import should_disable_connection_verify from azure.cli.core.cloud import CloudSuffixNotSetException from azure.cli.core._profile import _AZ_LOGIN_MESSAGE from ._client_factory import cf_acr_registries from ._constants import get_managed_sku from ._utils import get_registry_by_name, ResourceNotFound logger = get_logger(__name__) EMPTY_GUID = '00000000-0000-0000-0000-000000000000' ALLOWED_HTTP_METHOD = ['get', 'patch', 'put', 'delete'] ACCESS_TOKEN_PERMISSION = ['pull', 'push', 'delete', 'push,pull', 'delete,pull'] AAD_TOKEN_BASE_ERROR_MESSAGE = "Unable to get AAD authorization tokens with message" ADMIN_USER_BASE_ERROR_MESSAGE = "Unable to get admin user credentials with message" def _get_aad_token_after_challenge(cli_ctx, token_params, login_server, only_refresh_token, repository, artifact_repository, permission, is_diagnostics_context): authurl = urlparse(token_params['realm']) authhost = urlunparse((authurl[0], authurl[1], '/oauth2/exchange', '', '', '')) from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cli_ctx) creds, _, tenant = profile.get_raw_token() headers = {'Content-Type': 'application/x-www-form-urlencoded'} content = { 'grant_type': 'access_token', 'service': token_params['service'], 'tenant': tenant, 'access_token': creds[1] } response = requests.post(authhost, urlencode(content), headers=headers, verify=(not should_disable_connection_verify())) if response.status_code not in [200]: from ._errors import CONNECTIVITY_REFRESH_TOKEN_ERROR if is_diagnostics_context: return CONNECTIVITY_REFRESH_TOKEN_ERROR.format_error_message(login_server, response.status_code) raise CLIError(CONNECTIVITY_REFRESH_TOKEN_ERROR.format_error_message(login_server, response.status_code) .get_error_message()) refresh_token = loads(response.content.decode("utf-8"))["refresh_token"] if only_refresh_token: return refresh_token authhost = urlunparse((authurl[0], authurl[1], '/oauth2/token', '', '', '')) if repository: scope = 'repository:{}:{}'.format(repository, permission) elif artifact_repository: scope = 'artifact-repository:{}:{}'.format(artifact_repository, permission) else: # catalog only has * as permission, even for a read operation scope = 'registry:catalog:*' content = { 'grant_type': 'refresh_token', 'service': login_server, 'scope': scope, 'refresh_token': refresh_token } response = requests.post(authhost, urlencode(content), headers=headers, verify=(not should_disable_connection_verify())) if response.status_code not in [200]: from ._errors import CONNECTIVITY_ACCESS_TOKEN_ERROR if is_diagnostics_context: return CONNECTIVITY_ACCESS_TOKEN_ERROR.format_error_message(login_server, response.status_code) raise CLIError(CONNECTIVITY_ACCESS_TOKEN_ERROR.format_error_message(login_server, response.status_code) .get_error_message()) return loads(response.content.decode("utf-8"))["access_token"] def _get_aad_token(cli_ctx, login_server, only_refresh_token, repository=None, artifact_repository=None, permission=None, is_diagnostics_context=False): """Obtains refresh and access tokens for an AAD-enabled registry. :param str login_server: The registry login server URL to log in to :param bool only_refresh_token: Whether to ask for only refresh token, or for both refresh and access tokens :param str repository: Repository for which the access token is requested :param str artifact_repository: Artifact repository for which the access token is requested :param str permission: The requested permission on the repository, '*' or 'pull' """ if repository and artifact_repository: raise ValueError("Only one of repository and artifact_repository can be provided.") if (repository or artifact_repository) and permission not in ACCESS_TOKEN_PERMISSION: raise ValueError( "Permission is required for a repository or artifact_repository. Allowed access token permission: {}" .format(ACCESS_TOKEN_PERMISSION)) login_server = login_server.rstrip('/') challenge = requests.get('https://' + login_server + '/v2/', verify=(not should_disable_connection_verify())) if challenge.status_code not in [401] or 'WWW-Authenticate' not in challenge.headers: from ._errors import CONNECTIVITY_CHALLENGE_ERROR if is_diagnostics_context: return CONNECTIVITY_CHALLENGE_ERROR.format_error_message(login_server) raise CLIError(CONNECTIVITY_CHALLENGE_ERROR.format_error_message(login_server).get_error_message()) authenticate = challenge.headers['WWW-Authenticate'] tokens = authenticate.split(' ', 2) if len(tokens) < 2 or tokens[0].lower() != 'bearer': from ._errors import CONNECTIVITY_AAD_LOGIN_ERROR if is_diagnostics_context: return CONNECTIVITY_AAD_LOGIN_ERROR.format_error_message(login_server) raise CLIError(CONNECTIVITY_AAD_LOGIN_ERROR.format_error_message(login_server).get_error_message()) token_params = {y[0]: y[1].strip('"') for y in (x.strip().split('=', 2) for x in tokens[1].split(','))} if 'realm' not in token_params or 'service' not in token_params: from ._errors import CONNECTIVITY_AAD_LOGIN_ERROR if is_diagnostics_context: return CONNECTIVITY_AAD_LOGIN_ERROR.format_error_message(login_server) raise CLIError(CONNECTIVITY_AAD_LOGIN_ERROR.format_error_message(login_server).get_error_message()) return _get_aad_token_after_challenge(cli_ctx, token_params, login_server, only_refresh_token, repository, artifact_repository, permission, is_diagnostics_context) def _get_credentials(cmd, # pylint: disable=too-many-statements registry_name, tenant_suffix, username, password, only_refresh_token, repository=None, artifact_repository=None, permission=None): """Try to get AAD authorization tokens or admin user credentials. :param str registry_name: The name of container registry :param str tenant_suffix: The registry login server tenant suffix :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry :param bool only_refresh_token: Whether to ask for only refresh token, or for both refresh and access tokens :param str repository: Repository for which the access token is requested :param str artifact_repository: Artifact repository for which the access token is requested :param str permission: The requested permission on the repository, '*' or 'pull' """ # Raise an error if password is specified but username isn't if not username and password: raise CLIError('Please also specify username if password is specified.') cli_ctx = cmd.cli_ctx resource_not_found, registry = None, None try: registry, resource_group_name = get_registry_by_name(cli_ctx, registry_name) login_server = registry.login_server if tenant_suffix: logger.warning( "Obtained registry login server '%s' from service. The specified suffix '%s' is ignored.", login_server, tenant_suffix) except (ResourceNotFound, CLIError) as e: resource_not_found = str(e) logger.debug("Could not get registry from service. Exception: %s", resource_not_found) if not isinstance(e, ResourceNotFound) and _AZ_LOGIN_MESSAGE not in resource_not_found: raise # Try to use the pre-defined login server suffix to construct login server from registry name. login_server_suffix = get_login_server_suffix(cli_ctx) if not login_server_suffix: raise login_server = '{}{}{}'.format( registry_name, '-{}'.format(tenant_suffix) if tenant_suffix else '', login_server_suffix).lower() # Validate the login server is reachable url = 'https://' + login_server + '/v2/' try: challenge = requests.get(url, verify=(not should_disable_connection_verify())) if challenge.status_code in [403]: raise CLIError("Looks like you don't have access to registry '{}'. ".format(login_server) + "To see configured firewall rules, run" + " 'az acr show --query networkRuleSet --name {}'. ".format(registry_name) + "Details: https://docs.microsoft.com/en-us/azure/container-registry/container-registry-health-error-reference#connectivity_forbidden_error") # pylint: disable=line-too-long except RequestException as e: logger.debug("Could not connect to registry login server. Exception: %s", str(e)) if resource_not_found: logger.warning("%s\nUsing '%s' as the default registry login server.", resource_not_found, login_server) raise CLIError("Could not connect to the registry login server '{}'. ".format(login_server) + "Please verify that the registry exists and " + "the URL '{}' is reachable from your environment.".format(url)) # 1. if username was specified, verify that password was also specified if username: if not password: try: password = prompt_pass(msg='Password: ') except NoTTYException: raise CLIError('Please specify both username and password in non-interactive mode.') return login_server, username, password # 2. if we don't yet have credentials, attempt to get a refresh token if not registry or registry.sku.name in get_managed_sku(cmd): try: return login_server, EMPTY_GUID, _get_aad_token( cli_ctx, login_server, only_refresh_token, repository, artifact_repository, permission) except CLIError as e: logger.warning("%s: %s", AAD_TOKEN_BASE_ERROR_MESSAGE, str(e)) # 3. if we still don't have credentials, attempt to get the admin credentials (if enabled) if registry: if registry.admin_user_enabled: try: cred = cf_acr_registries(cli_ctx).list_credentials(resource_group_name, registry_name) return login_server, cred.username, cred.passwords[0].value except CLIError as e: logger.warning("%s: %s", ADMIN_USER_BASE_ERROR_MESSAGE, str(e)) else: logger.warning("%s: %s", ADMIN_USER_BASE_ERROR_MESSAGE, "Admin user is disabled.") else: logger.warning("%s: %s", ADMIN_USER_BASE_ERROR_MESSAGE, resource_not_found) # 4. if we still don't have credentials, prompt the user try: username = prompt('Username: ') password = <PASSWORD>(msg='Password: ') return login_server, username, password except NoTTYException: raise CLIError( 'Unable to authenticate using AAD or admin login credentials. ' + 'Please specify both username and password in non-interactive mode.') return login_server, None, None def get_login_credentials(cmd, registry_name, tenant_suffix=None, username=None, password=None): """Try to get AAD authorization tokens or admin user credentials to log into a registry. :param str registry_name: The name of container registry :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry """ return _get_credentials(cmd, registry_name, tenant_suffix, username, password, only_refresh_token=True) def get_access_credentials(cmd, registry_name, tenant_suffix=None, username=None, password=<PASSWORD>, repository=None, artifact_repository=None, permission=None): """Try to get AAD authorization tokens or admin user credentials to access a registry. :param str registry_name: The name of container registry :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry :param str repository: Repository for which the access token is requested :param str artifact_repository: Artifact repository for which the access token is requested :param str permission: The requested permission on the repository """ return _get_credentials(cmd, registry_name, tenant_suffix, username, password, only_refresh_token=False, repository=repository, artifact_repository=artifact_repository, permission=permission) def log_registry_response(response): """Log the HTTP request and response of a registry API call. :param Response response: The response object """ log_request(None, response.request) log_response(None, response.request, RegistryResponse(response.request, response)) def get_login_server_suffix(cli_ctx): """Get the Azure Container Registry login server suffix in the current cloud.""" try: return cli_ctx.cloud.suffixes.acr_login_server_endpoint except CloudSuffixNotSetException as e: logger.debug("Could not get login server endpoint suffix. Exception: %s", str(e)) # Ignore the error if the suffix is not set, the caller should then try to get login server from server. return None def _get_basic_auth_str(username, password): return 'Basic ' + to_native_string( b64encode(('%s:%s' % (username, password)).encode('latin1')).strip() ) def _get_bearer_auth_str(token): return 'Bearer ' + token def get_authorization_header(username, password): """Get the authorization header as Basic auth if username is provided, or Bearer auth otherwise :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry """ if username == EMPTY_GUID: auth = _get_bearer_auth_str(password) else: auth = _get_basic_auth_str(username, password) return {'Authorization': auth} def request_data_from_registry(http_method, login_server, path, username, password, result_index=None, json_payload=None, file_payload=None, params=None, retry_times=3, retry_interval=5): if http_method not in ALLOWED_HTTP_METHOD: raise ValueError("Allowed http method: {}".format(ALLOWED_HTTP_METHOD)) if json_payload and file_payload: raise ValueError("One of json_payload and file_payload can be specified.") if http_method in ['get', 'delete'] and (json_payload or file_payload): raise ValueError("Empty payload is required for http method: {}".format(http_method)) if http_method in ['patch', 'put'] and not (json_payload or file_payload): raise ValueError("Non-empty payload is required for http method: {}".format(http_method)) url = 'https://{}{}'.format(login_server, path) headers = get_authorization_header(username, password) for i in range(0, retry_times): errorMessage = None try: if file_payload: with open(file_payload, 'rb') as data_payload: response = requests.request( method=http_method, url=url, headers=headers, params=params, data=data_payload, verify=(not should_disable_connection_verify()) ) else: response = requests.request( method=http_method, url=url, headers=headers, params=params, json=json_payload, verify=(not should_disable_connection_verify()) ) log_registry_response(response) if response.status_code == 200: result = response.json()[result_index] if result_index else response.json() next_link = response.headers['link'] if 'link' in response.headers else None return result, next_link if response.status_code == 201 or response.status_code == 202: result = None try: result = response.json()[result_index] if result_index else response.json() except ValueError as e: logger.debug('Response is empty or is not a valid json. Exception: %s', str(e)) return result, None if response.status_code == 204: return None, None if response.status_code == 401: raise RegistryException( parse_error_message('Authentication required.', response), response.status_code) if response.status_code == 404: raise RegistryException( parse_error_message('The requested data does not exist.', response), response.status_code) if response.status_code == 405: raise RegistryException( parse_error_message('This operation is not supported.', response), response.status_code) if response.status_code == 409: raise RegistryException( parse_error_message('Failed to request data due to a conflict.', response), response.status_code) raise Exception(parse_error_message('Could not {} the requested data.'.format(http_method), response)) except CLIError: raise except Exception as e: # pylint: disable=broad-except errorMessage = str(e) logger.debug('Retrying %s with exception %s', i + 1, errorMessage) time.sleep(retry_interval) raise CLIError(errorMessage) def parse_error_message(error_message, response): import json try: server_message = json.loads(response.text)['errors'][0]['message'] error_message = 'Error: {}'.format(server_message) if server_message else error_message except (ValueError, KeyError, TypeError, IndexError): pass if not error_message.endswith('.'): error_message = '{}.'.format(error_message) try: correlation_id = response.headers['x-ms-correlation-request-id'] return '{} Correlation ID: {}.'.format(error_message, correlation_id) except (KeyError, TypeError, AttributeError): return error_message class RegistryException(CLIError): def __init__(self, message, status_code): super(RegistryException, self).__init__(message) self.status_code = status_code class RegistryResponse(object): # pylint: disable=too-few-public-methods def __init__(self, request, internal_response): self.request = request self.internal_response = internal_response self.status_code = internal_response.status_code self.headers = internal_response.headers self.encoding = internal_response.encoding self.reason = internal_response.reason self.content = internal_response.content def text(self): return self.content.decode(self.encoding or "utf-8")
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- try: from urllib.parse import urlencode, urlparse, urlunparse except ImportError: from urllib import urlencode from urlparse import urlparse, urlunparse import time from json import loads from base64 import b64encode import requests from requests import RequestException from requests.utils import to_native_string from msrest.http_logger import log_request, log_response from knack.util import CLIError from knack.prompting import prompt, prompt_pass, NoTTYException from knack.log import get_logger from azure.cli.core.util import should_disable_connection_verify from azure.cli.core.cloud import CloudSuffixNotSetException from azure.cli.core._profile import _AZ_LOGIN_MESSAGE from ._client_factory import cf_acr_registries from ._constants import get_managed_sku from ._utils import get_registry_by_name, ResourceNotFound logger = get_logger(__name__) EMPTY_GUID = '00000000-0000-0000-0000-000000000000' ALLOWED_HTTP_METHOD = ['get', 'patch', 'put', 'delete'] ACCESS_TOKEN_PERMISSION = ['pull', 'push', 'delete', 'push,pull', 'delete,pull'] AAD_TOKEN_BASE_ERROR_MESSAGE = "Unable to get AAD authorization tokens with message" ADMIN_USER_BASE_ERROR_MESSAGE = "Unable to get admin user credentials with message" def _get_aad_token_after_challenge(cli_ctx, token_params, login_server, only_refresh_token, repository, artifact_repository, permission, is_diagnostics_context): authurl = urlparse(token_params['realm']) authhost = urlunparse((authurl[0], authurl[1], '/oauth2/exchange', '', '', '')) from azure.cli.core._profile import Profile profile = Profile(cli_ctx=cli_ctx) creds, _, tenant = profile.get_raw_token() headers = {'Content-Type': 'application/x-www-form-urlencoded'} content = { 'grant_type': 'access_token', 'service': token_params['service'], 'tenant': tenant, 'access_token': creds[1] } response = requests.post(authhost, urlencode(content), headers=headers, verify=(not should_disable_connection_verify())) if response.status_code not in [200]: from ._errors import CONNECTIVITY_REFRESH_TOKEN_ERROR if is_diagnostics_context: return CONNECTIVITY_REFRESH_TOKEN_ERROR.format_error_message(login_server, response.status_code) raise CLIError(CONNECTIVITY_REFRESH_TOKEN_ERROR.format_error_message(login_server, response.status_code) .get_error_message()) refresh_token = loads(response.content.decode("utf-8"))["refresh_token"] if only_refresh_token: return refresh_token authhost = urlunparse((authurl[0], authurl[1], '/oauth2/token', '', '', '')) if repository: scope = 'repository:{}:{}'.format(repository, permission) elif artifact_repository: scope = 'artifact-repository:{}:{}'.format(artifact_repository, permission) else: # catalog only has * as permission, even for a read operation scope = 'registry:catalog:*' content = { 'grant_type': 'refresh_token', 'service': login_server, 'scope': scope, 'refresh_token': refresh_token } response = requests.post(authhost, urlencode(content), headers=headers, verify=(not should_disable_connection_verify())) if response.status_code not in [200]: from ._errors import CONNECTIVITY_ACCESS_TOKEN_ERROR if is_diagnostics_context: return CONNECTIVITY_ACCESS_TOKEN_ERROR.format_error_message(login_server, response.status_code) raise CLIError(CONNECTIVITY_ACCESS_TOKEN_ERROR.format_error_message(login_server, response.status_code) .get_error_message()) return loads(response.content.decode("utf-8"))["access_token"] def _get_aad_token(cli_ctx, login_server, only_refresh_token, repository=None, artifact_repository=None, permission=None, is_diagnostics_context=False): """Obtains refresh and access tokens for an AAD-enabled registry. :param str login_server: The registry login server URL to log in to :param bool only_refresh_token: Whether to ask for only refresh token, or for both refresh and access tokens :param str repository: Repository for which the access token is requested :param str artifact_repository: Artifact repository for which the access token is requested :param str permission: The requested permission on the repository, '*' or 'pull' """ if repository and artifact_repository: raise ValueError("Only one of repository and artifact_repository can be provided.") if (repository or artifact_repository) and permission not in ACCESS_TOKEN_PERMISSION: raise ValueError( "Permission is required for a repository or artifact_repository. Allowed access token permission: {}" .format(ACCESS_TOKEN_PERMISSION)) login_server = login_server.rstrip('/') challenge = requests.get('https://' + login_server + '/v2/', verify=(not should_disable_connection_verify())) if challenge.status_code not in [401] or 'WWW-Authenticate' not in challenge.headers: from ._errors import CONNECTIVITY_CHALLENGE_ERROR if is_diagnostics_context: return CONNECTIVITY_CHALLENGE_ERROR.format_error_message(login_server) raise CLIError(CONNECTIVITY_CHALLENGE_ERROR.format_error_message(login_server).get_error_message()) authenticate = challenge.headers['WWW-Authenticate'] tokens = authenticate.split(' ', 2) if len(tokens) < 2 or tokens[0].lower() != 'bearer': from ._errors import CONNECTIVITY_AAD_LOGIN_ERROR if is_diagnostics_context: return CONNECTIVITY_AAD_LOGIN_ERROR.format_error_message(login_server) raise CLIError(CONNECTIVITY_AAD_LOGIN_ERROR.format_error_message(login_server).get_error_message()) token_params = {y[0]: y[1].strip('"') for y in (x.strip().split('=', 2) for x in tokens[1].split(','))} if 'realm' not in token_params or 'service' not in token_params: from ._errors import CONNECTIVITY_AAD_LOGIN_ERROR if is_diagnostics_context: return CONNECTIVITY_AAD_LOGIN_ERROR.format_error_message(login_server) raise CLIError(CONNECTIVITY_AAD_LOGIN_ERROR.format_error_message(login_server).get_error_message()) return _get_aad_token_after_challenge(cli_ctx, token_params, login_server, only_refresh_token, repository, artifact_repository, permission, is_diagnostics_context) def _get_credentials(cmd, # pylint: disable=too-many-statements registry_name, tenant_suffix, username, password, only_refresh_token, repository=None, artifact_repository=None, permission=None): """Try to get AAD authorization tokens or admin user credentials. :param str registry_name: The name of container registry :param str tenant_suffix: The registry login server tenant suffix :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry :param bool only_refresh_token: Whether to ask for only refresh token, or for both refresh and access tokens :param str repository: Repository for which the access token is requested :param str artifact_repository: Artifact repository for which the access token is requested :param str permission: The requested permission on the repository, '*' or 'pull' """ # Raise an error if password is specified but username isn't if not username and password: raise CLIError('Please also specify username if password is specified.') cli_ctx = cmd.cli_ctx resource_not_found, registry = None, None try: registry, resource_group_name = get_registry_by_name(cli_ctx, registry_name) login_server = registry.login_server if tenant_suffix: logger.warning( "Obtained registry login server '%s' from service. The specified suffix '%s' is ignored.", login_server, tenant_suffix) except (ResourceNotFound, CLIError) as e: resource_not_found = str(e) logger.debug("Could not get registry from service. Exception: %s", resource_not_found) if not isinstance(e, ResourceNotFound) and _AZ_LOGIN_MESSAGE not in resource_not_found: raise # Try to use the pre-defined login server suffix to construct login server from registry name. login_server_suffix = get_login_server_suffix(cli_ctx) if not login_server_suffix: raise login_server = '{}{}{}'.format( registry_name, '-{}'.format(tenant_suffix) if tenant_suffix else '', login_server_suffix).lower() # Validate the login server is reachable url = 'https://' + login_server + '/v2/' try: challenge = requests.get(url, verify=(not should_disable_connection_verify())) if challenge.status_code in [403]: raise CLIError("Looks like you don't have access to registry '{}'. ".format(login_server) + "To see configured firewall rules, run" + " 'az acr show --query networkRuleSet --name {}'. ".format(registry_name) + "Details: https://docs.microsoft.com/en-us/azure/container-registry/container-registry-health-error-reference#connectivity_forbidden_error") # pylint: disable=line-too-long except RequestException as e: logger.debug("Could not connect to registry login server. Exception: %s", str(e)) if resource_not_found: logger.warning("%s\nUsing '%s' as the default registry login server.", resource_not_found, login_server) raise CLIError("Could not connect to the registry login server '{}'. ".format(login_server) + "Please verify that the registry exists and " + "the URL '{}' is reachable from your environment.".format(url)) # 1. if username was specified, verify that password was also specified if username: if not password: try: password = prompt_pass(msg='Password: ') except NoTTYException: raise CLIError('Please specify both username and password in non-interactive mode.') return login_server, username, password # 2. if we don't yet have credentials, attempt to get a refresh token if not registry or registry.sku.name in get_managed_sku(cmd): try: return login_server, EMPTY_GUID, _get_aad_token( cli_ctx, login_server, only_refresh_token, repository, artifact_repository, permission) except CLIError as e: logger.warning("%s: %s", AAD_TOKEN_BASE_ERROR_MESSAGE, str(e)) # 3. if we still don't have credentials, attempt to get the admin credentials (if enabled) if registry: if registry.admin_user_enabled: try: cred = cf_acr_registries(cli_ctx).list_credentials(resource_group_name, registry_name) return login_server, cred.username, cred.passwords[0].value except CLIError as e: logger.warning("%s: %s", ADMIN_USER_BASE_ERROR_MESSAGE, str(e)) else: logger.warning("%s: %s", ADMIN_USER_BASE_ERROR_MESSAGE, "Admin user is disabled.") else: logger.warning("%s: %s", ADMIN_USER_BASE_ERROR_MESSAGE, resource_not_found) # 4. if we still don't have credentials, prompt the user try: username = prompt('Username: ') password = <PASSWORD>(msg='Password: ') return login_server, username, password except NoTTYException: raise CLIError( 'Unable to authenticate using AAD or admin login credentials. ' + 'Please specify both username and password in non-interactive mode.') return login_server, None, None def get_login_credentials(cmd, registry_name, tenant_suffix=None, username=None, password=None): """Try to get AAD authorization tokens or admin user credentials to log into a registry. :param str registry_name: The name of container registry :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry """ return _get_credentials(cmd, registry_name, tenant_suffix, username, password, only_refresh_token=True) def get_access_credentials(cmd, registry_name, tenant_suffix=None, username=None, password=<PASSWORD>, repository=None, artifact_repository=None, permission=None): """Try to get AAD authorization tokens or admin user credentials to access a registry. :param str registry_name: The name of container registry :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry :param str repository: Repository for which the access token is requested :param str artifact_repository: Artifact repository for which the access token is requested :param str permission: The requested permission on the repository """ return _get_credentials(cmd, registry_name, tenant_suffix, username, password, only_refresh_token=False, repository=repository, artifact_repository=artifact_repository, permission=permission) def log_registry_response(response): """Log the HTTP request and response of a registry API call. :param Response response: The response object """ log_request(None, response.request) log_response(None, response.request, RegistryResponse(response.request, response)) def get_login_server_suffix(cli_ctx): """Get the Azure Container Registry login server suffix in the current cloud.""" try: return cli_ctx.cloud.suffixes.acr_login_server_endpoint except CloudSuffixNotSetException as e: logger.debug("Could not get login server endpoint suffix. Exception: %s", str(e)) # Ignore the error if the suffix is not set, the caller should then try to get login server from server. return None def _get_basic_auth_str(username, password): return 'Basic ' + to_native_string( b64encode(('%s:%s' % (username, password)).encode('latin1')).strip() ) def _get_bearer_auth_str(token): return 'Bearer ' + token def get_authorization_header(username, password): """Get the authorization header as Basic auth if username is provided, or Bearer auth otherwise :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry """ if username == EMPTY_GUID: auth = _get_bearer_auth_str(password) else: auth = _get_basic_auth_str(username, password) return {'Authorization': auth} def request_data_from_registry(http_method, login_server, path, username, password, result_index=None, json_payload=None, file_payload=None, params=None, retry_times=3, retry_interval=5): if http_method not in ALLOWED_HTTP_METHOD: raise ValueError("Allowed http method: {}".format(ALLOWED_HTTP_METHOD)) if json_payload and file_payload: raise ValueError("One of json_payload and file_payload can be specified.") if http_method in ['get', 'delete'] and (json_payload or file_payload): raise ValueError("Empty payload is required for http method: {}".format(http_method)) if http_method in ['patch', 'put'] and not (json_payload or file_payload): raise ValueError("Non-empty payload is required for http method: {}".format(http_method)) url = 'https://{}{}'.format(login_server, path) headers = get_authorization_header(username, password) for i in range(0, retry_times): errorMessage = None try: if file_payload: with open(file_payload, 'rb') as data_payload: response = requests.request( method=http_method, url=url, headers=headers, params=params, data=data_payload, verify=(not should_disable_connection_verify()) ) else: response = requests.request( method=http_method, url=url, headers=headers, params=params, json=json_payload, verify=(not should_disable_connection_verify()) ) log_registry_response(response) if response.status_code == 200: result = response.json()[result_index] if result_index else response.json() next_link = response.headers['link'] if 'link' in response.headers else None return result, next_link if response.status_code == 201 or response.status_code == 202: result = None try: result = response.json()[result_index] if result_index else response.json() except ValueError as e: logger.debug('Response is empty or is not a valid json. Exception: %s', str(e)) return result, None if response.status_code == 204: return None, None if response.status_code == 401: raise RegistryException( parse_error_message('Authentication required.', response), response.status_code) if response.status_code == 404: raise RegistryException( parse_error_message('The requested data does not exist.', response), response.status_code) if response.status_code == 405: raise RegistryException( parse_error_message('This operation is not supported.', response), response.status_code) if response.status_code == 409: raise RegistryException( parse_error_message('Failed to request data due to a conflict.', response), response.status_code) raise Exception(parse_error_message('Could not {} the requested data.'.format(http_method), response)) except CLIError: raise except Exception as e: # pylint: disable=broad-except errorMessage = str(e) logger.debug('Retrying %s with exception %s', i + 1, errorMessage) time.sleep(retry_interval) raise CLIError(errorMessage) def parse_error_message(error_message, response): import json try: server_message = json.loads(response.text)['errors'][0]['message'] error_message = 'Error: {}'.format(server_message) if server_message else error_message except (ValueError, KeyError, TypeError, IndexError): pass if not error_message.endswith('.'): error_message = '{}.'.format(error_message) try: correlation_id = response.headers['x-ms-correlation-request-id'] return '{} Correlation ID: {}.'.format(error_message, correlation_id) except (KeyError, TypeError, AttributeError): return error_message class RegistryException(CLIError): def __init__(self, message, status_code): super(RegistryException, self).__init__(message) self.status_code = status_code class RegistryResponse(object): # pylint: disable=too-few-public-methods def __init__(self, request, internal_response): self.request = request self.internal_response = internal_response self.status_code = internal_response.status_code self.headers = internal_response.headers self.encoding = internal_response.encoding self.reason = internal_response.reason self.content = internal_response.content def text(self): return self.content.decode(self.encoding or "utf-8")
en
0.759035
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # catalog only has * as permission, even for a read operation Obtains refresh and access tokens for an AAD-enabled registry. :param str login_server: The registry login server URL to log in to :param bool only_refresh_token: Whether to ask for only refresh token, or for both refresh and access tokens :param str repository: Repository for which the access token is requested :param str artifact_repository: Artifact repository for which the access token is requested :param str permission: The requested permission on the repository, '*' or 'pull' # pylint: disable=too-many-statements Try to get AAD authorization tokens or admin user credentials. :param str registry_name: The name of container registry :param str tenant_suffix: The registry login server tenant suffix :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry :param bool only_refresh_token: Whether to ask for only refresh token, or for both refresh and access tokens :param str repository: Repository for which the access token is requested :param str artifact_repository: Artifact repository for which the access token is requested :param str permission: The requested permission on the repository, '*' or 'pull' # Raise an error if password is specified but username isn't # Try to use the pre-defined login server suffix to construct login server from registry name. # Validate the login server is reachable #connectivity_forbidden_error") # pylint: disable=line-too-long # 1. if username was specified, verify that password was also specified # 2. if we don't yet have credentials, attempt to get a refresh token # 3. if we still don't have credentials, attempt to get the admin credentials (if enabled) # 4. if we still don't have credentials, prompt the user Try to get AAD authorization tokens or admin user credentials to log into a registry. :param str registry_name: The name of container registry :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry Try to get AAD authorization tokens or admin user credentials to access a registry. :param str registry_name: The name of container registry :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry :param str repository: Repository for which the access token is requested :param str artifact_repository: Artifact repository for which the access token is requested :param str permission: The requested permission on the repository Log the HTTP request and response of a registry API call. :param Response response: The response object Get the Azure Container Registry login server suffix in the current cloud. # Ignore the error if the suffix is not set, the caller should then try to get login server from server. Get the authorization header as Basic auth if username is provided, or Bearer auth otherwise :param str username: The username used to log into the container registry :param str password: The password used to log into the container registry # pylint: disable=broad-except # pylint: disable=too-few-public-methods
1.840435
2
src/main.py
glovguy/survey_cluster
0
6625815
<reponame>glovguy/survey_cluster import json from models.surveys import Surveys from models.clusters import KmeansClusters from cluster_diagram import generate_diagram from silouette_scores import find_best_clust_num data_raw = [ {'survey_text': 'The quick brown fox jumps over the lazy dog', 'surveyid': '1'}, {'survey_text': 'Some days require more coffee than others', 'surveyid': '2'}, {'survey_text': 'coffee makes the world go round', 'surveyid': '3'}, {'survey_text': 'Crazy like a fox', 'surveyid': '4'} ] infer_num_clusters = False num_clusters = 2 srvys = Surveys(data_raw) kmObject = KmeansClusters(srvys) kmObject.set_num_clusters(num_clusters) if infer_num_clusters else find_best_clust_num(kmObject, save_plot=True) generate_diagram(srvys, kmObject) print(json.dumps(kmObject.clusters_to_dict()))
import json from models.surveys import Surveys from models.clusters import KmeansClusters from cluster_diagram import generate_diagram from silouette_scores import find_best_clust_num data_raw = [ {'survey_text': 'The quick brown fox jumps over the lazy dog', 'surveyid': '1'}, {'survey_text': 'Some days require more coffee than others', 'surveyid': '2'}, {'survey_text': 'coffee makes the world go round', 'surveyid': '3'}, {'survey_text': 'Crazy like a fox', 'surveyid': '4'} ] infer_num_clusters = False num_clusters = 2 srvys = Surveys(data_raw) kmObject = KmeansClusters(srvys) kmObject.set_num_clusters(num_clusters) if infer_num_clusters else find_best_clust_num(kmObject, save_plot=True) generate_diagram(srvys, kmObject) print(json.dumps(kmObject.clusters_to_dict()))
none
1
2.570536
3
lccs_ws/views.py
brazil-data-cube/lccs-ws
2
6625816
<filename>lccs_ws/views.py # # This file is part of Land Cover Classification System Web Service. # Copyright (C) 2020-2021 INPE. # # Land Cover Classification System Web Service is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # """Views of Land Cover Classification System Web Service.""" from bdc_auth_client.decorators import oauth2 from flask import abort, current_app, jsonify, request, send_file from werkzeug.urls import url_encode from lccs_ws.forms import (ClassesMappingMetadataSchema, ClassesSchema, ClassificationSystemMetadataSchema, ClassMetadataForm, ClassMetadataSchema, StyleFormatsMetadataSchema, StyleFormatsSchema) from . import data from .config import Config from .utils import language BASE_URL = Config.LCCS_URL @current_app.before_request def before_request(): """Handle for before request processing.""" request.assets_kwargs = None if Config.BDC_LCCS_ARGS: assets_kwargs = {arg: request.args.get(arg) for arg in Config.BDC_LCCS_ARGS.split(",")} if "access_token" in request.args: assets_kwargs["access_token"] = request.args.get("access_token") assets_kwargs = "?" + url_encode(assets_kwargs) if url_encode(assets_kwargs) else "" request.assets_kwargs = assets_kwargs if Config.BDC_LCCS_ARGS_I18N: intern_kwargs = {arg: request.args.get(arg) for arg in Config.BDC_LCCS_ARGS_I18N.split(",")} if "language" in request.args: intern_kwargs["language"] = request.args.get("language") intern_kwargs = "&" + url_encode(intern_kwargs) if url_encode(intern_kwargs) else "" request.intern_kwargs = intern_kwargs @current_app.route("/", methods=["GET"]) @oauth2(required=False) def root(**kwargs): """URL Handler for Land User Cover Classification System through REST API.""" links = list() response = dict() links += [ { "href": f"{BASE_URL}/{request.assets_kwargs}{request.intern_kwargs}", "rel": "self", "type": "application/json", "title": "Link to this document" }, { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "classification_systems", "type": "application/json", "title": "Information about Classification Systems", }, { "href": f"{BASE_URL}/style_formats{request.assets_kwargs}", "rel": "style_formats", "type": "application/json", "title": "Information about Style Formats" } ] response["links"] = links response["application_name"] = "Land Cover Classification System Service" response["version"] = Config.BDC_LCCS_API_VERSION return response, 200 @current_app.route("/classification_systems", methods=["GET"]) @oauth2(required=True) @language() def get_classification_systems(**kwargs): """Retrieve the list of available classification systems in the service.""" classification_systems_list = data.get_classification_systems() for class_system in classification_systems_list: links = [ { "href": f"{BASE_URL}/classification_systems/{class_system['id']}{request.assets_kwargs}{request.intern_kwargs}", "rel": "classification_system", "type": "application/json", "title": "Link to Classification System", }, { "href": f"{BASE_URL}/classification_systems/{class_system['id']}/classes{request.assets_kwargs}{request.intern_kwargs}", "rel": "classes", "type": "application/json", "title": "Link to Classification System Classes", }, { "href": f"{BASE_URL}/classification_systems/{class_system['id']}/style_formats{request.assets_kwargs}", "rel": "style_formats", "type": "application/json", "title": "Link to Available Style Formats", }, { "href": f"{BASE_URL}/mappings/{class_system['id']}{request.assets_kwargs}", "rel": "mappings", "type": "application/json", "title": "Link to Classification Mappings", }, { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "self", "type": "application/json", "title": "Link to this document", }, ] class_system["links"] = links return jsonify(classification_systems_list), 200 @current_app.route("/classification_systems/<system_id_or_identifier>", methods=["GET"]) @language() @oauth2(required=True) def get_classification_system(system_id_or_identifier, **kwargs): """Retrieve information about the classification system. :param system_id_or_identifier: The id or identifier of a classification system """ classification_system = data.get_classification_system(system_id_or_identifier) if not classification_system: abort(404, "Classification System not found.") links = [ { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to this document", }, { "href": f"{BASE_URL}/classification_systems/{classification_system['id']}{request.assets_kwargs}{request.intern_kwargs}", "rel": "self", "type": "application/json", "title": "The classification_system", }, { "href": f"{BASE_URL}/classification_systems/{classification_system['id']}/classes{request.assets_kwargs}{request.intern_kwargs}", "rel": "classes", "type": "application/json", "title": "The classes related to this item", }, { "href": f"{BASE_URL}/classification_systems/{classification_system['id']}/style_formats{request.assets_kwargs}", "rel": "styles_formats", "type": "application/json", "title": "The styles formats related to this item", }, { "href": f"{BASE_URL}/mappings/{classification_system['id']}{request.assets_kwargs}", "rel": "mappings", "type": "application/json", "title": "The classification system mappings", }, { "href": f"{BASE_URL}/{request.assets_kwargs}{request.intern_kwargs}", "rel": "root", "type": "application/json", "title": "API landing page." }, ] classification_system["links"] = links return classification_system, 200 @current_app.route("/classification_systems/<system_id_or_identifier>/classes", methods=["GET"]) @oauth2(required=True) def classification_systems_classes(system_id_or_identifier, **kwargs): """Retrieve the classes of a classification system. :param system_id_or_identifier: The id or identifier of a classification system """ system_id, classes_list = data.get_classification_system_classes(system_id_or_identifier) links = [ { "href": f"{BASE_URL}/classification_systems/{system_id}/classes{request.assets_kwargs}{request.intern_kwargs}", "rel": "self", "type": "application/json", "title": f"Classes of the classification system {system_id}{request.assets_kwargs}", }, { "href": f"{BASE_URL}/classification_systems/{system_id}{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification system", }, { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification systems", }, { "href": f"{BASE_URL}/{request.assets_kwargs}{request.intern_kwargs}", "rel": "root", "type": "application/json", "title": "API landing page", }, ] if not len(classes_list) > 0: return jsonify(links) for system_classes in classes_list: system_classes["links"] = links system_classes["links"].append( { "href": f"{BASE_URL}/classification_systems/{system_id}/classes/{system_classes['id']}{request.assets_kwargs}{request.intern_kwargs}", "rel": "child", "type": "application/json", "title": "Classification System Class", } ) return jsonify(classes_list), 200 @current_app.route("/classification_systems/<system_id_or_identifier>/classes/<class_id_or_name>", methods=["GET"]) @oauth2(required=True) @language() def classification_systems_class(system_id_or_identifier, class_id_or_name, **kwargs): """Retrieve class information from a classification system. :param system_id_or_identifier: The id or identifier of a classification system :param class_id_or_name: identifier of a class """ system_id, class_info = data.get_classification_system_class(system_id_or_identifier, class_id_or_name) if not len(class_info) > 0: abort(404, f"Class not found.") links = [ { "href": f"{BASE_URL}/classification_systems/{system_id}/classes/{class_info['id']}{request.assets_kwargs}{request.intern_kwargs}", "rel": "self", "type": "application/json", "title": "Link to this document", }, { "href": f"{BASE_URL}/classification_systems/{system_id}/classes{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to this document", }, { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "classification_systems", "type": "application/json", "title": "Link to classification systems", }, { "href": f"{BASE_URL}/{request.assets_kwargs}{request.intern_kwargs}", "rel": "root", "type": "application/json", "title": "API landing page", }, ] class_info["links"] = links return class_info, 200 @current_app.route("/mappings/<system_id_or_identifier>", methods=["GET"]) @oauth2(required=True) @language() def get_mappings(system_id_or_identifier, **kwargs): """Retrieve available mappings for a classification system. :param system_id_or_identifier: The id or identifier of a classification system """ system_source, system_target = data.get_mappings(system_id_or_identifier) if not len(system_target) > 0: abort(404, f"Mappings not found.") links = list() links += [ { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification systems", }, { "href": f"{BASE_URL}/{request.assets_kwargs}{request.intern_kwargs}", "rel": "root", "type": "application/json", "title": "API landing page", }, ] for sys in system_target: links.append( { "href": f"{BASE_URL}/mappings/{system_source.id}/{sys.id}{request.assets_kwargs}", "rel": "child", "type": "application/json", "title": "Mapping", } ) return jsonify(links) @current_app.route("/mappings/<system_id_or_identifier_source>/<system_id_or_identifier_target>", methods=["GET"]) @oauth2(required=True) @language() def get_mapping(system_id_or_identifier_source, system_id_or_identifier_target, **kwargs): """Retrieve mapping. :param system_id_or_identifier_source: The id or identifier of source classification system :param system_id_or_identifier_target: The id or identifier of target classification system """ system_id_source, system_id_target, mappings = data.get_mapping(system_id_or_identifier_source, system_id_or_identifier_target) for mp in mappings: links = [ { "href": f"{BASE_URL}/classification_systems/{system_id_source}/classes/{mp['source_class_id']}{request.assets_kwargs}", "rel": "item", "type": "application/json", "title": "Link to source class", }, { "href": f"{BASE_URL}/classification_systems/{system_id_target}/classes/{mp['target_class_id']}{request.assets_kwargs}", "rel": "item", "type": "application/json", "title": "Link to target class", }, ] if mp["degree_of_similarity"] is not None: mp["degree_of_similarity"] = float(mp["degree_of_similarity"]) mp["links"] = links return jsonify(mappings) @current_app.route("/style_formats", methods=["GET"]) @oauth2(required=True) def get_styles_formats(**kwargs): """Retrieve available style formats in service.""" styles_formats = data.get_style_formats() for st_f in styles_formats: links = [ { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification systems", }, { "href": f"{BASE_URL}/{request.assets_kwargs}{request.intern_kwargs}", "rel": "root", "type": "application/json", "title": "API landing page", }, { "href": f"{BASE_URL}/style_formats/{st_f['id']}{request.assets_kwargs}", "rel": "items", "type": "application/json", "title": f"Link to style format {st_f['id']}" } ] st_f["links"] = links return jsonify(styles_formats) @current_app.route("/style_formats/<style_format_id_or_name>", methods=["GET"]) @oauth2(required=True) def get_style_format(style_format_id_or_name, **kwargs): """Retrieve information of a style formats. :param style_format_id_or_name: The id or name of a style format """ styles_format = data.get_style_format(style_format_id_or_name) if not len(styles_format) > 0: abort(404, f"Style Format not found.") links = [ { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "classification_systems", "type": "application/json", "title": "Link to classification systems", }, { "href": f"{BASE_URL}/{request.assets_kwargs}{request.intern_kwargs}", "rel": "root", "type": "application/json", "title": "API landing page", }, { "href": f"{BASE_URL}/style_formats/{styles_format['id']}{request.assets_kwargs}", "rel": "style_format", "type": "application/json", "title": "Link to classification systems", }, { "href": f"{BASE_URL}/style_formats/{request.assets_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification systems", }, ] styles_format["links"] = links return styles_format @current_app.route("/classification_systems/<system_id_or_identifier>/style_formats", methods=["GET"]) @oauth2(required=True) def get_style_formats_classification_system(system_id_or_identifier, **kwargs): """Retrieve available style formats for a classification system. :param system_id_or_identifier: The id or identifier of a source classification system """ system_id, style_formats_id = data.get_system_style_format(system_id_or_identifier) if not len(style_formats_id) > 0: abort(404, f"Style Formats not found.") links = list() links += [ { "href": f"{BASE_URL}/classification_systems/{system_id}/style_formats{request.assets_kwargs}", "rel": "self", "type": "application/json", "title": f"Available style formats for {system_id}{request.assets_kwargs}", }, { "href": f"{BASE_URL}/classification_systems/{system_id}{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification system", }, { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification systems", }, { "href": f"{BASE_URL}/{request.assets_kwargs}{request.intern_kwargs}", "rel": "root", "type": "application/json", "title": "API landing page", }, ] for style_id in style_formats_id: links.append( { "href": f"{BASE_URL}/classification_systems/{system_id}/styles/{style_id[0]}{request.assets_kwargs}", "rel": "style", "type": "application/json", "title": "Link to style", } ) return jsonify(links) @current_app.route("/classification_systems/<system_id_or_identifier>/styles/<style_format_id_or_name>", methods=["GET"]) @oauth2(required=True) def style_file(system_id_or_identifier, style_format_id_or_name, **kwargs): """Retrieve available styles. :param system_id_or_identifier: The id or identifier of a classification system :param style_format_id_or_name: The id or name of a style format """ file_name, file = data.get_classification_system_style(system_id_or_identifier=system_id_or_identifier, style_format_id_or_name=style_format_id_or_name) if not file: abort(404, f"Style File not found.") return send_file(file, mimetype='application/octet-stream', as_attachment=True, attachment_filename=file_name) @current_app.route("/classification_systems/search/<system_name>/<system_version>", methods=["GET"]) def classification_system_search(system_name, system_version): """Return identifier of a classification system. :param system_name: name of a classification system :param system_version: version of a classification system """ system = data.get_identifier_system(system_name, system_version) return system, 200 @current_app.route("/style_formats/search/<style_format_name>", methods=["GET"]) def style_format_search(style_format_name): """Return identifier of a style format. :param style_format_name: name of a style format """ style_format = data.get_identifier_style_format(style_format_name) return style_format, 200 @current_app.route('/classification_systems', defaults={'system_id_or_identifier': None}, methods=["POST"]) @current_app.route("/classification_systems/<system_id_or_identifier>", methods=["PUT", "DELETE"]) @oauth2(roles=[['admin', 'editor']]) @language() def edit_classification_system(system_id_or_identifier, **kwargs): """Create or edit a specific classification system. :param system_id_or_identifier: The id or identifier of a classification system """ if request.method == "POST": args = request.get_json() errors = ClassificationSystemMetadataSchema().validate(args) if errors: return abort(400, str(errors)) classification_system = data.create_classification_system(**args) return classification_system, 201 if request.method == "DELETE": data.delete_classification_system(system_id_or_identifier) return {'message': f'{system_id_or_identifier} deleted'}, 204 if request.method == "PUT": args = request.get_json() errors = ClassificationSystemMetadataSchema().validate(args, partial=True) if errors: return abort(400, str(errors)) classification_system = data.update_classification_system(system_id_or_identifier, args) return classification_system, 200 @current_app.route("/classification_systems/<system_id_or_identifier>/classes", methods=["POST", "DELETE"]) @oauth2(roles=["admin"]) @language() def create_delete_classes(system_id_or_identifier, **kwargs): """Create classes for a classification system. :param system_id_or_identifier: The id or identifier of a classification system """ if request.method == "DELETE": data.delete_classes(system_id_or_identifier) return {'message': f'Classes of {system_id_or_identifier} deleted'}, 204 if request.method == "POST": args = request.get_json() errors = ClassMetadataForm().validate(args) if errors: return abort(400, str(errors)) classes = data.insert_classes(system_id_or_identifier=system_id_or_identifier, classes_files_json=args['classes']) result = ClassesSchema(exclude=['classification_system_id']).dump(classes, many=True) return jsonify(result), 201 @current_app.route("/classification_systems/<system_id_or_identifier>/classes/<class_id_or_name>", methods=["PUT", "DELETE"]) @oauth2(roles=["admin"]) @language() def edit_class(system_id_or_identifier, class_id_or_name, **kwargs): """Delete class of a specific classification system. :param system_id_or_identifier: The id or identifier of a classification system :param class_id_or_name: The id or identifier of a class """ if request.method == "DELETE": data.delete_class(system_id_or_identifier, class_id_or_name) return {'message': f'{class_id_or_name} deleted'}, 204 if request.method == "PUT": args = request.get_json() errors = ClassMetadataSchema().validate(args, partial=True) if errors: return abort(400, str(errors)) system_class = data.update_class(system_id_or_identifier, class_id_or_name, args) return system_class, 200 @current_app.route("/mappings/<system_id_or_identifier_source>/<system_id_or_identifier_target>", methods=["POST", "PUT", "DELETE"]) @oauth2(roles=['admin']) def edit_mapping(system_id_or_identifier_source, system_id_or_identifier_target, **kwargs): """Create or edit mappings in service. :param system_id_or_identifier_source: The id or identifier of a source classification system :param system_id_or_identifier_target: The id or identifier of a target classification system """ if request.method == "POST": args = request.get_json() errors = ClassesMappingMetadataSchema(many=True).validate(args) if errors: return abort(400, str(errors)) mappings = data.insert_mappings(system_id_or_identifier_source, system_id_or_identifier_target, args) return jsonify(mappings), 201 if request.method == "DELETE": data.delete_mappings(system_id_or_identifier_source, system_id_or_identifier_target) return {'message': 'Mapping delete!'}, 204 if request.method == "PUT": args = request.get_json() errors = ClassesMappingMetadataSchema().validate(args) if errors: return abort(400, str(errors)) mappings = data.update_mapping(system_id_or_identifier_source, system_id_or_identifier_target, **args) return mappings, 200 @current_app.route("/classification_systems/<system_id_or_identifier>/styles", defaults={'style_format_id_or_name': None}, methods=["POST"]) @current_app.route("/classification_systems/<system_id_or_identifier>/styles/<style_format_id_or_name>", methods=["PUT", "DELETE"]) @oauth2(roles=['admin']) def edit_styles(system_id_or_identifier, style_format_id_or_name, **kwargs): """Create or edit styles. :param system_id_or_identifier: The id or identifier of a specific classification system :param style_format_id_or_name: The id or identifier of a specific style format. """ if request.method == "POST": if 'style_format' not in request.form: return abort(404, "Invalid parameter.") style_format = request.form.get('style_format') if 'style' not in request.files: return abort(404, "Invalid parameter.") file = request.files['style'] system_id, format_id = data.insert_file(style_format_id_or_name=style_format, system_id_or_identifier=system_id_or_identifier, file=file) links = list() links += [ { "href": f"{BASE_URL}/classification_systems/{system_id}/styles/{format_id}{request.assets_kwargs}", "rel": "style", "type": "application/json", "title": "style", }, { "href": f"{BASE_URL}/classification_systems/{system_id}/style_formats{request.assets_kwargs}", "rel": "self", "type": "application/json", "title": f"Styles of the classification system {system_id}{request.assets_kwargs}", }, { "href": f"{BASE_URL}/classification_systems/{system_id}{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification system", }, { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification systems", }, { "href": f"{BASE_URL}/{request.assets_kwargs}{request.intern_kwargs}", "rel": "root", "type": "application/json", "title": "API landing page", }, ] return jsonify(links) if request.method == "PUT": if 'style' not in request.files: return abort(500, "Style File not found!") file = request.files['style'] system_id, style_format_id = data.update_file(style_format_id_or_name=style_format_id_or_name, system_id_or_identifier=system_id_or_identifier, file=file) links = list() links += [ { "href": f"{BASE_URL}/classification_systems/{system_id}/styles/{style_format_id}{request.assets_kwargs}", "rel": "style", "type": "application/json", "title": "style", }, { "href": f"{BASE_URL}/classification_systems/{system_id}/style_formats{request.assets_kwargs}", "rel": "self", "type": "application/json", "title": f"Styles of the classification system {system_id}{request.assets_kwargs}", }, { "href": f"{BASE_URL}/classification_systems/{system_id}{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification system", }, { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification systems", }, { "href": f"{BASE_URL}/{request.assets_kwargs}{request.intern_kwargs}", "rel": "root", "type": "application/json", "title": "API landing page", }, ] return jsonify(links) if request.method == "DELETE": data.delete_file(style_format_id_or_name, system_id_or_identifier) return {'message': 'deleted!'}, 204 @current_app.route("/style_formats", defaults={'style_format_id_or_name': None}, methods=["POST"]) @current_app.route("/style_formats/<style_format_id_or_name>", methods=["PUT", "DELETE"]) @oauth2(roles=['admin']) def edit_style_formats(style_format_id_or_name, **kwargs): """Create or edit styles formats. :param style_format_id_or_name: The id or name of a specific style format """ if request.method == "POST": args = request.get_json() errors = StyleFormatsSchema().validate(args) if errors: return abort(400, str(errors)) style_format = data.create_style_format(**args) return style_format, 201 if request.method == "DELETE": data.delete_style_format(style_format_id_or_name) return {'message': 'deleted'}, 204 if request.method == "PUT": args = request.get_json() errors = StyleFormatsMetadataSchema().validate(args) if errors: return abort(400, str(errors)) style_format = data.update_style_format(style_format_id_or_name, **args) return style_format, 200
<filename>lccs_ws/views.py # # This file is part of Land Cover Classification System Web Service. # Copyright (C) 2020-2021 INPE. # # Land Cover Classification System Web Service is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # """Views of Land Cover Classification System Web Service.""" from bdc_auth_client.decorators import oauth2 from flask import abort, current_app, jsonify, request, send_file from werkzeug.urls import url_encode from lccs_ws.forms import (ClassesMappingMetadataSchema, ClassesSchema, ClassificationSystemMetadataSchema, ClassMetadataForm, ClassMetadataSchema, StyleFormatsMetadataSchema, StyleFormatsSchema) from . import data from .config import Config from .utils import language BASE_URL = Config.LCCS_URL @current_app.before_request def before_request(): """Handle for before request processing.""" request.assets_kwargs = None if Config.BDC_LCCS_ARGS: assets_kwargs = {arg: request.args.get(arg) for arg in Config.BDC_LCCS_ARGS.split(",")} if "access_token" in request.args: assets_kwargs["access_token"] = request.args.get("access_token") assets_kwargs = "?" + url_encode(assets_kwargs) if url_encode(assets_kwargs) else "" request.assets_kwargs = assets_kwargs if Config.BDC_LCCS_ARGS_I18N: intern_kwargs = {arg: request.args.get(arg) for arg in Config.BDC_LCCS_ARGS_I18N.split(",")} if "language" in request.args: intern_kwargs["language"] = request.args.get("language") intern_kwargs = "&" + url_encode(intern_kwargs) if url_encode(intern_kwargs) else "" request.intern_kwargs = intern_kwargs @current_app.route("/", methods=["GET"]) @oauth2(required=False) def root(**kwargs): """URL Handler for Land User Cover Classification System through REST API.""" links = list() response = dict() links += [ { "href": f"{BASE_URL}/{request.assets_kwargs}{request.intern_kwargs}", "rel": "self", "type": "application/json", "title": "Link to this document" }, { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "classification_systems", "type": "application/json", "title": "Information about Classification Systems", }, { "href": f"{BASE_URL}/style_formats{request.assets_kwargs}", "rel": "style_formats", "type": "application/json", "title": "Information about Style Formats" } ] response["links"] = links response["application_name"] = "Land Cover Classification System Service" response["version"] = Config.BDC_LCCS_API_VERSION return response, 200 @current_app.route("/classification_systems", methods=["GET"]) @oauth2(required=True) @language() def get_classification_systems(**kwargs): """Retrieve the list of available classification systems in the service.""" classification_systems_list = data.get_classification_systems() for class_system in classification_systems_list: links = [ { "href": f"{BASE_URL}/classification_systems/{class_system['id']}{request.assets_kwargs}{request.intern_kwargs}", "rel": "classification_system", "type": "application/json", "title": "Link to Classification System", }, { "href": f"{BASE_URL}/classification_systems/{class_system['id']}/classes{request.assets_kwargs}{request.intern_kwargs}", "rel": "classes", "type": "application/json", "title": "Link to Classification System Classes", }, { "href": f"{BASE_URL}/classification_systems/{class_system['id']}/style_formats{request.assets_kwargs}", "rel": "style_formats", "type": "application/json", "title": "Link to Available Style Formats", }, { "href": f"{BASE_URL}/mappings/{class_system['id']}{request.assets_kwargs}", "rel": "mappings", "type": "application/json", "title": "Link to Classification Mappings", }, { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "self", "type": "application/json", "title": "Link to this document", }, ] class_system["links"] = links return jsonify(classification_systems_list), 200 @current_app.route("/classification_systems/<system_id_or_identifier>", methods=["GET"]) @language() @oauth2(required=True) def get_classification_system(system_id_or_identifier, **kwargs): """Retrieve information about the classification system. :param system_id_or_identifier: The id or identifier of a classification system """ classification_system = data.get_classification_system(system_id_or_identifier) if not classification_system: abort(404, "Classification System not found.") links = [ { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to this document", }, { "href": f"{BASE_URL}/classification_systems/{classification_system['id']}{request.assets_kwargs}{request.intern_kwargs}", "rel": "self", "type": "application/json", "title": "The classification_system", }, { "href": f"{BASE_URL}/classification_systems/{classification_system['id']}/classes{request.assets_kwargs}{request.intern_kwargs}", "rel": "classes", "type": "application/json", "title": "The classes related to this item", }, { "href": f"{BASE_URL}/classification_systems/{classification_system['id']}/style_formats{request.assets_kwargs}", "rel": "styles_formats", "type": "application/json", "title": "The styles formats related to this item", }, { "href": f"{BASE_URL}/mappings/{classification_system['id']}{request.assets_kwargs}", "rel": "mappings", "type": "application/json", "title": "The classification system mappings", }, { "href": f"{BASE_URL}/{request.assets_kwargs}{request.intern_kwargs}", "rel": "root", "type": "application/json", "title": "API landing page." }, ] classification_system["links"] = links return classification_system, 200 @current_app.route("/classification_systems/<system_id_or_identifier>/classes", methods=["GET"]) @oauth2(required=True) def classification_systems_classes(system_id_or_identifier, **kwargs): """Retrieve the classes of a classification system. :param system_id_or_identifier: The id or identifier of a classification system """ system_id, classes_list = data.get_classification_system_classes(system_id_or_identifier) links = [ { "href": f"{BASE_URL}/classification_systems/{system_id}/classes{request.assets_kwargs}{request.intern_kwargs}", "rel": "self", "type": "application/json", "title": f"Classes of the classification system {system_id}{request.assets_kwargs}", }, { "href": f"{BASE_URL}/classification_systems/{system_id}{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification system", }, { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification systems", }, { "href": f"{BASE_URL}/{request.assets_kwargs}{request.intern_kwargs}", "rel": "root", "type": "application/json", "title": "API landing page", }, ] if not len(classes_list) > 0: return jsonify(links) for system_classes in classes_list: system_classes["links"] = links system_classes["links"].append( { "href": f"{BASE_URL}/classification_systems/{system_id}/classes/{system_classes['id']}{request.assets_kwargs}{request.intern_kwargs}", "rel": "child", "type": "application/json", "title": "Classification System Class", } ) return jsonify(classes_list), 200 @current_app.route("/classification_systems/<system_id_or_identifier>/classes/<class_id_or_name>", methods=["GET"]) @oauth2(required=True) @language() def classification_systems_class(system_id_or_identifier, class_id_or_name, **kwargs): """Retrieve class information from a classification system. :param system_id_or_identifier: The id or identifier of a classification system :param class_id_or_name: identifier of a class """ system_id, class_info = data.get_classification_system_class(system_id_or_identifier, class_id_or_name) if not len(class_info) > 0: abort(404, f"Class not found.") links = [ { "href": f"{BASE_URL}/classification_systems/{system_id}/classes/{class_info['id']}{request.assets_kwargs}{request.intern_kwargs}", "rel": "self", "type": "application/json", "title": "Link to this document", }, { "href": f"{BASE_URL}/classification_systems/{system_id}/classes{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to this document", }, { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "classification_systems", "type": "application/json", "title": "Link to classification systems", }, { "href": f"{BASE_URL}/{request.assets_kwargs}{request.intern_kwargs}", "rel": "root", "type": "application/json", "title": "API landing page", }, ] class_info["links"] = links return class_info, 200 @current_app.route("/mappings/<system_id_or_identifier>", methods=["GET"]) @oauth2(required=True) @language() def get_mappings(system_id_or_identifier, **kwargs): """Retrieve available mappings for a classification system. :param system_id_or_identifier: The id or identifier of a classification system """ system_source, system_target = data.get_mappings(system_id_or_identifier) if not len(system_target) > 0: abort(404, f"Mappings not found.") links = list() links += [ { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification systems", }, { "href": f"{BASE_URL}/{request.assets_kwargs}{request.intern_kwargs}", "rel": "root", "type": "application/json", "title": "API landing page", }, ] for sys in system_target: links.append( { "href": f"{BASE_URL}/mappings/{system_source.id}/{sys.id}{request.assets_kwargs}", "rel": "child", "type": "application/json", "title": "Mapping", } ) return jsonify(links) @current_app.route("/mappings/<system_id_or_identifier_source>/<system_id_or_identifier_target>", methods=["GET"]) @oauth2(required=True) @language() def get_mapping(system_id_or_identifier_source, system_id_or_identifier_target, **kwargs): """Retrieve mapping. :param system_id_or_identifier_source: The id or identifier of source classification system :param system_id_or_identifier_target: The id or identifier of target classification system """ system_id_source, system_id_target, mappings = data.get_mapping(system_id_or_identifier_source, system_id_or_identifier_target) for mp in mappings: links = [ { "href": f"{BASE_URL}/classification_systems/{system_id_source}/classes/{mp['source_class_id']}{request.assets_kwargs}", "rel": "item", "type": "application/json", "title": "Link to source class", }, { "href": f"{BASE_URL}/classification_systems/{system_id_target}/classes/{mp['target_class_id']}{request.assets_kwargs}", "rel": "item", "type": "application/json", "title": "Link to target class", }, ] if mp["degree_of_similarity"] is not None: mp["degree_of_similarity"] = float(mp["degree_of_similarity"]) mp["links"] = links return jsonify(mappings) @current_app.route("/style_formats", methods=["GET"]) @oauth2(required=True) def get_styles_formats(**kwargs): """Retrieve available style formats in service.""" styles_formats = data.get_style_formats() for st_f in styles_formats: links = [ { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification systems", }, { "href": f"{BASE_URL}/{request.assets_kwargs}{request.intern_kwargs}", "rel": "root", "type": "application/json", "title": "API landing page", }, { "href": f"{BASE_URL}/style_formats/{st_f['id']}{request.assets_kwargs}", "rel": "items", "type": "application/json", "title": f"Link to style format {st_f['id']}" } ] st_f["links"] = links return jsonify(styles_formats) @current_app.route("/style_formats/<style_format_id_or_name>", methods=["GET"]) @oauth2(required=True) def get_style_format(style_format_id_or_name, **kwargs): """Retrieve information of a style formats. :param style_format_id_or_name: The id or name of a style format """ styles_format = data.get_style_format(style_format_id_or_name) if not len(styles_format) > 0: abort(404, f"Style Format not found.") links = [ { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "classification_systems", "type": "application/json", "title": "Link to classification systems", }, { "href": f"{BASE_URL}/{request.assets_kwargs}{request.intern_kwargs}", "rel": "root", "type": "application/json", "title": "API landing page", }, { "href": f"{BASE_URL}/style_formats/{styles_format['id']}{request.assets_kwargs}", "rel": "style_format", "type": "application/json", "title": "Link to classification systems", }, { "href": f"{BASE_URL}/style_formats/{request.assets_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification systems", }, ] styles_format["links"] = links return styles_format @current_app.route("/classification_systems/<system_id_or_identifier>/style_formats", methods=["GET"]) @oauth2(required=True) def get_style_formats_classification_system(system_id_or_identifier, **kwargs): """Retrieve available style formats for a classification system. :param system_id_or_identifier: The id or identifier of a source classification system """ system_id, style_formats_id = data.get_system_style_format(system_id_or_identifier) if not len(style_formats_id) > 0: abort(404, f"Style Formats not found.") links = list() links += [ { "href": f"{BASE_URL}/classification_systems/{system_id}/style_formats{request.assets_kwargs}", "rel": "self", "type": "application/json", "title": f"Available style formats for {system_id}{request.assets_kwargs}", }, { "href": f"{BASE_URL}/classification_systems/{system_id}{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification system", }, { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification systems", }, { "href": f"{BASE_URL}/{request.assets_kwargs}{request.intern_kwargs}", "rel": "root", "type": "application/json", "title": "API landing page", }, ] for style_id in style_formats_id: links.append( { "href": f"{BASE_URL}/classification_systems/{system_id}/styles/{style_id[0]}{request.assets_kwargs}", "rel": "style", "type": "application/json", "title": "Link to style", } ) return jsonify(links) @current_app.route("/classification_systems/<system_id_or_identifier>/styles/<style_format_id_or_name>", methods=["GET"]) @oauth2(required=True) def style_file(system_id_or_identifier, style_format_id_or_name, **kwargs): """Retrieve available styles. :param system_id_or_identifier: The id or identifier of a classification system :param style_format_id_or_name: The id or name of a style format """ file_name, file = data.get_classification_system_style(system_id_or_identifier=system_id_or_identifier, style_format_id_or_name=style_format_id_or_name) if not file: abort(404, f"Style File not found.") return send_file(file, mimetype='application/octet-stream', as_attachment=True, attachment_filename=file_name) @current_app.route("/classification_systems/search/<system_name>/<system_version>", methods=["GET"]) def classification_system_search(system_name, system_version): """Return identifier of a classification system. :param system_name: name of a classification system :param system_version: version of a classification system """ system = data.get_identifier_system(system_name, system_version) return system, 200 @current_app.route("/style_formats/search/<style_format_name>", methods=["GET"]) def style_format_search(style_format_name): """Return identifier of a style format. :param style_format_name: name of a style format """ style_format = data.get_identifier_style_format(style_format_name) return style_format, 200 @current_app.route('/classification_systems', defaults={'system_id_or_identifier': None}, methods=["POST"]) @current_app.route("/classification_systems/<system_id_or_identifier>", methods=["PUT", "DELETE"]) @oauth2(roles=[['admin', 'editor']]) @language() def edit_classification_system(system_id_or_identifier, **kwargs): """Create or edit a specific classification system. :param system_id_or_identifier: The id or identifier of a classification system """ if request.method == "POST": args = request.get_json() errors = ClassificationSystemMetadataSchema().validate(args) if errors: return abort(400, str(errors)) classification_system = data.create_classification_system(**args) return classification_system, 201 if request.method == "DELETE": data.delete_classification_system(system_id_or_identifier) return {'message': f'{system_id_or_identifier} deleted'}, 204 if request.method == "PUT": args = request.get_json() errors = ClassificationSystemMetadataSchema().validate(args, partial=True) if errors: return abort(400, str(errors)) classification_system = data.update_classification_system(system_id_or_identifier, args) return classification_system, 200 @current_app.route("/classification_systems/<system_id_or_identifier>/classes", methods=["POST", "DELETE"]) @oauth2(roles=["admin"]) @language() def create_delete_classes(system_id_or_identifier, **kwargs): """Create classes for a classification system. :param system_id_or_identifier: The id or identifier of a classification system """ if request.method == "DELETE": data.delete_classes(system_id_or_identifier) return {'message': f'Classes of {system_id_or_identifier} deleted'}, 204 if request.method == "POST": args = request.get_json() errors = ClassMetadataForm().validate(args) if errors: return abort(400, str(errors)) classes = data.insert_classes(system_id_or_identifier=system_id_or_identifier, classes_files_json=args['classes']) result = ClassesSchema(exclude=['classification_system_id']).dump(classes, many=True) return jsonify(result), 201 @current_app.route("/classification_systems/<system_id_or_identifier>/classes/<class_id_or_name>", methods=["PUT", "DELETE"]) @oauth2(roles=["admin"]) @language() def edit_class(system_id_or_identifier, class_id_or_name, **kwargs): """Delete class of a specific classification system. :param system_id_or_identifier: The id or identifier of a classification system :param class_id_or_name: The id or identifier of a class """ if request.method == "DELETE": data.delete_class(system_id_or_identifier, class_id_or_name) return {'message': f'{class_id_or_name} deleted'}, 204 if request.method == "PUT": args = request.get_json() errors = ClassMetadataSchema().validate(args, partial=True) if errors: return abort(400, str(errors)) system_class = data.update_class(system_id_or_identifier, class_id_or_name, args) return system_class, 200 @current_app.route("/mappings/<system_id_or_identifier_source>/<system_id_or_identifier_target>", methods=["POST", "PUT", "DELETE"]) @oauth2(roles=['admin']) def edit_mapping(system_id_or_identifier_source, system_id_or_identifier_target, **kwargs): """Create or edit mappings in service. :param system_id_or_identifier_source: The id or identifier of a source classification system :param system_id_or_identifier_target: The id or identifier of a target classification system """ if request.method == "POST": args = request.get_json() errors = ClassesMappingMetadataSchema(many=True).validate(args) if errors: return abort(400, str(errors)) mappings = data.insert_mappings(system_id_or_identifier_source, system_id_or_identifier_target, args) return jsonify(mappings), 201 if request.method == "DELETE": data.delete_mappings(system_id_or_identifier_source, system_id_or_identifier_target) return {'message': 'Mapping delete!'}, 204 if request.method == "PUT": args = request.get_json() errors = ClassesMappingMetadataSchema().validate(args) if errors: return abort(400, str(errors)) mappings = data.update_mapping(system_id_or_identifier_source, system_id_or_identifier_target, **args) return mappings, 200 @current_app.route("/classification_systems/<system_id_or_identifier>/styles", defaults={'style_format_id_or_name': None}, methods=["POST"]) @current_app.route("/classification_systems/<system_id_or_identifier>/styles/<style_format_id_or_name>", methods=["PUT", "DELETE"]) @oauth2(roles=['admin']) def edit_styles(system_id_or_identifier, style_format_id_or_name, **kwargs): """Create or edit styles. :param system_id_or_identifier: The id or identifier of a specific classification system :param style_format_id_or_name: The id or identifier of a specific style format. """ if request.method == "POST": if 'style_format' not in request.form: return abort(404, "Invalid parameter.") style_format = request.form.get('style_format') if 'style' not in request.files: return abort(404, "Invalid parameter.") file = request.files['style'] system_id, format_id = data.insert_file(style_format_id_or_name=style_format, system_id_or_identifier=system_id_or_identifier, file=file) links = list() links += [ { "href": f"{BASE_URL}/classification_systems/{system_id}/styles/{format_id}{request.assets_kwargs}", "rel": "style", "type": "application/json", "title": "style", }, { "href": f"{BASE_URL}/classification_systems/{system_id}/style_formats{request.assets_kwargs}", "rel": "self", "type": "application/json", "title": f"Styles of the classification system {system_id}{request.assets_kwargs}", }, { "href": f"{BASE_URL}/classification_systems/{system_id}{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification system", }, { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification systems", }, { "href": f"{BASE_URL}/{request.assets_kwargs}{request.intern_kwargs}", "rel": "root", "type": "application/json", "title": "API landing page", }, ] return jsonify(links) if request.method == "PUT": if 'style' not in request.files: return abort(500, "Style File not found!") file = request.files['style'] system_id, style_format_id = data.update_file(style_format_id_or_name=style_format_id_or_name, system_id_or_identifier=system_id_or_identifier, file=file) links = list() links += [ { "href": f"{BASE_URL}/classification_systems/{system_id}/styles/{style_format_id}{request.assets_kwargs}", "rel": "style", "type": "application/json", "title": "style", }, { "href": f"{BASE_URL}/classification_systems/{system_id}/style_formats{request.assets_kwargs}", "rel": "self", "type": "application/json", "title": f"Styles of the classification system {system_id}{request.assets_kwargs}", }, { "href": f"{BASE_URL}/classification_systems/{system_id}{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification system", }, { "href": f"{BASE_URL}/classification_systems{request.assets_kwargs}{request.intern_kwargs}", "rel": "parent", "type": "application/json", "title": "Link to classification systems", }, { "href": f"{BASE_URL}/{request.assets_kwargs}{request.intern_kwargs}", "rel": "root", "type": "application/json", "title": "API landing page", }, ] return jsonify(links) if request.method == "DELETE": data.delete_file(style_format_id_or_name, system_id_or_identifier) return {'message': 'deleted!'}, 204 @current_app.route("/style_formats", defaults={'style_format_id_or_name': None}, methods=["POST"]) @current_app.route("/style_formats/<style_format_id_or_name>", methods=["PUT", "DELETE"]) @oauth2(roles=['admin']) def edit_style_formats(style_format_id_or_name, **kwargs): """Create or edit styles formats. :param style_format_id_or_name: The id or name of a specific style format """ if request.method == "POST": args = request.get_json() errors = StyleFormatsSchema().validate(args) if errors: return abort(400, str(errors)) style_format = data.create_style_format(**args) return style_format, 201 if request.method == "DELETE": data.delete_style_format(style_format_id_or_name) return {'message': 'deleted'}, 204 if request.method == "PUT": args = request.get_json() errors = StyleFormatsMetadataSchema().validate(args) if errors: return abort(400, str(errors)) style_format = data.update_style_format(style_format_id_or_name, **args) return style_format, 200
en
0.549465
# # This file is part of Land Cover Classification System Web Service. # Copyright (C) 2020-2021 INPE. # # Land Cover Classification System Web Service is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # Views of Land Cover Classification System Web Service. Handle for before request processing. URL Handler for Land User Cover Classification System through REST API. Retrieve the list of available classification systems in the service. Retrieve information about the classification system. :param system_id_or_identifier: The id or identifier of a classification system Retrieve the classes of a classification system. :param system_id_or_identifier: The id or identifier of a classification system Retrieve class information from a classification system. :param system_id_or_identifier: The id or identifier of a classification system :param class_id_or_name: identifier of a class Retrieve available mappings for a classification system. :param system_id_or_identifier: The id or identifier of a classification system Retrieve mapping. :param system_id_or_identifier_source: The id or identifier of source classification system :param system_id_or_identifier_target: The id or identifier of target classification system Retrieve available style formats in service. Retrieve information of a style formats. :param style_format_id_or_name: The id or name of a style format Retrieve available style formats for a classification system. :param system_id_or_identifier: The id or identifier of a source classification system Retrieve available styles. :param system_id_or_identifier: The id or identifier of a classification system :param style_format_id_or_name: The id or name of a style format Return identifier of a classification system. :param system_name: name of a classification system :param system_version: version of a classification system Return identifier of a style format. :param style_format_name: name of a style format Create or edit a specific classification system. :param system_id_or_identifier: The id or identifier of a classification system Create classes for a classification system. :param system_id_or_identifier: The id or identifier of a classification system Delete class of a specific classification system. :param system_id_or_identifier: The id or identifier of a classification system :param class_id_or_name: The id or identifier of a class Create or edit mappings in service. :param system_id_or_identifier_source: The id or identifier of a source classification system :param system_id_or_identifier_target: The id or identifier of a target classification system Create or edit styles. :param system_id_or_identifier: The id or identifier of a specific classification system :param style_format_id_or_name: The id or identifier of a specific style format. Create or edit styles formats. :param style_format_id_or_name: The id or name of a specific style format
2.236409
2
multirun/deps.bzl
shiwano/bazel-tools
118
6625817
<reponame>shiwano/bazel-tools load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") def multirun_dependencies(): maybe( http_archive, name = "bazel_skylib", urls = [ "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.0.2/bazel-skylib-1.0.2.tar.gz", "https://github.com/bazelbuild/bazel-skylib/releases/download/1.0.2/bazel-skylib-1.0.2.tar.gz", ], sha256 = "97e70364e9249702246c0e9444bccdc4b847bed1eb03c5a3ece4f83dfe6abc44", )
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") def multirun_dependencies(): maybe( http_archive, name = "bazel_skylib", urls = [ "https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.0.2/bazel-skylib-1.0.2.tar.gz", "https://github.com/bazelbuild/bazel-skylib/releases/download/1.0.2/bazel-skylib-1.0.2.tar.gz", ], sha256 = "97e70364e9249702246c0e9444bccdc4b847bed1eb03c5a3ece4f83dfe6abc44", )
none
1
1.486008
1
plugins/extract/_base.py
aaman123/faceswap
2
6625818
<gh_stars>1-10 #!/usr/bin/env python3 """ Base class for Faceswap :mod:`~plugins.extract.detect`, :mod:`~plugins.extract.align` and :mod:`~plugins.extract.mask` Plugins """ import logging import os import sys from tensorflow.python import errors_impl as tf_errors # pylint:disable=no-name-in-module from lib.multithreading import MultiThread from lib.queue_manager import queue_manager from lib.utils import GetModel, FaceswapError from ._config import Config from .pipeline import ExtractMedia logger = logging.getLogger(__name__) # pylint: disable=invalid-name # TODO CPU mode # TODO Run with warnings mode def _get_config(plugin_name, configfile=None): """ Return the configuration for the requested model Parameters ---------- plugin_name: str The module name of the child plugin. configfile: str, optional Path to a :file:`./config/<plugin_type>.ini` file for this plugin. Default: use system configuration. Returns ------- config_dict, dict A dictionary of configuration items from the configuration file """ return Config(plugin_name, configfile=configfile).config_dict class Extractor(): """ Extractor Plugin Object All ``_base`` classes for Aligners, Detectors and Maskers inherit from this class. This class sets up a pipeline for working with ML plugins. Plugins are split into 3 threads, to utilize Numpy and CV2s parallel processing, as well as allow the predict function of the model to sit in a dedicated thread. A plugin is expected to have 3 core functions, each in their own thread: - :func:`process_input()` - Prepare the data for feeding into a model - :func:`predict` - Feed the data through the model - :func:`process_output()` - Perform any data post-processing Parameters ---------- git_model_id: int The second digit in the github tag that identifies this model. See https://github.com/deepfakes-models/faceswap-models for more information model_filename: str The name of the model file to be loaded exclude_gpus: list, optional A list of indices correlating to connected GPUs that Tensorflow should not use. Pass ``None`` to not exclude any GPUs. Default: ``None`` configfile: str, optional Path to a custom configuration ``ini`` file. Default: Use system configfile instance: int, optional If this plugin is being executed multiple times (i.e. multiple pipelines have been launched), the instance of the plugin must be passed in for naming convention reasons. Default: 0 The following attributes should be set in the plugin's :func:`__init__` method after initializing the parent. Attributes ---------- name: str Name of this plugin. Used for display purposes. input_size: int The input size to the model in pixels across one edge. The input size should always be square. color_format: str Color format for model. Must be ``'BGR'``, ``'RGB'`` or ``'GRAY'``. Defaults to ``'BGR'`` if not explicitly set. vram: int Approximate VRAM used by the model at :attr:`input_size`. Used to calculate the :attr:`batchsize`. Be conservative to avoid OOM. vram_warnings: int Approximate VRAM used by the model at :attr:`input_size` that will still run, but generates warnings. Used to calculate the :attr:`batchsize`. Be conservative to avoid OOM. vram_per_batch: int Approximate additional VRAM used by the model for each additional batch. Used to calculate the :attr:`batchsize`. Be conservative to avoid OOM. See Also -------- plugins.extract.detect._base : Detector parent class for extraction plugins. plugins.extract.align._base : Aligner parent class for extraction plugins. plugins.extract.mask._base : Masker parent class for extraction plugins. plugins.extract.pipeline : The extract pipeline that configures and calls all plugins """ def __init__(self, git_model_id=None, model_filename=None, exclude_gpus=None, configfile=None, instance=0): logger.debug("Initializing %s: (git_model_id: %s, model_filename: %s, exclude_gpus: %s, " "configfile: %s, instance: %s, )", self.__class__.__name__, git_model_id, model_filename, exclude_gpus, configfile, instance) self._instance = instance self._exclude_gpus = exclude_gpus self.config = _get_config(".".join(self.__module__.split(".")[-2:]), configfile=configfile) """ dict: Config for this plugin, loaded from ``extract.ini`` configfile """ self.model_path = self._get_model(git_model_id, model_filename) """ str or list: Path to the model file(s) (if required). Multiple model files should be a list of strings """ # << SET THE FOLLOWING IN PLUGINS __init__ IF DIFFERENT FROM DEFAULT >> # self.name = None self.input_size = None self.color_format = "BGR" self.vram = None self.vram_warnings = None # Will run at this with warnings self.vram_per_batch = None # << THE FOLLOWING ARE SET IN self.initialize METHOD >> # self.queue_size = 1 """ int: Queue size for all internal queues. Set in :func:`initialize()` """ self.model = None """varies: The model for this plugin. Set in the plugin's :func:`init_model()` method """ # For detectors that support batching, this should be set to the calculated batch size # that the amount of available VRAM will support. self.batchsize = 1 """ int: Batchsize for feeding this model. The number of images the model should feed through at once. """ self._queues = dict() """ dict: in + out queues and internal queues for this plugin, """ self._threads = [] """ list: Internal threads for this plugin """ self._extract_media = dict() """ dict: The :class:`plugins.extract.pipeline.ExtractMedia` objects currently being processed. Stored at input for pairing back up on output of extractor process """ # << THE FOLLOWING PROTECTED ATTRIBUTES ARE SET IN PLUGIN TYPE _base.py >>> # self._plugin_type = None """ str: Plugin type. ``detect`` or ``align`` set in ``<plugin_type>._base`` """ logger.debug("Initialized _base %s", self.__class__.__name__) # <<< OVERIDABLE METHODS >>> # def init_model(self): """ **Override method** Override this method to execute the specific model initialization method """ raise NotImplementedError def process_input(self, batch): """ **Override method** Override this method for specific extractor pre-processing of image Parameters ---------- batch : dict Contains the batch that is currently being passed through the plugin process Notes ----- When preparing an input to the model a key ``feed`` must be added to the :attr:`batch` ``dict`` which contains this input. """ raise NotImplementedError def predict(self, batch): """ **Override method** Override this method for specific extractor model prediction function Parameters ---------- batch : dict Contains the batch that is currently being passed through the plugin process Notes ----- Input for :func:`predict` should have been set in :func:`process_input` with the addition of a ``feed`` key to the :attr:`batch` ``dict``. Output from the model should add the key ``prediction`` to the :attr:`batch` ``dict``. For Detect: the expected output for the ``prediction`` key of the :attr:`batch` dict should be a ``list`` of :attr:`batchsize` of detected face points. These points should be either a ``list``, ``tuple`` or ``numpy.ndarray`` with the first 4 items being the `left`, `top`, `right`, `bottom` points, in that order """ raise NotImplementedError def process_output(self, batch): """ **Override method** Override this method for specific extractor model post predict function Parameters ---------- batch : dict Contains the batch that is currently being passed through the plugin process Notes ----- For Align: The key ``landmarks`` must be returned in the :attr:`batch` ``dict`` from this method. This should be a ``list`` or ``numpy.ndarray`` of :attr:`batchsize` containing a ``list``, ``tuple`` or ``numpy.ndarray`` of `(x, y)` coordinates of the 68 point landmarks as calculated from the :attr:`model`. """ raise NotImplementedError def _predict(self, batch): """ **Override method** (at `<plugin_type>` level) This method should be overridden at the `<plugin_type>` level (IE. ``plugins.extract.detect._base`` or ``plugins.extract.align._base``) and should not be overridden within plugins themselves. It acts as a wrapper for the plugin's ``self.predict`` method and handles any predict processing that is consistent for all plugins within the `plugin_type` Parameters ---------- batch : dict Contains the batch that is currently being passed through the plugin process """ raise NotImplementedError def finalize(self, batch): """ **Override method** (at `<plugin_type>` level) This method should be overridden at the `<plugin_type>` level (IE. :mod:`plugins.extract.detect._base`, :mod:`plugins.extract.align._base` or :mod:`plugins.extract.mask._base`) and should not be overridden within plugins themselves. Handles consistent finalization for all plugins that exist within that plugin type. Its input is always the output from :func:`process_output()` Parameters ---------- batch : dict Contains the batch that is currently being passed through the plugin process """ def get_batch(self, queue): """ **Override method** (at `<plugin_type>` level) This method should be overridden at the `<plugin_type>` level (IE. :mod:`plugins.extract.detect._base`, :mod:`plugins.extract.align._base` or :mod:`plugins.extract.mask._base`) and should not be overridden within plugins themselves. Get :class:`~plugins.extract.pipeline.ExtractMedia` items from the queue in batches of :attr:`batchsize` Parameters ---------- queue : queue.Queue() The ``queue`` that the batch will be fed from. This will be the input to the plugin. """ raise NotImplementedError # <<< THREADING METHODS >>> # def start(self): """ Start all threads Exposed for :mod:`~plugins.extract.pipeline` to start plugin's threads """ for thread in self._threads: thread.start() def join(self): """ Join all threads Exposed for :mod:`~plugins.extract.pipeline` to join plugin's threads """ for thread in self._threads: thread.join() del thread def check_and_raise_error(self): """ Check all threads for errors Exposed for :mod:`~plugins.extract.pipeline` to check plugin's threads for errors """ for thread in self._threads: err = thread.check_and_raise_error() if err is not None: logger.debug("thread_error_detected") return True return False # <<< PROTECTED ACCESS METHODS >>> # # <<< INIT METHODS >>> # def _get_model(self, git_model_id, model_filename): """ Check if model is available, if not, download and unzip it """ if model_filename is None: logger.debug("No model_filename specified. Returning None") return None if git_model_id is None: logger.debug("No git_model_id specified. Returning None") return None plugin_path = os.path.join(*self.__module__.split(".")[:-1]) if os.path.basename(plugin_path) in ("detect", "align", "mask", "recognition"): base_path = os.path.dirname(os.path.realpath(sys.argv[0])) cache_path = os.path.join(base_path, plugin_path, ".cache") else: cache_path = os.path.join(os.path.dirname(__file__), ".cache") model = GetModel(model_filename, cache_path, git_model_id) return model.model_path # <<< PLUGIN INITIALIZATION >>> # def initialize(self, *args, **kwargs): """ Initialize the extractor plugin Should be called from :mod:`~plugins.extract.pipeline` """ logger.debug("initialize %s: (args: %s, kwargs: %s)", self.__class__.__name__, args, kwargs) logger.info("Initializing %s (%s)...", self.name, self._plugin_type.title()) self.queue_size = 1 name = self.name.replace(" ", "_").lower() self._add_queues(kwargs["in_queue"], kwargs["out_queue"], ["predict_{}".format(name), "post_{}".format(name)]) self._compile_threads() try: self.init_model() except tf_errors.UnknownError as err: if "failed to get convolution algorithm" in str(err).lower(): msg = ("Tensorflow raised an unknown error. This is most likely caused by a " "failure to launch cuDNN which can occur for some GPU/Tensorflow " "combinations. You should enable `allow_growth` to attempt to resolve this " "issue:" "\nGUI: Go to Settings > Extract Plugins > Global and enable the " "`allow_growth` option." "\nCLI: Go to `faceswap/config/extract.ini` and change the `allow_growth " "option to `True`.") raise FaceswapError(msg) from err raise err logger.info("Initialized %s (%s) with batchsize of %s", self.name, self._plugin_type.title(), self.batchsize) def _add_queues(self, in_queue, out_queue, queues): """ Add the queues in_queue and out_queue should be previously created queue manager queues. queues should be a list of queue names """ self._queues["in"] = in_queue self._queues["out"] = out_queue for q_name in queues: self._queues[q_name] = queue_manager.get_queue( name="{}{}_{}".format(self._plugin_type, self._instance, q_name), maxsize=self.queue_size) # <<< THREAD METHODS >>> # def _compile_threads(self): """ Compile the threads into self._threads list """ logger.debug("Compiling %s threads", self._plugin_type) name = self.name.replace(" ", "_").lower() base_name = "{}_{}".format(self._plugin_type, name) self._add_thread("{}_input".format(base_name), self.process_input, self._queues["in"], self._queues["predict_{}".format(name)]) self._add_thread("{}_predict".format(base_name), self._predict, self._queues["predict_{}".format(name)], self._queues["post_{}".format(name)]) self._add_thread("{}_output".format(base_name), self.process_output, self._queues["post_{}".format(name)], self._queues["out"]) logger.debug("Compiled %s threads: %s", self._plugin_type, self._threads) def _add_thread(self, name, function, in_queue, out_queue): """ Add a MultiThread thread to self._threads """ logger.debug("Adding thread: (name: %s, function: %s, in_queue: %s, out_queue: %s)", name, function, in_queue, out_queue) self._threads.append(MultiThread(target=self._thread_process, name=name, function=function, in_queue=in_queue, out_queue=out_queue)) logger.debug("Added thread: %s", name) def _thread_process(self, function, in_queue, out_queue): """ Perform a plugin function in a thread """ func_name = function.__name__ logger.debug("threading: (function: '%s')", func_name) while True: if func_name == "process_input": # Process input items to batches exhausted, batch = self.get_batch(in_queue) if exhausted: if batch: # Put the final batch batch = function(batch) out_queue.put(batch) break else: batch = self._get_item(in_queue) if batch == "EOF": break try: batch = function(batch) except tf_errors.UnknownError as err: if "failed to get convolution algorithm" in str(err).lower(): msg = ("Tensorflow raised an unknown error. This is most likely caused by a " "failure to launch cuDNN which can occur for some GPU/Tensorflow " "combinations. You should enable `allow_growth` to attempt to resolve " "this issue:" "\nGUI: Go to Settings > Extract Plugins > Global and enable the " "`allow_growth` option." "\nCLI: Go to `faceswap/config/extract.ini` and change the " "`allow_growth option to `True`.") raise FaceswapError(msg) from err raise err if func_name == "process_output": # Process output items to individual items from batch for item in self.finalize(batch): out_queue.put(item) else: out_queue.put(batch) logger.debug("Putting EOF") out_queue.put("EOF") # <<< QUEUE METHODS >>> # def _get_item(self, queue): """ Yield one item from a queue """ item = queue.get() if isinstance(item, ExtractMedia): logger.trace("filename: '%s', image shape: %s, detected_faces: %s, queue: %s, " "item: %s", item.filename, item.image_shape, item.detected_faces, queue, item) self._extract_media[item.filename] = item else: logger.trace("item: %s, queue: %s", item, queue) return item @staticmethod def _dict_lists_to_list_dicts(dictionary): """ Convert a dictionary of lists to a list of dictionaries """ return [dict(zip(dictionary, val)) for val in zip(*dictionary.values())]
#!/usr/bin/env python3 """ Base class for Faceswap :mod:`~plugins.extract.detect`, :mod:`~plugins.extract.align` and :mod:`~plugins.extract.mask` Plugins """ import logging import os import sys from tensorflow.python import errors_impl as tf_errors # pylint:disable=no-name-in-module from lib.multithreading import MultiThread from lib.queue_manager import queue_manager from lib.utils import GetModel, FaceswapError from ._config import Config from .pipeline import ExtractMedia logger = logging.getLogger(__name__) # pylint: disable=invalid-name # TODO CPU mode # TODO Run with warnings mode def _get_config(plugin_name, configfile=None): """ Return the configuration for the requested model Parameters ---------- plugin_name: str The module name of the child plugin. configfile: str, optional Path to a :file:`./config/<plugin_type>.ini` file for this plugin. Default: use system configuration. Returns ------- config_dict, dict A dictionary of configuration items from the configuration file """ return Config(plugin_name, configfile=configfile).config_dict class Extractor(): """ Extractor Plugin Object All ``_base`` classes for Aligners, Detectors and Maskers inherit from this class. This class sets up a pipeline for working with ML plugins. Plugins are split into 3 threads, to utilize Numpy and CV2s parallel processing, as well as allow the predict function of the model to sit in a dedicated thread. A plugin is expected to have 3 core functions, each in their own thread: - :func:`process_input()` - Prepare the data for feeding into a model - :func:`predict` - Feed the data through the model - :func:`process_output()` - Perform any data post-processing Parameters ---------- git_model_id: int The second digit in the github tag that identifies this model. See https://github.com/deepfakes-models/faceswap-models for more information model_filename: str The name of the model file to be loaded exclude_gpus: list, optional A list of indices correlating to connected GPUs that Tensorflow should not use. Pass ``None`` to not exclude any GPUs. Default: ``None`` configfile: str, optional Path to a custom configuration ``ini`` file. Default: Use system configfile instance: int, optional If this plugin is being executed multiple times (i.e. multiple pipelines have been launched), the instance of the plugin must be passed in for naming convention reasons. Default: 0 The following attributes should be set in the plugin's :func:`__init__` method after initializing the parent. Attributes ---------- name: str Name of this plugin. Used for display purposes. input_size: int The input size to the model in pixels across one edge. The input size should always be square. color_format: str Color format for model. Must be ``'BGR'``, ``'RGB'`` or ``'GRAY'``. Defaults to ``'BGR'`` if not explicitly set. vram: int Approximate VRAM used by the model at :attr:`input_size`. Used to calculate the :attr:`batchsize`. Be conservative to avoid OOM. vram_warnings: int Approximate VRAM used by the model at :attr:`input_size` that will still run, but generates warnings. Used to calculate the :attr:`batchsize`. Be conservative to avoid OOM. vram_per_batch: int Approximate additional VRAM used by the model for each additional batch. Used to calculate the :attr:`batchsize`. Be conservative to avoid OOM. See Also -------- plugins.extract.detect._base : Detector parent class for extraction plugins. plugins.extract.align._base : Aligner parent class for extraction plugins. plugins.extract.mask._base : Masker parent class for extraction plugins. plugins.extract.pipeline : The extract pipeline that configures and calls all plugins """ def __init__(self, git_model_id=None, model_filename=None, exclude_gpus=None, configfile=None, instance=0): logger.debug("Initializing %s: (git_model_id: %s, model_filename: %s, exclude_gpus: %s, " "configfile: %s, instance: %s, )", self.__class__.__name__, git_model_id, model_filename, exclude_gpus, configfile, instance) self._instance = instance self._exclude_gpus = exclude_gpus self.config = _get_config(".".join(self.__module__.split(".")[-2:]), configfile=configfile) """ dict: Config for this plugin, loaded from ``extract.ini`` configfile """ self.model_path = self._get_model(git_model_id, model_filename) """ str or list: Path to the model file(s) (if required). Multiple model files should be a list of strings """ # << SET THE FOLLOWING IN PLUGINS __init__ IF DIFFERENT FROM DEFAULT >> # self.name = None self.input_size = None self.color_format = "BGR" self.vram = None self.vram_warnings = None # Will run at this with warnings self.vram_per_batch = None # << THE FOLLOWING ARE SET IN self.initialize METHOD >> # self.queue_size = 1 """ int: Queue size for all internal queues. Set in :func:`initialize()` """ self.model = None """varies: The model for this plugin. Set in the plugin's :func:`init_model()` method """ # For detectors that support batching, this should be set to the calculated batch size # that the amount of available VRAM will support. self.batchsize = 1 """ int: Batchsize for feeding this model. The number of images the model should feed through at once. """ self._queues = dict() """ dict: in + out queues and internal queues for this plugin, """ self._threads = [] """ list: Internal threads for this plugin """ self._extract_media = dict() """ dict: The :class:`plugins.extract.pipeline.ExtractMedia` objects currently being processed. Stored at input for pairing back up on output of extractor process """ # << THE FOLLOWING PROTECTED ATTRIBUTES ARE SET IN PLUGIN TYPE _base.py >>> # self._plugin_type = None """ str: Plugin type. ``detect`` or ``align`` set in ``<plugin_type>._base`` """ logger.debug("Initialized _base %s", self.__class__.__name__) # <<< OVERIDABLE METHODS >>> # def init_model(self): """ **Override method** Override this method to execute the specific model initialization method """ raise NotImplementedError def process_input(self, batch): """ **Override method** Override this method for specific extractor pre-processing of image Parameters ---------- batch : dict Contains the batch that is currently being passed through the plugin process Notes ----- When preparing an input to the model a key ``feed`` must be added to the :attr:`batch` ``dict`` which contains this input. """ raise NotImplementedError def predict(self, batch): """ **Override method** Override this method for specific extractor model prediction function Parameters ---------- batch : dict Contains the batch that is currently being passed through the plugin process Notes ----- Input for :func:`predict` should have been set in :func:`process_input` with the addition of a ``feed`` key to the :attr:`batch` ``dict``. Output from the model should add the key ``prediction`` to the :attr:`batch` ``dict``. For Detect: the expected output for the ``prediction`` key of the :attr:`batch` dict should be a ``list`` of :attr:`batchsize` of detected face points. These points should be either a ``list``, ``tuple`` or ``numpy.ndarray`` with the first 4 items being the `left`, `top`, `right`, `bottom` points, in that order """ raise NotImplementedError def process_output(self, batch): """ **Override method** Override this method for specific extractor model post predict function Parameters ---------- batch : dict Contains the batch that is currently being passed through the plugin process Notes ----- For Align: The key ``landmarks`` must be returned in the :attr:`batch` ``dict`` from this method. This should be a ``list`` or ``numpy.ndarray`` of :attr:`batchsize` containing a ``list``, ``tuple`` or ``numpy.ndarray`` of `(x, y)` coordinates of the 68 point landmarks as calculated from the :attr:`model`. """ raise NotImplementedError def _predict(self, batch): """ **Override method** (at `<plugin_type>` level) This method should be overridden at the `<plugin_type>` level (IE. ``plugins.extract.detect._base`` or ``plugins.extract.align._base``) and should not be overridden within plugins themselves. It acts as a wrapper for the plugin's ``self.predict`` method and handles any predict processing that is consistent for all plugins within the `plugin_type` Parameters ---------- batch : dict Contains the batch that is currently being passed through the plugin process """ raise NotImplementedError def finalize(self, batch): """ **Override method** (at `<plugin_type>` level) This method should be overridden at the `<plugin_type>` level (IE. :mod:`plugins.extract.detect._base`, :mod:`plugins.extract.align._base` or :mod:`plugins.extract.mask._base`) and should not be overridden within plugins themselves. Handles consistent finalization for all plugins that exist within that plugin type. Its input is always the output from :func:`process_output()` Parameters ---------- batch : dict Contains the batch that is currently being passed through the plugin process """ def get_batch(self, queue): """ **Override method** (at `<plugin_type>` level) This method should be overridden at the `<plugin_type>` level (IE. :mod:`plugins.extract.detect._base`, :mod:`plugins.extract.align._base` or :mod:`plugins.extract.mask._base`) and should not be overridden within plugins themselves. Get :class:`~plugins.extract.pipeline.ExtractMedia` items from the queue in batches of :attr:`batchsize` Parameters ---------- queue : queue.Queue() The ``queue`` that the batch will be fed from. This will be the input to the plugin. """ raise NotImplementedError # <<< THREADING METHODS >>> # def start(self): """ Start all threads Exposed for :mod:`~plugins.extract.pipeline` to start plugin's threads """ for thread in self._threads: thread.start() def join(self): """ Join all threads Exposed for :mod:`~plugins.extract.pipeline` to join plugin's threads """ for thread in self._threads: thread.join() del thread def check_and_raise_error(self): """ Check all threads for errors Exposed for :mod:`~plugins.extract.pipeline` to check plugin's threads for errors """ for thread in self._threads: err = thread.check_and_raise_error() if err is not None: logger.debug("thread_error_detected") return True return False # <<< PROTECTED ACCESS METHODS >>> # # <<< INIT METHODS >>> # def _get_model(self, git_model_id, model_filename): """ Check if model is available, if not, download and unzip it """ if model_filename is None: logger.debug("No model_filename specified. Returning None") return None if git_model_id is None: logger.debug("No git_model_id specified. Returning None") return None plugin_path = os.path.join(*self.__module__.split(".")[:-1]) if os.path.basename(plugin_path) in ("detect", "align", "mask", "recognition"): base_path = os.path.dirname(os.path.realpath(sys.argv[0])) cache_path = os.path.join(base_path, plugin_path, ".cache") else: cache_path = os.path.join(os.path.dirname(__file__), ".cache") model = GetModel(model_filename, cache_path, git_model_id) return model.model_path # <<< PLUGIN INITIALIZATION >>> # def initialize(self, *args, **kwargs): """ Initialize the extractor plugin Should be called from :mod:`~plugins.extract.pipeline` """ logger.debug("initialize %s: (args: %s, kwargs: %s)", self.__class__.__name__, args, kwargs) logger.info("Initializing %s (%s)...", self.name, self._plugin_type.title()) self.queue_size = 1 name = self.name.replace(" ", "_").lower() self._add_queues(kwargs["in_queue"], kwargs["out_queue"], ["predict_{}".format(name), "post_{}".format(name)]) self._compile_threads() try: self.init_model() except tf_errors.UnknownError as err: if "failed to get convolution algorithm" in str(err).lower(): msg = ("Tensorflow raised an unknown error. This is most likely caused by a " "failure to launch cuDNN which can occur for some GPU/Tensorflow " "combinations. You should enable `allow_growth` to attempt to resolve this " "issue:" "\nGUI: Go to Settings > Extract Plugins > Global and enable the " "`allow_growth` option." "\nCLI: Go to `faceswap/config/extract.ini` and change the `allow_growth " "option to `True`.") raise FaceswapError(msg) from err raise err logger.info("Initialized %s (%s) with batchsize of %s", self.name, self._plugin_type.title(), self.batchsize) def _add_queues(self, in_queue, out_queue, queues): """ Add the queues in_queue and out_queue should be previously created queue manager queues. queues should be a list of queue names """ self._queues["in"] = in_queue self._queues["out"] = out_queue for q_name in queues: self._queues[q_name] = queue_manager.get_queue( name="{}{}_{}".format(self._plugin_type, self._instance, q_name), maxsize=self.queue_size) # <<< THREAD METHODS >>> # def _compile_threads(self): """ Compile the threads into self._threads list """ logger.debug("Compiling %s threads", self._plugin_type) name = self.name.replace(" ", "_").lower() base_name = "{}_{}".format(self._plugin_type, name) self._add_thread("{}_input".format(base_name), self.process_input, self._queues["in"], self._queues["predict_{}".format(name)]) self._add_thread("{}_predict".format(base_name), self._predict, self._queues["predict_{}".format(name)], self._queues["post_{}".format(name)]) self._add_thread("{}_output".format(base_name), self.process_output, self._queues["post_{}".format(name)], self._queues["out"]) logger.debug("Compiled %s threads: %s", self._plugin_type, self._threads) def _add_thread(self, name, function, in_queue, out_queue): """ Add a MultiThread thread to self._threads """ logger.debug("Adding thread: (name: %s, function: %s, in_queue: %s, out_queue: %s)", name, function, in_queue, out_queue) self._threads.append(MultiThread(target=self._thread_process, name=name, function=function, in_queue=in_queue, out_queue=out_queue)) logger.debug("Added thread: %s", name) def _thread_process(self, function, in_queue, out_queue): """ Perform a plugin function in a thread """ func_name = function.__name__ logger.debug("threading: (function: '%s')", func_name) while True: if func_name == "process_input": # Process input items to batches exhausted, batch = self.get_batch(in_queue) if exhausted: if batch: # Put the final batch batch = function(batch) out_queue.put(batch) break else: batch = self._get_item(in_queue) if batch == "EOF": break try: batch = function(batch) except tf_errors.UnknownError as err: if "failed to get convolution algorithm" in str(err).lower(): msg = ("Tensorflow raised an unknown error. This is most likely caused by a " "failure to launch cuDNN which can occur for some GPU/Tensorflow " "combinations. You should enable `allow_growth` to attempt to resolve " "this issue:" "\nGUI: Go to Settings > Extract Plugins > Global and enable the " "`allow_growth` option." "\nCLI: Go to `faceswap/config/extract.ini` and change the " "`allow_growth option to `True`.") raise FaceswapError(msg) from err raise err if func_name == "process_output": # Process output items to individual items from batch for item in self.finalize(batch): out_queue.put(item) else: out_queue.put(batch) logger.debug("Putting EOF") out_queue.put("EOF") # <<< QUEUE METHODS >>> # def _get_item(self, queue): """ Yield one item from a queue """ item = queue.get() if isinstance(item, ExtractMedia): logger.trace("filename: '%s', image shape: %s, detected_faces: %s, queue: %s, " "item: %s", item.filename, item.image_shape, item.detected_faces, queue, item) self._extract_media[item.filename] = item else: logger.trace("item: %s, queue: %s", item, queue) return item @staticmethod def _dict_lists_to_list_dicts(dictionary): """ Convert a dictionary of lists to a list of dictionaries """ return [dict(zip(dictionary, val)) for val in zip(*dictionary.values())]
en
0.730543
#!/usr/bin/env python3 Base class for Faceswap :mod:`~plugins.extract.detect`, :mod:`~plugins.extract.align` and :mod:`~plugins.extract.mask` Plugins # pylint:disable=no-name-in-module # pylint: disable=invalid-name # TODO CPU mode # TODO Run with warnings mode Return the configuration for the requested model Parameters ---------- plugin_name: str The module name of the child plugin. configfile: str, optional Path to a :file:`./config/<plugin_type>.ini` file for this plugin. Default: use system configuration. Returns ------- config_dict, dict A dictionary of configuration items from the configuration file Extractor Plugin Object All ``_base`` classes for Aligners, Detectors and Maskers inherit from this class. This class sets up a pipeline for working with ML plugins. Plugins are split into 3 threads, to utilize Numpy and CV2s parallel processing, as well as allow the predict function of the model to sit in a dedicated thread. A plugin is expected to have 3 core functions, each in their own thread: - :func:`process_input()` - Prepare the data for feeding into a model - :func:`predict` - Feed the data through the model - :func:`process_output()` - Perform any data post-processing Parameters ---------- git_model_id: int The second digit in the github tag that identifies this model. See https://github.com/deepfakes-models/faceswap-models for more information model_filename: str The name of the model file to be loaded exclude_gpus: list, optional A list of indices correlating to connected GPUs that Tensorflow should not use. Pass ``None`` to not exclude any GPUs. Default: ``None`` configfile: str, optional Path to a custom configuration ``ini`` file. Default: Use system configfile instance: int, optional If this plugin is being executed multiple times (i.e. multiple pipelines have been launched), the instance of the plugin must be passed in for naming convention reasons. Default: 0 The following attributes should be set in the plugin's :func:`__init__` method after initializing the parent. Attributes ---------- name: str Name of this plugin. Used for display purposes. input_size: int The input size to the model in pixels across one edge. The input size should always be square. color_format: str Color format for model. Must be ``'BGR'``, ``'RGB'`` or ``'GRAY'``. Defaults to ``'BGR'`` if not explicitly set. vram: int Approximate VRAM used by the model at :attr:`input_size`. Used to calculate the :attr:`batchsize`. Be conservative to avoid OOM. vram_warnings: int Approximate VRAM used by the model at :attr:`input_size` that will still run, but generates warnings. Used to calculate the :attr:`batchsize`. Be conservative to avoid OOM. vram_per_batch: int Approximate additional VRAM used by the model for each additional batch. Used to calculate the :attr:`batchsize`. Be conservative to avoid OOM. See Also -------- plugins.extract.detect._base : Detector parent class for extraction plugins. plugins.extract.align._base : Aligner parent class for extraction plugins. plugins.extract.mask._base : Masker parent class for extraction plugins. plugins.extract.pipeline : The extract pipeline that configures and calls all plugins dict: Config for this plugin, loaded from ``extract.ini`` configfile str or list: Path to the model file(s) (if required). Multiple model files should be a list of strings # << SET THE FOLLOWING IN PLUGINS __init__ IF DIFFERENT FROM DEFAULT >> # # Will run at this with warnings # << THE FOLLOWING ARE SET IN self.initialize METHOD >> # int: Queue size for all internal queues. Set in :func:`initialize()` varies: The model for this plugin. Set in the plugin's :func:`init_model()` method # For detectors that support batching, this should be set to the calculated batch size # that the amount of available VRAM will support. int: Batchsize for feeding this model. The number of images the model should feed through at once. dict: in + out queues and internal queues for this plugin, list: Internal threads for this plugin dict: The :class:`plugins.extract.pipeline.ExtractMedia` objects currently being processed. Stored at input for pairing back up on output of extractor process # << THE FOLLOWING PROTECTED ATTRIBUTES ARE SET IN PLUGIN TYPE _base.py >>> # str: Plugin type. ``detect`` or ``align`` set in ``<plugin_type>._base`` # <<< OVERIDABLE METHODS >>> # **Override method** Override this method to execute the specific model initialization method **Override method** Override this method for specific extractor pre-processing of image Parameters ---------- batch : dict Contains the batch that is currently being passed through the plugin process Notes ----- When preparing an input to the model a key ``feed`` must be added to the :attr:`batch` ``dict`` which contains this input. **Override method** Override this method for specific extractor model prediction function Parameters ---------- batch : dict Contains the batch that is currently being passed through the plugin process Notes ----- Input for :func:`predict` should have been set in :func:`process_input` with the addition of a ``feed`` key to the :attr:`batch` ``dict``. Output from the model should add the key ``prediction`` to the :attr:`batch` ``dict``. For Detect: the expected output for the ``prediction`` key of the :attr:`batch` dict should be a ``list`` of :attr:`batchsize` of detected face points. These points should be either a ``list``, ``tuple`` or ``numpy.ndarray`` with the first 4 items being the `left`, `top`, `right`, `bottom` points, in that order **Override method** Override this method for specific extractor model post predict function Parameters ---------- batch : dict Contains the batch that is currently being passed through the plugin process Notes ----- For Align: The key ``landmarks`` must be returned in the :attr:`batch` ``dict`` from this method. This should be a ``list`` or ``numpy.ndarray`` of :attr:`batchsize` containing a ``list``, ``tuple`` or ``numpy.ndarray`` of `(x, y)` coordinates of the 68 point landmarks as calculated from the :attr:`model`. **Override method** (at `<plugin_type>` level) This method should be overridden at the `<plugin_type>` level (IE. ``plugins.extract.detect._base`` or ``plugins.extract.align._base``) and should not be overridden within plugins themselves. It acts as a wrapper for the plugin's ``self.predict`` method and handles any predict processing that is consistent for all plugins within the `plugin_type` Parameters ---------- batch : dict Contains the batch that is currently being passed through the plugin process **Override method** (at `<plugin_type>` level) This method should be overridden at the `<plugin_type>` level (IE. :mod:`plugins.extract.detect._base`, :mod:`plugins.extract.align._base` or :mod:`plugins.extract.mask._base`) and should not be overridden within plugins themselves. Handles consistent finalization for all plugins that exist within that plugin type. Its input is always the output from :func:`process_output()` Parameters ---------- batch : dict Contains the batch that is currently being passed through the plugin process **Override method** (at `<plugin_type>` level) This method should be overridden at the `<plugin_type>` level (IE. :mod:`plugins.extract.detect._base`, :mod:`plugins.extract.align._base` or :mod:`plugins.extract.mask._base`) and should not be overridden within plugins themselves. Get :class:`~plugins.extract.pipeline.ExtractMedia` items from the queue in batches of :attr:`batchsize` Parameters ---------- queue : queue.Queue() The ``queue`` that the batch will be fed from. This will be the input to the plugin. # <<< THREADING METHODS >>> # Start all threads Exposed for :mod:`~plugins.extract.pipeline` to start plugin's threads Join all threads Exposed for :mod:`~plugins.extract.pipeline` to join plugin's threads Check all threads for errors Exposed for :mod:`~plugins.extract.pipeline` to check plugin's threads for errors # <<< PROTECTED ACCESS METHODS >>> # # <<< INIT METHODS >>> # Check if model is available, if not, download and unzip it # <<< PLUGIN INITIALIZATION >>> # Initialize the extractor plugin Should be called from :mod:`~plugins.extract.pipeline` Add the queues in_queue and out_queue should be previously created queue manager queues. queues should be a list of queue names # <<< THREAD METHODS >>> # Compile the threads into self._threads list Add a MultiThread thread to self._threads Perform a plugin function in a thread # Process input items to batches # Put the final batch # Process output items to individual items from batch # <<< QUEUE METHODS >>> # Yield one item from a queue Convert a dictionary of lists to a list of dictionaries
2.176684
2
pyplan/pyplan/preference_module/serializers.py
jorgedouglas71/pyplan-ide
17
6625819
<reponame>jorgedouglas71/pyplan-ide<gh_stars>10-100 from rest_framework import serializers from .models import PreferenceModule class PreferenceModuleSerializer(serializers.ModelSerializer): class Meta: model = PreferenceModule fields = '__all__'
from rest_framework import serializers from .models import PreferenceModule class PreferenceModuleSerializer(serializers.ModelSerializer): class Meta: model = PreferenceModule fields = '__all__'
none
1
1.6972
2
examples/mysql.py
vamshi091211/pyinfra
1
6625820
from pyinfra import host, state from pyinfra.operations import apt, files, mysql, python SUDO = True if host.fact.linux_name != 'Debian': # Raises an exception mid-deploy python.raise_exception( {'Ensure we are Debian'}, NotImplementedError, '`mysql.py` only works on Debian', ) apt.packages( {'Install mysql server & client'}, ['mysql-server'], update=True, cache_time=3600, ) # Setup a MySQL role & database # mysql.user( {'Create the pyinfra@localhost MySQL user'}, 'pyinfra', password='<PASSWORD>', ) mysql.database( {'Create the pyinfra_stuff database'}, 'pyinfra_stuff', user='pyinfra', user_privileges=['SELECT', 'INSERT'], charset='utf8', ) # Upload & import a SQL file into the pyinfra_stuff database # filename = 'files/a_db.sql' temp_filename = state.get_temp_filename(filename) files.put( {'Upload the a_db.sql file'}, filename, temp_filename, ) mysql.load( {'Import the a_db.sql file'}, temp_filename, database='pyinfra_stuff', ) # Now duplicate the pyinfra_stuff database -> pyinfra_stuff_copy # mysql.database( {'Create the pyinfra_stuff_copy database'}, 'pyinfra_stuff_copy', charset='utf8', ) dump_filename = state.get_temp_filename('mysql_dump') mysql.dump( {'Dump the pyinfra_stuff database'}, dump_filename, database='pyinfra_stuff', ) mysql.load( {'Import the pyinfra_stuff dump into pyinfra_stuff_copy'}, dump_filename, database='pyinfra_stuff_copy', )
from pyinfra import host, state from pyinfra.operations import apt, files, mysql, python SUDO = True if host.fact.linux_name != 'Debian': # Raises an exception mid-deploy python.raise_exception( {'Ensure we are Debian'}, NotImplementedError, '`mysql.py` only works on Debian', ) apt.packages( {'Install mysql server & client'}, ['mysql-server'], update=True, cache_time=3600, ) # Setup a MySQL role & database # mysql.user( {'Create the pyinfra@localhost MySQL user'}, 'pyinfra', password='<PASSWORD>', ) mysql.database( {'Create the pyinfra_stuff database'}, 'pyinfra_stuff', user='pyinfra', user_privileges=['SELECT', 'INSERT'], charset='utf8', ) # Upload & import a SQL file into the pyinfra_stuff database # filename = 'files/a_db.sql' temp_filename = state.get_temp_filename(filename) files.put( {'Upload the a_db.sql file'}, filename, temp_filename, ) mysql.load( {'Import the a_db.sql file'}, temp_filename, database='pyinfra_stuff', ) # Now duplicate the pyinfra_stuff database -> pyinfra_stuff_copy # mysql.database( {'Create the pyinfra_stuff_copy database'}, 'pyinfra_stuff_copy', charset='utf8', ) dump_filename = state.get_temp_filename('mysql_dump') mysql.dump( {'Dump the pyinfra_stuff database'}, dump_filename, database='pyinfra_stuff', ) mysql.load( {'Import the pyinfra_stuff dump into pyinfra_stuff_copy'}, dump_filename, database='pyinfra_stuff_copy', )
en
0.433261
# Raises an exception mid-deploy # Setup a MySQL role & database # # Upload & import a SQL file into the pyinfra_stuff database # # Now duplicate the pyinfra_stuff database -> pyinfra_stuff_copy #
2.402385
2
python/lbann/modules/graph/utils.py
aj-prime/lbann
0
6625821
import lbann from lbann.util import str_list class GraphVertexData: def __init__(self, layers, num_features): """Object to hold list of layers, where each layer represents a vertex in a graph. Args: layers (iterator of layers): One dimensional iterator of node features with N number of ndoes num_features (int) : the number of features per vertex """ self.shape = (len(layers), num_features) self.layers = layers self.num_nodes = len(layers) self.num_features = num_features def __getitem__(self, node): """Get the feature vector of the None node represented as an LBANN layer args: node (int): The node to retrieve the features for. returns: (Layer) : returns the features of the Vertex <node> of the graph. """ return self.layers[node] def __setitem__(self, node, feature): """Set the value of the row-th layer in args: row (int): layer (Layer): """ self.layers[node] = feature def update_num_features(self, num_features): """Update the internal shapes to keep track of features Args: num_features (int): the features per vertex """ self.num_features = num_features self.shape = (len(self.layers), num_features) def size(self, index = None): """Get the size (shape) of the GraphVertexObject, where the size is represented as a tuple (n,m), where n is the number of nodes and m is the number of features per node. args: index (int): 0 to return the number of nodes and 1 to return the number of features. returns: (int) or (int,int): Either returns the tuple (n,m) or n or m. """ if isinstance(index,int): return self.shape[index] else: return self.shape def get_mat(self, cols = None): """Generates a matrix representation of the graph data. args: cols (int) """ mat = lbann.Concatenation(self.layers) if (cols): mat = lbann.Reshape(mat, dims=str_list([self.shape[0], cols])) else: mat = lbann.Reshape(mat, dims=str_list([self.shape[0], self.shape[1]])) return mat def clone(self): """Generates a clone of the GraphVertexData object. Results in a splitting in the DAG. """ cloned_layers = [] for i,node in enumerate(self.layers): temp = lbann.Split(node) layers[i] = lbann.Identity(temp) cloned_layers.append(lbann.Identity(temp)) return GraphVertexData(cloned_layers, self.num_features) @classmethod def matrix_to_graph(cls, mat_layer, num_vertices, num_features): """Given a 2D matrix of shape (num_vertices, num_features), returns a GraphVertexData object with num_vertices number of nodes with num_features. """ slice_points = str_list([i for i in range(0,num_vertices * num_features + 1, num_features)]) flattened_layer = lbann.Reshape(mat_layer, dims = str(num_vertices * num_features)) sliced_mat_layer = lbann.Slice(flattened_layer, axis = 0, slice_points = slice_points) list_of_layers = [] for node in range(num_vertices): temp = lbann.Identity(sliced_mat_layer) list_of_layers.append(lbann.Reshape(temp, dims=str_list([1, num_features]))) return cls(list_of_layers, num_features)
import lbann from lbann.util import str_list class GraphVertexData: def __init__(self, layers, num_features): """Object to hold list of layers, where each layer represents a vertex in a graph. Args: layers (iterator of layers): One dimensional iterator of node features with N number of ndoes num_features (int) : the number of features per vertex """ self.shape = (len(layers), num_features) self.layers = layers self.num_nodes = len(layers) self.num_features = num_features def __getitem__(self, node): """Get the feature vector of the None node represented as an LBANN layer args: node (int): The node to retrieve the features for. returns: (Layer) : returns the features of the Vertex <node> of the graph. """ return self.layers[node] def __setitem__(self, node, feature): """Set the value of the row-th layer in args: row (int): layer (Layer): """ self.layers[node] = feature def update_num_features(self, num_features): """Update the internal shapes to keep track of features Args: num_features (int): the features per vertex """ self.num_features = num_features self.shape = (len(self.layers), num_features) def size(self, index = None): """Get the size (shape) of the GraphVertexObject, where the size is represented as a tuple (n,m), where n is the number of nodes and m is the number of features per node. args: index (int): 0 to return the number of nodes and 1 to return the number of features. returns: (int) or (int,int): Either returns the tuple (n,m) or n or m. """ if isinstance(index,int): return self.shape[index] else: return self.shape def get_mat(self, cols = None): """Generates a matrix representation of the graph data. args: cols (int) """ mat = lbann.Concatenation(self.layers) if (cols): mat = lbann.Reshape(mat, dims=str_list([self.shape[0], cols])) else: mat = lbann.Reshape(mat, dims=str_list([self.shape[0], self.shape[1]])) return mat def clone(self): """Generates a clone of the GraphVertexData object. Results in a splitting in the DAG. """ cloned_layers = [] for i,node in enumerate(self.layers): temp = lbann.Split(node) layers[i] = lbann.Identity(temp) cloned_layers.append(lbann.Identity(temp)) return GraphVertexData(cloned_layers, self.num_features) @classmethod def matrix_to_graph(cls, mat_layer, num_vertices, num_features): """Given a 2D matrix of shape (num_vertices, num_features), returns a GraphVertexData object with num_vertices number of nodes with num_features. """ slice_points = str_list([i for i in range(0,num_vertices * num_features + 1, num_features)]) flattened_layer = lbann.Reshape(mat_layer, dims = str(num_vertices * num_features)) sliced_mat_layer = lbann.Slice(flattened_layer, axis = 0, slice_points = slice_points) list_of_layers = [] for node in range(num_vertices): temp = lbann.Identity(sliced_mat_layer) list_of_layers.append(lbann.Reshape(temp, dims=str_list([1, num_features]))) return cls(list_of_layers, num_features)
en
0.81183
Object to hold list of layers, where each layer represents a vertex in a graph. Args: layers (iterator of layers): One dimensional iterator of node features with N number of ndoes num_features (int) : the number of features per vertex Get the feature vector of the None node represented as an LBANN layer args: node (int): The node to retrieve the features for. returns: (Layer) : returns the features of the Vertex <node> of the graph. Set the value of the row-th layer in args: row (int): layer (Layer): Update the internal shapes to keep track of features Args: num_features (int): the features per vertex Get the size (shape) of the GraphVertexObject, where the size is represented as a tuple (n,m), where n is the number of nodes and m is the number of features per node. args: index (int): 0 to return the number of nodes and 1 to return the number of features. returns: (int) or (int,int): Either returns the tuple (n,m) or n or m. Generates a matrix representation of the graph data. args: cols (int) Generates a clone of the GraphVertexData object. Results in a splitting in the DAG. Given a 2D matrix of shape (num_vertices, num_features), returns a GraphVertexData object with num_vertices number of nodes with num_features.
3.217636
3
meta.py
mayur295/MetaDesktopAssistant-
0
6625822
#This a python project that focuses on development of basic desktop assistant #---**********************--- #import module pyttsx3 which is used for coversion of text into speech # init function to get an engine instance for the speech synthesis (formation) # sapi5 is API which allows the use of speech recognition(user asks) and speech synthesis (meta replys) within windows application # say method on the engine that passes the text input to be spoken # run and wait method, it processes the voice commands. import pyttsx3 import datetime import speech_recognition as sr import wikipedia import webbrowser import os import smtplib import pyautogui engine = pyttsx3.init('sapi5') voices = engine.getProperty('voices') #to get the voice details # print(voices[1].id) #0 and 1 are the voices available 0- male voice 1- female voice engine.setProperty('voice',voices[1].id) def speak(audio): engine.say(audio) engine.runAndWait() #Without this command, speech will not be audible to us. def screenshot(): pic=pyautogui.screenshot() pic.save('c:/User') def wishMe(): hour = int(datetime.datetime.now().hour) if hour>=0 and hour<12: speak("Good morning!") elif hour>=12 and hour<=16: speak("Good afternoon!") else: speak("Good evening!") speak("This is Meta, How may I help you?") def takecommand(): ''' it takes micrphone input from the user and returns string output ''' # creating a recognizer instance r = sr.Recognizer() # taking the audio input from microphone as source audio_data argument with sr.Microphone() as source: print("listening...") r.pause_threshold = 0.8 audio = r.listen(source) try: print("Recognizing...") # method of recognizer instance query = r.recognize_google(audio, language = 'en-in')#Using google speech recognition api for voice recognition. # returns the audio in the string format print(f"user said: {query}\n") except Exception as e: # print e print("sorry, i dont understand") # return none string when there is some problem return"None" return query def sendEmail(to, content): server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login('<EMAIL>', '<PASSWORD>') #write server.sendmail('<EMAIL>', to, content) #write server.close() if __name__ == "__main__" : wishMe() while True: query = takecommand().lower() ## LOGIC for executing task based on query asked by the user #To search something in wikipedia if 'wikipedia' in query: speak("searching wikipedia") query = query.replace('wikipedia',"") results = wikipedia.summary(query, sentences=2) speak("According to wikipedia") print(results) speak(results) #To open youtube elif "open youtube" in query: webbrowser.open("youtube.com") elif "open google" in query: webbrowser.open("google.com") elif 'open Linkedin' in query: webbrowser.open("Linkedin.com") elif 'open instagram' in query: webbrowser.open("instagram.com") elif 'open whatsapp' in query: webbrowser.open("https://web.whatsapp.com/") # this will exit and terminate the program elif "bye" in query: speak("Bye. Have A Good Day") exit() elif 'screenshot' in query: screenshot() #Know time by using datetime() function and storing the current #or live system into a variable called strTime. elif 'the time' in query: strTime = datetime.datetime.now().strftime("%H:%M:%S") speak(f"The time is {strTime}") print(strTime) #To open visual studio code elif 'open code' in query: codePath = "C:\\Users\\akanksha\\AppData\Local\\Programs\\Microsoft VS Code\\Code.exe" #mention the target location of app os.startfile(codePath) #To send mail elif 'mail to user' in query: try: speak("What should I say?") content = takecommand() to = "<EMAIL>" sendEmail(to, content) speak("Email has been sent!") except Exception as e: print(e) speak("Sorry, I am not able to send this email")
#This a python project that focuses on development of basic desktop assistant #---**********************--- #import module pyttsx3 which is used for coversion of text into speech # init function to get an engine instance for the speech synthesis (formation) # sapi5 is API which allows the use of speech recognition(user asks) and speech synthesis (meta replys) within windows application # say method on the engine that passes the text input to be spoken # run and wait method, it processes the voice commands. import pyttsx3 import datetime import speech_recognition as sr import wikipedia import webbrowser import os import smtplib import pyautogui engine = pyttsx3.init('sapi5') voices = engine.getProperty('voices') #to get the voice details # print(voices[1].id) #0 and 1 are the voices available 0- male voice 1- female voice engine.setProperty('voice',voices[1].id) def speak(audio): engine.say(audio) engine.runAndWait() #Without this command, speech will not be audible to us. def screenshot(): pic=pyautogui.screenshot() pic.save('c:/User') def wishMe(): hour = int(datetime.datetime.now().hour) if hour>=0 and hour<12: speak("Good morning!") elif hour>=12 and hour<=16: speak("Good afternoon!") else: speak("Good evening!") speak("This is Meta, How may I help you?") def takecommand(): ''' it takes micrphone input from the user and returns string output ''' # creating a recognizer instance r = sr.Recognizer() # taking the audio input from microphone as source audio_data argument with sr.Microphone() as source: print("listening...") r.pause_threshold = 0.8 audio = r.listen(source) try: print("Recognizing...") # method of recognizer instance query = r.recognize_google(audio, language = 'en-in')#Using google speech recognition api for voice recognition. # returns the audio in the string format print(f"user said: {query}\n") except Exception as e: # print e print("sorry, i dont understand") # return none string when there is some problem return"None" return query def sendEmail(to, content): server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login('<EMAIL>', '<PASSWORD>') #write server.sendmail('<EMAIL>', to, content) #write server.close() if __name__ == "__main__" : wishMe() while True: query = takecommand().lower() ## LOGIC for executing task based on query asked by the user #To search something in wikipedia if 'wikipedia' in query: speak("searching wikipedia") query = query.replace('wikipedia',"") results = wikipedia.summary(query, sentences=2) speak("According to wikipedia") print(results) speak(results) #To open youtube elif "open youtube" in query: webbrowser.open("youtube.com") elif "open google" in query: webbrowser.open("google.com") elif 'open Linkedin' in query: webbrowser.open("Linkedin.com") elif 'open instagram' in query: webbrowser.open("instagram.com") elif 'open whatsapp' in query: webbrowser.open("https://web.whatsapp.com/") # this will exit and terminate the program elif "bye" in query: speak("Bye. Have A Good Day") exit() elif 'screenshot' in query: screenshot() #Know time by using datetime() function and storing the current #or live system into a variable called strTime. elif 'the time' in query: strTime = datetime.datetime.now().strftime("%H:%M:%S") speak(f"The time is {strTime}") print(strTime) #To open visual studio code elif 'open code' in query: codePath = "C:\\Users\\akanksha\\AppData\Local\\Programs\\Microsoft VS Code\\Code.exe" #mention the target location of app os.startfile(codePath) #To send mail elif 'mail to user' in query: try: speak("What should I say?") content = takecommand() to = "<EMAIL>" sendEmail(to, content) speak("Email has been sent!") except Exception as e: print(e) speak("Sorry, I am not able to send this email")
en
0.848647
#This a python project that focuses on development of basic desktop assistant #---**********************--- #import module pyttsx3 which is used for coversion of text into speech # init function to get an engine instance for the speech synthesis (formation) # sapi5 is API which allows the use of speech recognition(user asks) and speech synthesis (meta replys) within windows application # say method on the engine that passes the text input to be spoken # run and wait method, it processes the voice commands. #to get the voice details # print(voices[1].id) #0 and 1 are the voices available 0- male voice 1- female voice #Without this command, speech will not be audible to us. it takes micrphone input from the user and returns string output # creating a recognizer instance # taking the audio input from microphone as source audio_data argument # method of recognizer instance #Using google speech recognition api for voice recognition. # returns the audio in the string format # print e # return none string when there is some problem #write #write ## LOGIC for executing task based on query asked by the user #To search something in wikipedia #To open youtube # this will exit and terminate the program #Know time by using datetime() function and storing the current #or live system into a variable called strTime. #To open visual studio code #mention the target location of app #To send mail
3.653066
4
sdk/python/pulumi_azure_nextgen/machinelearning/list_workspace_keys.py
pulumi/pulumi-azure-nextgen
31
6625823
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables __all__ = [ 'ListWorkspaceKeysResult', 'AwaitableListWorkspaceKeysResult', 'list_workspace_keys', ] @pulumi.output_type class ListWorkspaceKeysResult: """ Workspace authorization keys for a workspace. """ def __init__(__self__, primary_token=None, secondary_token=None): if primary_token and not isinstance(primary_token, str): raise TypeError("Expected argument 'primary_token' to be a str") pulumi.set(__self__, "primary_token", primary_token) if secondary_token and not isinstance(secondary_token, str): raise TypeError("Expected argument 'secondary_token' to be a str") pulumi.set(__self__, "secondary_token", secondary_token) @property @pulumi.getter(name="primaryToken") def primary_token(self) -> Optional[str]: """ Primary authorization key for this workspace. """ return pulumi.get(self, "primary_token") @property @pulumi.getter(name="secondaryToken") def secondary_token(self) -> Optional[str]: """ Secondary authorization key for this workspace. """ return pulumi.get(self, "secondary_token") class AwaitableListWorkspaceKeysResult(ListWorkspaceKeysResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return ListWorkspaceKeysResult( primary_token=self.primary_token, secondary_token=self.secondary_token) def list_workspace_keys(resource_group_name: Optional[str] = None, workspace_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableListWorkspaceKeysResult: """ Workspace authorization keys for a workspace. API Version: 2016-04-01. :param str resource_group_name: The name of the resource group to which the machine learning workspace belongs. :param str workspace_name: The name of the machine learning workspace. """ __args__ = dict() __args__['resourceGroupName'] = resource_group_name __args__['workspaceName'] = workspace_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-nextgen:machinelearning:listWorkspaceKeys', __args__, opts=opts, typ=ListWorkspaceKeysResult).value return AwaitableListWorkspaceKeysResult( primary_token=__ret__.primary_token, secondary_token=__ret__.secondary_token)
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables __all__ = [ 'ListWorkspaceKeysResult', 'AwaitableListWorkspaceKeysResult', 'list_workspace_keys', ] @pulumi.output_type class ListWorkspaceKeysResult: """ Workspace authorization keys for a workspace. """ def __init__(__self__, primary_token=None, secondary_token=None): if primary_token and not isinstance(primary_token, str): raise TypeError("Expected argument 'primary_token' to be a str") pulumi.set(__self__, "primary_token", primary_token) if secondary_token and not isinstance(secondary_token, str): raise TypeError("Expected argument 'secondary_token' to be a str") pulumi.set(__self__, "secondary_token", secondary_token) @property @pulumi.getter(name="primaryToken") def primary_token(self) -> Optional[str]: """ Primary authorization key for this workspace. """ return pulumi.get(self, "primary_token") @property @pulumi.getter(name="secondaryToken") def secondary_token(self) -> Optional[str]: """ Secondary authorization key for this workspace. """ return pulumi.get(self, "secondary_token") class AwaitableListWorkspaceKeysResult(ListWorkspaceKeysResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return ListWorkspaceKeysResult( primary_token=self.primary_token, secondary_token=self.secondary_token) def list_workspace_keys(resource_group_name: Optional[str] = None, workspace_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableListWorkspaceKeysResult: """ Workspace authorization keys for a workspace. API Version: 2016-04-01. :param str resource_group_name: The name of the resource group to which the machine learning workspace belongs. :param str workspace_name: The name of the machine learning workspace. """ __args__ = dict() __args__['resourceGroupName'] = resource_group_name __args__['workspaceName'] = workspace_name if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('azure-nextgen:machinelearning:listWorkspaceKeys', __args__, opts=opts, typ=ListWorkspaceKeysResult).value return AwaitableListWorkspaceKeysResult( primary_token=__ret__.primary_token, secondary_token=__ret__.secondary_token)
en
0.866014
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** Workspace authorization keys for a workspace. Primary authorization key for this workspace. Secondary authorization key for this workspace. # pylint: disable=using-constant-test Workspace authorization keys for a workspace. API Version: 2016-04-01. :param str resource_group_name: The name of the resource group to which the machine learning workspace belongs. :param str workspace_name: The name of the machine learning workspace.
1.758427
2
l-system_tree.py
dangbb/3D_L-System_Tree
7
6625824
<gh_stars>1-10 # Filename: l-system_tree.py # Author: <NAME> (@def-pri-pub) # License: BSD 3-Clause (read `./LICENSE` for details) # # This script is the logic for generating a Lindenmayer System tree. It's # needs to be run inside of Blender for it to work. When it's done genrating # you should be given a tree-like structure made out of cylinders and spheres import math import random import bpy from mathutils import Vector, Matrix ### Configuration Options ## # Tree Characteristics ANGLE = 45 # Angle which new branches come off of (in degrees) BRANCH_LENGTH = 10 # Length of parent branch BRANCH_DIVISOR = 1.6 # How much to divide parent branch length by THICKNESS = 0.25 # How thick the branches should be DEPTH = 5 # How many levels to render SOFT_ENDS = True # Add soft ends (spheres) to the branches # Twist at the A grammar TWIST = False # Twist the child branches around the parent branch TWIST_AMOUNT = 45 # How much to twist by # Mesh Resolution VERTICES = 16 # For branches (cylinders) RING_COUNT = 16 # For soft ends (spheres) SEGMENTS = 16 # For soft ends (spheres) # Apply some randomness to the tree VARIATION_MODE = False # apply a random variation to the tree, gives it a more natural feel BRANCH_LENGTH_VARIATION = .5 # How much to vary the branch length TWIST_VARIATION = 15 # How much to vary the twist by ANGLE_VARIATION = 30 # How much to vary the child branche's branch angle by #random.seed(0) # use this to set a random seed # class for storing render state class RenderParams: __slots__ = ( 'max_depth', 'cur_depth', 'branch_length', 'matrix_chain', ) # sets up the Rendering Parameters def __init__(self, branch_length=10, max_depth=5): self.max_depth = max_depth self.cur_depth = 0 self.branch_length = branch_length self.matrix_chain = [Matrix.Identity(4)] # Checks if we are deeper than our current depth or not def depthGood(self): return self.cur_depth < self.max_depth # Multiplies the stored matrx_chain def computedMatrixChain(self): m = self.matrix_chain[0] for i in range(1, len(self.matrix_chain)): m *= self.matrix_chain[i] return m # This is used so that we don't accidentally add more sphere than we need to _soft_ends_set = set() # Makes a branch # branch_length -- a non-negative number, how long each branch should be # world_matrix -- A Matrix that will be where the placement of the branch starts def mkBranch(branch_length, world_matrix): global _soft_ends_set # For the endpoints if SOFT_ENDS: # compute locations a = world_matrix b = world_matrix * Matrix.Translation((0, 0, branch_length)) # Get their tranlations (fronzen) (so we don't double add them) a_loc = a.to_translation().freeze() b_loc = b.to_translation().freeze() # first endpoint if a_loc not in _soft_ends_set: _soft_ends_set.add(a_loc) bpy.ops.mesh.primitive_uv_sphere_add(segments=SEGMENTS, ring_count=RING_COUNT, size=THICKNESS) bpy.context.active_object.matrix_world *= a # second if b_loc not in _soft_ends_set: _soft_ends_set.add(b_loc) bpy.ops.mesh.primitive_uv_sphere_add(segments=SEGMENTS, ring_count=RING_COUNT, size=THICKNESS) bpy.context.active_object.matrix_world *= b # The actual branch mid = world_matrix * Matrix.Translation((0, 0, branch_length / 2)) cylinder = bpy.ops.mesh.primitive_cylinder_add( vertices=VERTICES, radius=THICKNESS, depth=branch_length, ) bpy.context.active_object.matrix_world *= mid # Grammar # A -> BCDE # B -> A # C -> A # D -> A # E -> A # (All these are in the context of having a max render depth # A = Go forward x units, perform B & C, then back x units # B = Turn left 45 degrees, perform A, then turn right 45 degrees # C = Turn right 45 degrees, perform A, then turn left 45 degrees # A - BCDE def A(rp): # Check depth if not rp.depthGood(): return # Record the amounts original_branch_length = rp.branch_length branch_length = rp.branch_length twist_amount = TWIST_AMOUNT # If variations are on, apply some if VARIATION_MODE: branch_length += random.uniform(-BRANCH_LENGTH_VARIATION, BRANCH_LENGTH_VARIATION) twist_amount += random.uniform(-TWIST_VARIATION, TWIST_VARIATION) # Make the branch mkBranch(branch_length, rp.computedMatrixChain()) # Increase distance & twist rp.matrix_chain.append(Matrix.Translation((0, 0, branch_length))) if TWIST: rp.matrix_chain.append(Matrix.Rotation(math.radians(twist_amount), 4, 'Z')) rp.branch_length = branch_length / BRANCH_DIVISOR # Do the other grammars rp.cur_depth += 1 B(rp) C(rp) D(rp) E(rp) rp.cur_depth -= 1 # undo distance increase and twist rp.branch_length = original_branch_length if TWIST: rp.matrix_chain.pop() rp.matrix_chain.pop() # B -> A def B(rp): # Check depth if not rp.depthGood(): return # Set the angle angle = ANGLE if VARIATION_MODE: angle += random.uniform(-ANGLE_VARIATION, ANGLE_VARIATION) # Rotate & go deeper rp.matrix_chain.append(Matrix.Rotation(math.radians(angle), 4, 'X')) A(rp) rp.matrix_chain.pop() # C -> A def C(rp): # Check depth if not rp.depthGood(): return # Set the angle angle = ANGLE if VARIATION_MODE: angle += random.uniform(-ANGLE_VARIATION, ANGLE_VARIATION) # Rotate & go deeper rp.matrix_chain.append(Matrix.Rotation(math.radians(angle), 4, 'Y')) A(rp) rp.matrix_chain.pop() # D -> A def D(rp): # check depth if not rp.depthGood(): return # Set the angle angle = ANGLE if VARIATION_MODE: angle += random.uniform(-ANGLE_VARIATION, ANGLE_VARIATION) # Rotate & go deeper rp.matrix_chain.append(Matrix.Rotation(math.radians(-angle), 4, 'X')) A(rp) rp.matrix_chain.pop() # E -> A def E(rp): # check depth if not rp.depthGood(): return # Set the angle angle = ANGLE if VARIATION_MODE: angle += random.uniform(-ANGLE_VARIATION, ANGLE_VARIATION) # Rotate & go deeper rp.matrix_chain.append(Matrix.Rotation(math.radians(-angle), 4, 'Y')) A(rp) rp.matrix_chain.pop() # render something rp = RenderParams(BRANCH_LENGTH, DEPTH) A(rp)
# Filename: l-system_tree.py # Author: <NAME> (@def-pri-pub) # License: BSD 3-Clause (read `./LICENSE` for details) # # This script is the logic for generating a Lindenmayer System tree. It's # needs to be run inside of Blender for it to work. When it's done genrating # you should be given a tree-like structure made out of cylinders and spheres import math import random import bpy from mathutils import Vector, Matrix ### Configuration Options ## # Tree Characteristics ANGLE = 45 # Angle which new branches come off of (in degrees) BRANCH_LENGTH = 10 # Length of parent branch BRANCH_DIVISOR = 1.6 # How much to divide parent branch length by THICKNESS = 0.25 # How thick the branches should be DEPTH = 5 # How many levels to render SOFT_ENDS = True # Add soft ends (spheres) to the branches # Twist at the A grammar TWIST = False # Twist the child branches around the parent branch TWIST_AMOUNT = 45 # How much to twist by # Mesh Resolution VERTICES = 16 # For branches (cylinders) RING_COUNT = 16 # For soft ends (spheres) SEGMENTS = 16 # For soft ends (spheres) # Apply some randomness to the tree VARIATION_MODE = False # apply a random variation to the tree, gives it a more natural feel BRANCH_LENGTH_VARIATION = .5 # How much to vary the branch length TWIST_VARIATION = 15 # How much to vary the twist by ANGLE_VARIATION = 30 # How much to vary the child branche's branch angle by #random.seed(0) # use this to set a random seed # class for storing render state class RenderParams: __slots__ = ( 'max_depth', 'cur_depth', 'branch_length', 'matrix_chain', ) # sets up the Rendering Parameters def __init__(self, branch_length=10, max_depth=5): self.max_depth = max_depth self.cur_depth = 0 self.branch_length = branch_length self.matrix_chain = [Matrix.Identity(4)] # Checks if we are deeper than our current depth or not def depthGood(self): return self.cur_depth < self.max_depth # Multiplies the stored matrx_chain def computedMatrixChain(self): m = self.matrix_chain[0] for i in range(1, len(self.matrix_chain)): m *= self.matrix_chain[i] return m # This is used so that we don't accidentally add more sphere than we need to _soft_ends_set = set() # Makes a branch # branch_length -- a non-negative number, how long each branch should be # world_matrix -- A Matrix that will be where the placement of the branch starts def mkBranch(branch_length, world_matrix): global _soft_ends_set # For the endpoints if SOFT_ENDS: # compute locations a = world_matrix b = world_matrix * Matrix.Translation((0, 0, branch_length)) # Get their tranlations (fronzen) (so we don't double add them) a_loc = a.to_translation().freeze() b_loc = b.to_translation().freeze() # first endpoint if a_loc not in _soft_ends_set: _soft_ends_set.add(a_loc) bpy.ops.mesh.primitive_uv_sphere_add(segments=SEGMENTS, ring_count=RING_COUNT, size=THICKNESS) bpy.context.active_object.matrix_world *= a # second if b_loc not in _soft_ends_set: _soft_ends_set.add(b_loc) bpy.ops.mesh.primitive_uv_sphere_add(segments=SEGMENTS, ring_count=RING_COUNT, size=THICKNESS) bpy.context.active_object.matrix_world *= b # The actual branch mid = world_matrix * Matrix.Translation((0, 0, branch_length / 2)) cylinder = bpy.ops.mesh.primitive_cylinder_add( vertices=VERTICES, radius=THICKNESS, depth=branch_length, ) bpy.context.active_object.matrix_world *= mid # Grammar # A -> BCDE # B -> A # C -> A # D -> A # E -> A # (All these are in the context of having a max render depth # A = Go forward x units, perform B & C, then back x units # B = Turn left 45 degrees, perform A, then turn right 45 degrees # C = Turn right 45 degrees, perform A, then turn left 45 degrees # A - BCDE def A(rp): # Check depth if not rp.depthGood(): return # Record the amounts original_branch_length = rp.branch_length branch_length = rp.branch_length twist_amount = TWIST_AMOUNT # If variations are on, apply some if VARIATION_MODE: branch_length += random.uniform(-BRANCH_LENGTH_VARIATION, BRANCH_LENGTH_VARIATION) twist_amount += random.uniform(-TWIST_VARIATION, TWIST_VARIATION) # Make the branch mkBranch(branch_length, rp.computedMatrixChain()) # Increase distance & twist rp.matrix_chain.append(Matrix.Translation((0, 0, branch_length))) if TWIST: rp.matrix_chain.append(Matrix.Rotation(math.radians(twist_amount), 4, 'Z')) rp.branch_length = branch_length / BRANCH_DIVISOR # Do the other grammars rp.cur_depth += 1 B(rp) C(rp) D(rp) E(rp) rp.cur_depth -= 1 # undo distance increase and twist rp.branch_length = original_branch_length if TWIST: rp.matrix_chain.pop() rp.matrix_chain.pop() # B -> A def B(rp): # Check depth if not rp.depthGood(): return # Set the angle angle = ANGLE if VARIATION_MODE: angle += random.uniform(-ANGLE_VARIATION, ANGLE_VARIATION) # Rotate & go deeper rp.matrix_chain.append(Matrix.Rotation(math.radians(angle), 4, 'X')) A(rp) rp.matrix_chain.pop() # C -> A def C(rp): # Check depth if not rp.depthGood(): return # Set the angle angle = ANGLE if VARIATION_MODE: angle += random.uniform(-ANGLE_VARIATION, ANGLE_VARIATION) # Rotate & go deeper rp.matrix_chain.append(Matrix.Rotation(math.radians(angle), 4, 'Y')) A(rp) rp.matrix_chain.pop() # D -> A def D(rp): # check depth if not rp.depthGood(): return # Set the angle angle = ANGLE if VARIATION_MODE: angle += random.uniform(-ANGLE_VARIATION, ANGLE_VARIATION) # Rotate & go deeper rp.matrix_chain.append(Matrix.Rotation(math.radians(-angle), 4, 'X')) A(rp) rp.matrix_chain.pop() # E -> A def E(rp): # check depth if not rp.depthGood(): return # Set the angle angle = ANGLE if VARIATION_MODE: angle += random.uniform(-ANGLE_VARIATION, ANGLE_VARIATION) # Rotate & go deeper rp.matrix_chain.append(Matrix.Rotation(math.radians(-angle), 4, 'Y')) A(rp) rp.matrix_chain.pop() # render something rp = RenderParams(BRANCH_LENGTH, DEPTH) A(rp)
en
0.848232
# Filename: l-system_tree.py # Author: <NAME> (@def-pri-pub) # License: BSD 3-Clause (read `./LICENSE` for details) # # This script is the logic for generating a Lindenmayer System tree. It's # needs to be run inside of Blender for it to work. When it's done genrating # you should be given a tree-like structure made out of cylinders and spheres ### Configuration Options ## # Tree Characteristics # Angle which new branches come off of (in degrees) # Length of parent branch # How much to divide parent branch length by # How thick the branches should be # How many levels to render # Add soft ends (spheres) to the branches # Twist at the A grammar # Twist the child branches around the parent branch # How much to twist by # Mesh Resolution # For branches (cylinders) # For soft ends (spheres) # For soft ends (spheres) # Apply some randomness to the tree # apply a random variation to the tree, gives it a more natural feel # How much to vary the branch length # How much to vary the twist by # How much to vary the child branche's branch angle by #random.seed(0) # use this to set a random seed # class for storing render state # sets up the Rendering Parameters # Checks if we are deeper than our current depth or not # Multiplies the stored matrx_chain # This is used so that we don't accidentally add more sphere than we need to # Makes a branch # branch_length -- a non-negative number, how long each branch should be # world_matrix -- A Matrix that will be where the placement of the branch starts # For the endpoints # compute locations # Get their tranlations (fronzen) (so we don't double add them) # first endpoint # second # The actual branch # Grammar # A -> BCDE # B -> A # C -> A # D -> A # E -> A # (All these are in the context of having a max render depth # A = Go forward x units, perform B & C, then back x units # B = Turn left 45 degrees, perform A, then turn right 45 degrees # C = Turn right 45 degrees, perform A, then turn left 45 degrees # A - BCDE # Check depth # Record the amounts # If variations are on, apply some # Make the branch # Increase distance & twist # Do the other grammars # undo distance increase and twist # B -> A # Check depth # Set the angle # Rotate & go deeper # C -> A # Check depth # Set the angle # Rotate & go deeper # D -> A # check depth # Set the angle # Rotate & go deeper # E -> A # check depth # Set the angle # Rotate & go deeper # render something
2.765174
3
lnbits/extensions/lnticket/views_api.py
pseudozach/lnbits-legend
76
6625825
import re from http import HTTPStatus from fastapi import Query from fastapi.params import Depends from starlette.exceptions import HTTPException from lnbits.core.crud import get_user from lnbits.core.services import create_invoice from lnbits.core.views.api import api_payment from lnbits.decorators import WalletTypeInfo, get_key_type from lnbits.extensions.lnticket.models import CreateFormData, CreateTicketData from . import lnticket_ext from .crud import ( create_form, create_ticket, delete_form, delete_ticket, get_form, get_forms, get_ticket, get_tickets, set_ticket_paid, update_form, ) # FORMS @lnticket_ext.get("/api/v1/forms") async def api_forms_get( all_wallets: bool = Query(False), wallet: WalletTypeInfo = Depends(get_key_type) ): wallet_ids = [wallet.wallet.id] if all_wallets: wallet_ids = (await get_user(wallet.wallet.user)).wallet_ids return [form.dict() for form in await get_forms(wallet_ids)] @lnticket_ext.post("/api/v1/forms", status_code=HTTPStatus.CREATED) @lnticket_ext.put("/api/v1/forms/{form_id}") async def api_form_create( data: CreateFormData, form_id=None, wallet: WalletTypeInfo = Depends(get_key_type) ): if form_id: form = await get_form(form_id) if not form: raise HTTPException( status_code=HTTPStatus.NOT_FOUND, detail=f"Form does not exist." ) if form.wallet != wallet.wallet.id: raise HTTPException( status_code=HTTPStatus.FORBIDDEN, detail=f"Not your form." ) form = await update_form(form_id, **data.dict()) else: form = await create_form(data, wallet.wallet) return form.dict() @lnticket_ext.delete("/api/v1/forms/{form_id}") async def api_form_delete(form_id, wallet: WalletTypeInfo = Depends(get_key_type)): form = await get_form(form_id) if not form: raise HTTPException( status_code=HTTPStatus.NOT_FOUND, detail=f"Form does not exist." ) if form.wallet != wallet.wallet.id: raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail=f"Not your form.") await delete_form(form_id) raise HTTPException(status_code=HTTPStatus.NO_CONTENT) #########tickets########## @lnticket_ext.get("/api/v1/tickets") async def api_tickets( all_wallets: bool = Query(False), wallet: WalletTypeInfo = Depends(get_key_type) ): wallet_ids = [wallet.wallet.id] if all_wallets: wallet_ids = (await get_user(wallet.wallet.user)).wallet_ids return [form.dict() for form in await get_tickets(wallet_ids)] @lnticket_ext.post("/api/v1/tickets/{form_id}", status_code=HTTPStatus.CREATED) async def api_ticket_make_ticket(data: CreateTicketData, form_id): form = await get_form(form_id) if not form: raise HTTPException( status_code=HTTPStatus.NOT_FOUND, detail=f"LNTicket does not exist." ) if data.sats < 1: raise HTTPException( status_code=HTTPStatus.NOT_FOUND, detail=f"0 invoices not allowed." ) nwords = len(re.split(r"\s+", data.ltext)) try: payment_hash, payment_request = await create_invoice( wallet_id=form.wallet, amount=data.sats, memo=f"ticket with {nwords} words on {form_id}", extra={"tag": "lnticket"}, ) except Exception as e: raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(e)) ticket = await create_ticket( payment_hash=payment_hash, wallet=form.wallet, data=data ) if not ticket: raise HTTPException( status_code=HTTPStatus.NOT_FOUND, detail="LNTicket could not be fetched." ) return {"payment_hash": payment_hash, "payment_request": payment_request} @lnticket_ext.get("/api/v1/tickets/{payment_hash}", status_code=HTTPStatus.OK) async def api_ticket_send_ticket(payment_hash): ticket = await get_ticket(payment_hash) try: status = await api_payment(payment_hash) if status["paid"]: await set_ticket_paid(payment_hash=payment_hash) return {"paid": True} except Exception: return {"paid": False} return {"paid": False} @lnticket_ext.delete("/api/v1/tickets/{ticket_id}") async def api_ticket_delete(ticket_id, wallet: WalletTypeInfo = Depends(get_key_type)): ticket = await get_ticket(ticket_id) if not ticket: raise HTTPException( status_code=HTTPStatus.NOT_FOUND, detail=f"LNTicket does not exist." ) if ticket.wallet != wallet.wallet.id: raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="Not your ticket.") await delete_ticket(ticket_id) raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
import re from http import HTTPStatus from fastapi import Query from fastapi.params import Depends from starlette.exceptions import HTTPException from lnbits.core.crud import get_user from lnbits.core.services import create_invoice from lnbits.core.views.api import api_payment from lnbits.decorators import WalletTypeInfo, get_key_type from lnbits.extensions.lnticket.models import CreateFormData, CreateTicketData from . import lnticket_ext from .crud import ( create_form, create_ticket, delete_form, delete_ticket, get_form, get_forms, get_ticket, get_tickets, set_ticket_paid, update_form, ) # FORMS @lnticket_ext.get("/api/v1/forms") async def api_forms_get( all_wallets: bool = Query(False), wallet: WalletTypeInfo = Depends(get_key_type) ): wallet_ids = [wallet.wallet.id] if all_wallets: wallet_ids = (await get_user(wallet.wallet.user)).wallet_ids return [form.dict() for form in await get_forms(wallet_ids)] @lnticket_ext.post("/api/v1/forms", status_code=HTTPStatus.CREATED) @lnticket_ext.put("/api/v1/forms/{form_id}") async def api_form_create( data: CreateFormData, form_id=None, wallet: WalletTypeInfo = Depends(get_key_type) ): if form_id: form = await get_form(form_id) if not form: raise HTTPException( status_code=HTTPStatus.NOT_FOUND, detail=f"Form does not exist." ) if form.wallet != wallet.wallet.id: raise HTTPException( status_code=HTTPStatus.FORBIDDEN, detail=f"Not your form." ) form = await update_form(form_id, **data.dict()) else: form = await create_form(data, wallet.wallet) return form.dict() @lnticket_ext.delete("/api/v1/forms/{form_id}") async def api_form_delete(form_id, wallet: WalletTypeInfo = Depends(get_key_type)): form = await get_form(form_id) if not form: raise HTTPException( status_code=HTTPStatus.NOT_FOUND, detail=f"Form does not exist." ) if form.wallet != wallet.wallet.id: raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail=f"Not your form.") await delete_form(form_id) raise HTTPException(status_code=HTTPStatus.NO_CONTENT) #########tickets########## @lnticket_ext.get("/api/v1/tickets") async def api_tickets( all_wallets: bool = Query(False), wallet: WalletTypeInfo = Depends(get_key_type) ): wallet_ids = [wallet.wallet.id] if all_wallets: wallet_ids = (await get_user(wallet.wallet.user)).wallet_ids return [form.dict() for form in await get_tickets(wallet_ids)] @lnticket_ext.post("/api/v1/tickets/{form_id}", status_code=HTTPStatus.CREATED) async def api_ticket_make_ticket(data: CreateTicketData, form_id): form = await get_form(form_id) if not form: raise HTTPException( status_code=HTTPStatus.NOT_FOUND, detail=f"LNTicket does not exist." ) if data.sats < 1: raise HTTPException( status_code=HTTPStatus.NOT_FOUND, detail=f"0 invoices not allowed." ) nwords = len(re.split(r"\s+", data.ltext)) try: payment_hash, payment_request = await create_invoice( wallet_id=form.wallet, amount=data.sats, memo=f"ticket with {nwords} words on {form_id}", extra={"tag": "lnticket"}, ) except Exception as e: raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(e)) ticket = await create_ticket( payment_hash=payment_hash, wallet=form.wallet, data=data ) if not ticket: raise HTTPException( status_code=HTTPStatus.NOT_FOUND, detail="LNTicket could not be fetched." ) return {"payment_hash": payment_hash, "payment_request": payment_request} @lnticket_ext.get("/api/v1/tickets/{payment_hash}", status_code=HTTPStatus.OK) async def api_ticket_send_ticket(payment_hash): ticket = await get_ticket(payment_hash) try: status = await api_payment(payment_hash) if status["paid"]: await set_ticket_paid(payment_hash=payment_hash) return {"paid": True} except Exception: return {"paid": False} return {"paid": False} @lnticket_ext.delete("/api/v1/tickets/{ticket_id}") async def api_ticket_delete(ticket_id, wallet: WalletTypeInfo = Depends(get_key_type)): ticket = await get_ticket(ticket_id) if not ticket: raise HTTPException( status_code=HTTPStatus.NOT_FOUND, detail=f"LNTicket does not exist." ) if ticket.wallet != wallet.wallet.id: raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="Not your ticket.") await delete_ticket(ticket_id) raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
de
0.442539
# FORMS #########tickets##########
2.019866
2
core/acl_old.py
Caledor/dl
22
6625826
<gh_stars>10-100 import sys from core.timeline import now, Timeline import re do_act = None def acl_func_str(acl): global do_act s = acl_str(acl_build(acl)) exec(s, globals()) # return do_act_list, s do_act = do_act_list return s, do_act_list class Acl_Action: INDENT = " " PREP = """ try: {act} = self.{act} except Exception: raise AttributeError('{act} is not an action')""" ACT = """{indent}if {act}({args}): {indent} return '{act}'""" NONE = "{indent}return 0" QUEUE_ACT = """{indent}Acl_Control.AQU.append(({act}, compile('{cond}', '<string>', 'eval')))""" dragon_act = re.compile(r'dragon(form)?.act\(["\']([A-Za-z \*\+\d]+)["\']\)') def __init__(self, action): self._act = None self.args = None if action.startswith("dragon"): self.action = "dragonform" res = self.dragon_act.match(action) if res: self.args = res.group(2) else: self.action = action self.depth = 0 def __repr__(self): return self.action def prep(self, adv): if self.action == "dragonform" and self.args is not None: self._act = lambda: adv.dragonform.act(self.args) else: self._act = lambda: getattr(adv, self.action)() def do(self): return self._act() def prepare(self): if self.action is None: return False return self.PREP.format(act=self.action) def act(self): if self.action is None: return self.NONE.format(indent=self.INDENT * self.depth) return self.ACT.format( act=self.action, args=self.args or "", indent=self.INDENT * self.depth ) def queue_act(self, cond, depth_mod=0): if self.action is None: raise ValueError("No actions queued") return self.QUEUE_ACT.format( act=self.action, args=self.arguments, cond=cond, indent=self.INDENT * (self.depth + depth_mod), ) class Acl_Condition: banned = re.compile( r"(exec|eval|compile|setattr|delattr|memoryview|property|globals|locals|open|print|__[a-zA-Z]+__).*" ) banned_repl = "True" assignment = re.compile(r"([^=><!])=([^=])") assignment_repl = lambda s: s[1] + "==" + s[2] @staticmethod def sanitize_qwe_and_his_chunch_legs(condition): condition = Acl_Condition.banned.sub(Acl_Condition.banned_repl, condition) condition = Acl_Condition.assignment.sub( Acl_Condition.assignment_repl, condition ) return condition def __init__(self, condition): self.condition = Acl_Condition.sanitize_qwe_and_his_chunch_legs(condition) # self.condition = condition def prep(self): self._cond = compile(self.condition, "<string>", "eval") def eval(self): return self.condition is None or eval(self.condition, Acl_Control.CTX) class Acl_Control: INDENT = " " IF = """{indent}if {cond}: {block}""" ELIF = """{indent}elif {cond}: {block}""" ELSE = """{indent}else: {block}""" QUEUE = """{indent}if len(Acl_Control.AQU)==0 and {cond}: {block}""" AQU = [] CTX = None def __init__(self, condition, depth=0): self.conditions = [(Acl_Condition(condition), [])] self._act_cond = None self.depth = depth def add_action(self, action): action.depth = self.depth + 1 self.conditions[-1][-1].append(action) def add_condition(self, condition, is_else=False): self.conditions.append((Acl_Condition(condition), [])) def __repr__(self): return "\n".join(f"\n<{cond}> {acts}" for cond, acts in self.conditions) def prep(self, adv): Acl_Control.AQU = [] for cond, acts in self.conditions: cond.prep() for a in acts: a.prep(adv) if len(self.conditions) == 1: cond, acts = self.conditions[0] if len(acts) == 1 and isinstance(acts[0], Acl_Action): self._act_cond = acts[0], cond def do(self): for cond, acts in self.conditions: if cond.eval(): for a in acts: if a.do(): return True break return False @staticmethod def set_ctx(self, e): this = self pin, dname, dstat, didx = e.pin, e.dname, e.dstat, e.didx prev = self.action.getprev() seq = didx if dname[0] == "x" else 0 if dstat == -2 else -1 cancel = pin == "x" or pin == "fs" x = didx if pin == "x" else 0 fsc = pin == "fs" s = ( int(pin[1]) if (pin[0] == "s" and pin[1].isdigit()) or pin[-2:] == "-x" else 0 ) sp = dname if pin == "sp" else 0 prep = pin == "prep" sim_duration = self.duration Acl_Control.CTX = locals() def __call__(self, adv, e): Acl_Control.set_ctx(adv, e) if len(Acl_Control.AQU) > 0: next_act, next_cond = Acl_Control.AQU[0] if next_cond.eval() and next_act.do(): return Acl_Control.AQU.pop(0) self.do() def prepare(self): prep_list = [] for _, acts in self.conditions: prep_list.extend([a.prepare() for a in acts if a.prepare()]) return "\n".join(prep_list) def act(self): act_list = [] for idx, value in enumerate(self.conditions): cond, acts = value cond = cond.condition if len(acts) == 0: continue if cond.startswith("QUEUE"): cond = "True" if len(cond) < 6 else cond[6:] pattern = self.QUEUE block = [a.queue_act("True") for a in acts] block.append( "{indent} return 'queued'".format( indent=self.INDENT * self.depth ) ) else: if idx == 0: pattern = self.IF elif cond != "ELSE": pattern = self.ELIF else: pattern = self.ELSE block = [a.act() for a in acts] if self.depth == 0: act_list = block else: act_list.append( pattern.format( cond=cond, block="\n".join(block), indent=self.INDENT * self.depth, ) ) return "\n".join(act_list) def queue_act(self, bolb): act_list = [] for value in self.conditions: cond, acts = value cond = cond.condition if len(acts) == 0: continue act_list = [a.queue_act(cond, depth_mod=-1) for a in acts] return "\n".join(act_list) class Acl_Queue(Acl_Control): def do(self): for cond, acts in self.conditions: if len(Acl_Control.AQU) == 0 and cond.eval(): for a in acts: if isinstance(a, Acl_Action): Acl_Control.AQU.append((a._act, None)) elif a._act_cond: Acl_Control.AQU.append(a._act_cond) return False def acl_build(acl): root = Acl_Control("True") node_stack = [root] real_lines = [] for line in acl.split("\n"): line = line.strip().replace("`", "") if len(line) > 0 and line[0] != "#": if ";" in line: for s in line.split(";"): s = s.strip().replace("`", "") if len(s) > 0 and s[0] != "#": real_lines.append(s) else: real_lines.append(line) for line in real_lines: upper = line.upper() if upper.startswith("IF "): node = Acl_Control(line[3:]) node_stack[-1].add_action(node) node_stack.append(node) elif upper.startswith("QUEUE"): cond = "True" if upper == "QUEUE" else line[6:] node = Acl_Queue(cond) node_stack[-1].add_action(node) node_stack.append(node) elif upper.startswith("ELIF "): node_stack[-1].add_condition(line[5:]) elif upper.startswith("ELSE"): node_stack[-1].add_condition("True") elif upper.startswith("END"): node_stack.pop() else: parts = [l.strip() for l in line.split(",")] if len(parts) == 1 or len(parts[1]) == 0: action = parts[0] node = Acl_Action(action) node_stack[-1].add_action(node) else: action = parts[0] condition = parts[1] node = Acl_Control(condition) node_stack[-1].add_action(node) node.add_action(Acl_Action(action)) return root def acl_str(root): acl_base = """ def do_act_list(self, e): this = self pin, dname, dstat, didx = e.pin, e.dname, e.dstat, e.didx prev = self.action.getprev() seq = didx if dname[0] == 'x' else 0 if dstat == -2 else -1 cancel = pin =='x' or pin == 'fs' x = didx if pin =='x' else 0 fsc = pin =='fs' s = int(pin[1]) if (pin[0] == 's' and pin[1] in ('1', '2', '3')) or pin[-2:] == '-x' else 0 sp = dname if pin == 'sp' else 0 prep = pin == 'prep' sim_duration = self.duration {act_prep_block} if len(Acl_Control.AQU) > 0: next_act, next_cond = Acl_Control.AQU[0] if eval(next_cond) and next_act(): Acl_Control.AQU.pop(0) return 'queue' {act_cond_block} return 0""" acl_string = acl_base.format( act_prep_block=root.prepare(), act_cond_block=root.act() ) return acl_string
import sys from core.timeline import now, Timeline import re do_act = None def acl_func_str(acl): global do_act s = acl_str(acl_build(acl)) exec(s, globals()) # return do_act_list, s do_act = do_act_list return s, do_act_list class Acl_Action: INDENT = " " PREP = """ try: {act} = self.{act} except Exception: raise AttributeError('{act} is not an action')""" ACT = """{indent}if {act}({args}): {indent} return '{act}'""" NONE = "{indent}return 0" QUEUE_ACT = """{indent}Acl_Control.AQU.append(({act}, compile('{cond}', '<string>', 'eval')))""" dragon_act = re.compile(r'dragon(form)?.act\(["\']([A-Za-z \*\+\d]+)["\']\)') def __init__(self, action): self._act = None self.args = None if action.startswith("dragon"): self.action = "dragonform" res = self.dragon_act.match(action) if res: self.args = res.group(2) else: self.action = action self.depth = 0 def __repr__(self): return self.action def prep(self, adv): if self.action == "dragonform" and self.args is not None: self._act = lambda: adv.dragonform.act(self.args) else: self._act = lambda: getattr(adv, self.action)() def do(self): return self._act() def prepare(self): if self.action is None: return False return self.PREP.format(act=self.action) def act(self): if self.action is None: return self.NONE.format(indent=self.INDENT * self.depth) return self.ACT.format( act=self.action, args=self.args or "", indent=self.INDENT * self.depth ) def queue_act(self, cond, depth_mod=0): if self.action is None: raise ValueError("No actions queued") return self.QUEUE_ACT.format( act=self.action, args=self.arguments, cond=cond, indent=self.INDENT * (self.depth + depth_mod), ) class Acl_Condition: banned = re.compile( r"(exec|eval|compile|setattr|delattr|memoryview|property|globals|locals|open|print|__[a-zA-Z]+__).*" ) banned_repl = "True" assignment = re.compile(r"([^=><!])=([^=])") assignment_repl = lambda s: s[1] + "==" + s[2] @staticmethod def sanitize_qwe_and_his_chunch_legs(condition): condition = Acl_Condition.banned.sub(Acl_Condition.banned_repl, condition) condition = Acl_Condition.assignment.sub( Acl_Condition.assignment_repl, condition ) return condition def __init__(self, condition): self.condition = Acl_Condition.sanitize_qwe_and_his_chunch_legs(condition) # self.condition = condition def prep(self): self._cond = compile(self.condition, "<string>", "eval") def eval(self): return self.condition is None or eval(self.condition, Acl_Control.CTX) class Acl_Control: INDENT = " " IF = """{indent}if {cond}: {block}""" ELIF = """{indent}elif {cond}: {block}""" ELSE = """{indent}else: {block}""" QUEUE = """{indent}if len(Acl_Control.AQU)==0 and {cond}: {block}""" AQU = [] CTX = None def __init__(self, condition, depth=0): self.conditions = [(Acl_Condition(condition), [])] self._act_cond = None self.depth = depth def add_action(self, action): action.depth = self.depth + 1 self.conditions[-1][-1].append(action) def add_condition(self, condition, is_else=False): self.conditions.append((Acl_Condition(condition), [])) def __repr__(self): return "\n".join(f"\n<{cond}> {acts}" for cond, acts in self.conditions) def prep(self, adv): Acl_Control.AQU = [] for cond, acts in self.conditions: cond.prep() for a in acts: a.prep(adv) if len(self.conditions) == 1: cond, acts = self.conditions[0] if len(acts) == 1 and isinstance(acts[0], Acl_Action): self._act_cond = acts[0], cond def do(self): for cond, acts in self.conditions: if cond.eval(): for a in acts: if a.do(): return True break return False @staticmethod def set_ctx(self, e): this = self pin, dname, dstat, didx = e.pin, e.dname, e.dstat, e.didx prev = self.action.getprev() seq = didx if dname[0] == "x" else 0 if dstat == -2 else -1 cancel = pin == "x" or pin == "fs" x = didx if pin == "x" else 0 fsc = pin == "fs" s = ( int(pin[1]) if (pin[0] == "s" and pin[1].isdigit()) or pin[-2:] == "-x" else 0 ) sp = dname if pin == "sp" else 0 prep = pin == "prep" sim_duration = self.duration Acl_Control.CTX = locals() def __call__(self, adv, e): Acl_Control.set_ctx(adv, e) if len(Acl_Control.AQU) > 0: next_act, next_cond = Acl_Control.AQU[0] if next_cond.eval() and next_act.do(): return Acl_Control.AQU.pop(0) self.do() def prepare(self): prep_list = [] for _, acts in self.conditions: prep_list.extend([a.prepare() for a in acts if a.prepare()]) return "\n".join(prep_list) def act(self): act_list = [] for idx, value in enumerate(self.conditions): cond, acts = value cond = cond.condition if len(acts) == 0: continue if cond.startswith("QUEUE"): cond = "True" if len(cond) < 6 else cond[6:] pattern = self.QUEUE block = [a.queue_act("True") for a in acts] block.append( "{indent} return 'queued'".format( indent=self.INDENT * self.depth ) ) else: if idx == 0: pattern = self.IF elif cond != "ELSE": pattern = self.ELIF else: pattern = self.ELSE block = [a.act() for a in acts] if self.depth == 0: act_list = block else: act_list.append( pattern.format( cond=cond, block="\n".join(block), indent=self.INDENT * self.depth, ) ) return "\n".join(act_list) def queue_act(self, bolb): act_list = [] for value in self.conditions: cond, acts = value cond = cond.condition if len(acts) == 0: continue act_list = [a.queue_act(cond, depth_mod=-1) for a in acts] return "\n".join(act_list) class Acl_Queue(Acl_Control): def do(self): for cond, acts in self.conditions: if len(Acl_Control.AQU) == 0 and cond.eval(): for a in acts: if isinstance(a, Acl_Action): Acl_Control.AQU.append((a._act, None)) elif a._act_cond: Acl_Control.AQU.append(a._act_cond) return False def acl_build(acl): root = Acl_Control("True") node_stack = [root] real_lines = [] for line in acl.split("\n"): line = line.strip().replace("`", "") if len(line) > 0 and line[0] != "#": if ";" in line: for s in line.split(";"): s = s.strip().replace("`", "") if len(s) > 0 and s[0] != "#": real_lines.append(s) else: real_lines.append(line) for line in real_lines: upper = line.upper() if upper.startswith("IF "): node = Acl_Control(line[3:]) node_stack[-1].add_action(node) node_stack.append(node) elif upper.startswith("QUEUE"): cond = "True" if upper == "QUEUE" else line[6:] node = Acl_Queue(cond) node_stack[-1].add_action(node) node_stack.append(node) elif upper.startswith("ELIF "): node_stack[-1].add_condition(line[5:]) elif upper.startswith("ELSE"): node_stack[-1].add_condition("True") elif upper.startswith("END"): node_stack.pop() else: parts = [l.strip() for l in line.split(",")] if len(parts) == 1 or len(parts[1]) == 0: action = parts[0] node = Acl_Action(action) node_stack[-1].add_action(node) else: action = parts[0] condition = parts[1] node = Acl_Control(condition) node_stack[-1].add_action(node) node.add_action(Acl_Action(action)) return root def acl_str(root): acl_base = """ def do_act_list(self, e): this = self pin, dname, dstat, didx = e.pin, e.dname, e.dstat, e.didx prev = self.action.getprev() seq = didx if dname[0] == 'x' else 0 if dstat == -2 else -1 cancel = pin =='x' or pin == 'fs' x = didx if pin =='x' else 0 fsc = pin =='fs' s = int(pin[1]) if (pin[0] == 's' and pin[1] in ('1', '2', '3')) or pin[-2:] == '-x' else 0 sp = dname if pin == 'sp' else 0 prep = pin == 'prep' sim_duration = self.duration {act_prep_block} if len(Acl_Control.AQU) > 0: next_act, next_cond = Acl_Control.AQU[0] if eval(next_cond) and next_act(): Acl_Control.AQU.pop(0) return 'queue' {act_cond_block} return 0""" acl_string = acl_base.format( act_prep_block=root.prepare(), act_cond_block=root.act() ) return acl_string
en
0.340939
# return do_act_list, s try: {act} = self.{act} except Exception: raise AttributeError('{act} is not an action') {indent}if {act}({args}): {indent} return '{act}' {indent}Acl_Control.AQU.append(({act}, compile('{cond}', '<string>', 'eval'))) # self.condition = condition {indent}if {cond}: {block} {indent}elif {cond}: {block} {indent}else: {block} {indent}if len(Acl_Control.AQU)==0 and {cond}: {block} def do_act_list(self, e): this = self pin, dname, dstat, didx = e.pin, e.dname, e.dstat, e.didx prev = self.action.getprev() seq = didx if dname[0] == 'x' else 0 if dstat == -2 else -1 cancel = pin =='x' or pin == 'fs' x = didx if pin =='x' else 0 fsc = pin =='fs' s = int(pin[1]) if (pin[0] == 's' and pin[1] in ('1', '2', '3')) or pin[-2:] == '-x' else 0 sp = dname if pin == 'sp' else 0 prep = pin == 'prep' sim_duration = self.duration {act_prep_block} if len(Acl_Control.AQU) > 0: next_act, next_cond = Acl_Control.AQU[0] if eval(next_cond) and next_act(): Acl_Control.AQU.pop(0) return 'queue' {act_cond_block} return 0
2.915019
3
pimgen.py
rfrandse/phosphor-inventory-manager
0
6625827
#!/usr/bin/env python '''Phosphor Inventory Manager YAML parser and code generator. The parser workflow is broken down as follows: 1 - Import YAML files as native python type(s) instance(s). 2 - Create an instance of the Everything class from the native python type instance(s) with the Everything.load method. 3 - The Everything class constructor orchestrates conversion of the native python type(s) instances(s) to render helper types. Each render helper type constructor imports its attributes from the native python type(s) instances(s). 4 - Present the converted YAML to the command processing method requested by the script user. ''' import sys import os import argparse import subprocess import yaml import mako.lookup import sdbusplus.property from sdbusplus.namedelement import NamedElement from sdbusplus.renderer import Renderer # Global busname for use within classes where necessary busname = "xyz.openbmc_project.Inventory.Manager" def cppTypeName(yaml_type): ''' Convert yaml types to cpp types.''' return sdbusplus.property.Property(type=yaml_type).cppTypeName class InterfaceComposite(object): '''Compose interface properties.''' def __init__(self, dict): self.dict = dict def properties(self, interface): return self.dict[interface] def interfaces(self): return self.dict.keys() def names(self, interface): names = [] if self.dict[interface]: names = [x["name"] for x in self.dict[interface]] return names class Interface(list): '''Provide various interface transformations.''' def __init__(self, iface): super(Interface, self).__init__(iface.split('.')) def namespace(self): '''Represent as an sdbusplus namespace.''' return '::'.join(['sdbusplus'] + self[:-1] + ['server', self[-1]]) def header(self): '''Represent as an sdbusplus server binding header.''' return os.sep.join(self + ['server.hpp']) def __str__(self): return '.'.join(self) class Indent(object): '''Help templates be depth agnostic.''' def __init__(self, depth=0): self.depth = depth def __add__(self, depth): return Indent(self.depth + depth) def __call__(self, depth): '''Render an indent at the current depth plus depth.''' return 4*' '*(depth + self.depth) class Template(NamedElement): '''Associate a template name with its namespace.''' def __init__(self, **kw): self.namespace = kw.pop('namespace', []) super(Template, self).__init__(**kw) def qualified(self): return '::'.join(self.namespace + [self.name]) class FixBool(object): '''Un-capitalize booleans.''' def __call__(self, arg): return '{0}'.format(arg.lower()) class Quote(object): '''Decorate an argument by quoting it.''' def __call__(self, arg): return '"{0}"'.format(arg) class Cast(object): '''Decorate an argument by casting it.''' def __init__(self, cast, target): '''cast is the cast type (static, const, etc...). target is the cast target type.''' self.cast = cast self.target = target def __call__(self, arg): return '{0}_cast<{1}>({2})'.format(self.cast, self.target, arg) class Literal(object): '''Decorate an argument with a literal operator.''' integer_types = [ 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64' ] def __init__(self, type): self.type = type def __call__(self, arg): if 'uint' in self.type: arg = '{0}ull'.format(arg) elif 'int' in self.type: arg = '{0}ll'.format(arg) if self.type in self.integer_types: return Cast('static', '{0}_t'.format(self.type))(arg) if self.type == 'string': return '{0}s'.format(arg) return arg class Argument(NamedElement, Renderer): '''Define argument type inteface.''' def __init__(self, **kw): self.type = kw.pop('type', None) super(Argument, self).__init__(**kw) def argument(self, loader, indent): raise NotImplementedError class TrivialArgument(Argument): '''Non-array type arguments.''' def __init__(self, **kw): self.value = kw.pop('value') self.decorators = kw.pop('decorators', []) if kw.get('type', None) == 'string': self.decorators.insert(0, Quote()) if kw.get('type', None) == 'boolean': self.decorators.insert(0, FixBool()) super(TrivialArgument, self).__init__(**kw) def argument(self, loader, indent): a = str(self.value) for d in self.decorators: a = d(a) return a class InitializerList(Argument): '''Initializer list arguments.''' def __init__(self, **kw): self.values = kw.pop('values') super(InitializerList, self).__init__(**kw) def argument(self, loader, indent): return self.render( loader, 'argument.mako.cpp', arg=self, indent=indent) class DbusSignature(Argument): '''DBus signature arguments.''' def __init__(self, **kw): self.sig = {x: y for x, y in kw.iteritems()} kw.clear() super(DbusSignature, self).__init__(**kw) def argument(self, loader, indent): return self.render( loader, 'signature.mako.cpp', signature=self, indent=indent) class MethodCall(Argument): '''Render syntatically correct c++ method calls.''' def __init__(self, **kw): self.namespace = kw.pop('namespace', []) self.templates = kw.pop('templates', []) self.args = kw.pop('args', []) super(MethodCall, self).__init__(**kw) def call(self, loader, indent): return self.render( loader, 'method.mako.cpp', method=self, indent=indent) def argument(self, loader, indent): return self.call(loader, indent) class Vector(MethodCall): '''Convenience type for vectors.''' def __init__(self, **kw): kw['name'] = 'vector' kw['namespace'] = ['std'] kw['args'] = [InitializerList(values=kw.pop('args'))] super(Vector, self).__init__(**kw) class Filter(MethodCall): '''Convenience type for filters''' def __init__(self, **kw): kw['name'] = 'make_filter' super(Filter, self).__init__(**kw) class Action(MethodCall): '''Convenience type for actions''' def __init__(self, **kw): kw['name'] = 'make_action' super(Action, self).__init__(**kw) class PathCondition(MethodCall): '''Convenience type for path conditions''' def __init__(self, **kw): kw['name'] = 'make_path_condition' super(PathCondition, self).__init__(**kw) class GetProperty(MethodCall): '''Convenience type for getting inventory properties''' def __init__(self, **kw): kw['name'] = 'make_get_property' super(GetProperty, self).__init__(**kw) class CreateObjects(MethodCall): '''Assemble a createObjects functor.''' def __init__(self, **kw): objs = [] for path, interfaces in kw.pop('objs').iteritems(): key_o = TrivialArgument( value=path, type='string', decorators=[Literal('string')]) value_i = [] for interface, properties, in interfaces.iteritems(): key_i = TrivialArgument(value=interface, type='string') value_p = [] if properties: for prop, value in properties.iteritems(): key_p = TrivialArgument(value=prop, type='string') value_v = TrivialArgument( decorators=[Literal(value.get('type', None))], **value) value_p.append(InitializerList(values=[key_p, value_v])) value_p = InitializerList(values=value_p) value_i.append(InitializerList(values=[key_i, value_p])) value_i = InitializerList(values=value_i) objs.append(InitializerList(values=[key_o, value_i])) kw['args'] = [InitializerList(values=objs)] kw['namespace'] = ['functor'] super(CreateObjects, self).__init__(**kw) class DestroyObjects(MethodCall): '''Assemble a destroyObject functor.''' def __init__(self, **kw): values = [{'value': x, 'type': 'string'} for x in kw.pop('paths')] conditions = [ Event.functor_map[ x['name']](**x) for x in kw.pop('conditions', [])] conditions = [PathCondition(args=[x]) for x in conditions] args = [InitializerList( values=[TrivialArgument(**x) for x in values])] args.append(InitializerList(values=conditions)) kw['args'] = args kw['namespace'] = ['functor'] super(DestroyObjects, self).__init__(**kw) class SetProperty(MethodCall): '''Assemble a setProperty functor.''' def __init__(self, **kw): args = [] value = kw.pop('value') prop = kw.pop('property') iface = kw.pop('interface') iface = Interface(iface) namespace = iface.namespace().split('::')[:-1] name = iface[-1] t = Template(namespace=namespace, name=iface[-1]) member = '&%s' % '::'.join( namespace + [name, NamedElement(name=prop).camelCase]) member_type = cppTypeName(value['type']) member_cast = '{0} ({1}::*)({0})'.format(member_type, t.qualified()) paths = [{'value': x, 'type': 'string'} for x in kw.pop('paths')] args.append(InitializerList( values=[TrivialArgument(**x) for x in paths])) conditions = [ Event.functor_map[ x['name']](**x) for x in kw.pop('conditions', [])] conditions = [PathCondition(args=[x]) for x in conditions] args.append(InitializerList(values=conditions)) args.append(TrivialArgument(value=str(iface), type='string')) args.append(TrivialArgument( value=member, decorators=[Cast('static', member_cast)])) args.append(TrivialArgument(**value)) kw['templates'] = [Template(name=name, namespace=namespace)] kw['args'] = args kw['namespace'] = ['functor'] super(SetProperty, self).__init__(**kw) class PropertyChanged(MethodCall): '''Assemble a propertyChanged functor.''' def __init__(self, **kw): args = [] args.append(TrivialArgument(value=kw.pop('interface'), type='string')) args.append(TrivialArgument(value=kw.pop('property'), type='string')) args.append(TrivialArgument( decorators=[ Literal(kw['value'].get('type', None))], **kw.pop('value'))) kw['args'] = args kw['namespace'] = ['functor'] super(PropertyChanged, self).__init__(**kw) class PropertyIs(MethodCall): '''Assemble a propertyIs functor.''' def __init__(self, **kw): args = [] path = kw.pop('path', None) if not path: path = TrivialArgument(value='nullptr') else: path = TrivialArgument(value=path, type='string') args.append(path) iface = TrivialArgument(value=kw.pop('interface'), type='string') args.append(iface) prop = TrivialArgument(value=kw.pop('property'), type='string') args.append(prop) args.append(TrivialArgument( decorators=[ Literal(kw['value'].get('type', None))], **kw.pop('value'))) service = kw.pop('service', None) if service: args.append(TrivialArgument(value=service, type='string')) dbusMember = kw.pop('dbusMember', None) if dbusMember: # Inventory manager's service name is required if not service or service != busname: args.append(TrivialArgument(value=busname, type='string')) gpArgs = [] gpArgs.append(path) gpArgs.append(iface) # Prepend '&' and append 'getPropertyByName' function on dbusMember gpArgs.append(TrivialArgument( value='&'+dbusMember+'::getPropertyByName')) gpArgs.append(prop) fArg = MethodCall( name='getProperty', namespace=['functor'], templates=[Template( name=dbusMember, namespace=[])], args=gpArgs) # Append getProperty functor args.append(GetProperty( templates=[Template( name=dbusMember+'::PropertiesVariant', namespace=[])], args=[fArg])) kw['args'] = args kw['namespace'] = ['functor'] super(PropertyIs, self).__init__(**kw) class Event(MethodCall): '''Assemble an inventory manager event.''' functor_map = { 'destroyObjects': DestroyObjects, 'createObjects': CreateObjects, 'propertyChangedTo': PropertyChanged, 'propertyIs': PropertyIs, 'setProperty': SetProperty, } def __init__(self, **kw): self.summary = kw.pop('name') filters = [ self.functor_map[x['name']](**x) for x in kw.pop('filters', [])] filters = [Filter(args=[x]) for x in filters] filters = Vector( templates=[Template(name='Filter', namespace=[])], args=filters) event = MethodCall( name='make_shared', namespace=['std'], templates=[Template( name=kw.pop('event'), namespace=kw.pop('event_namespace', []))], args=kw.pop('event_args', []) + [filters]) events = Vector( templates=[Template(name='EventBasePtr', namespace=[])], args=[event]) action_type = Template(name='Action', namespace=[]) action_args = [ self.functor_map[x['name']](**x) for x in kw.pop('actions', [])] action_args = [Action(args=[x]) for x in action_args] actions = Vector( templates=[action_type], args=action_args) kw['name'] = 'make_tuple' kw['namespace'] = ['std'] kw['args'] = [events, actions] super(Event, self).__init__(**kw) class MatchEvent(Event): '''Associate one or more dbus signal match signatures with a filter.''' def __init__(self, **kw): kw['event'] = 'DbusSignal' kw['event_namespace'] = [] kw['event_args'] = [ DbusSignature(**x) for x in kw.pop('signatures', [])] super(MatchEvent, self).__init__(**kw) class StartupEvent(Event): '''Assemble a startup event.''' def __init__(self, **kw): kw['event'] = 'StartupEvent' kw['event_namespace'] = [] super(StartupEvent, self).__init__(**kw) class Everything(Renderer): '''Parse/render entry point.''' class_map = { 'match': MatchEvent, 'startup': StartupEvent, } @staticmethod def load(args): # Aggregate all the event YAML in the events.d directory # into a single list of events. events = [] events_dir = os.path.join(args.inputdir, 'events.d') if os.path.exists(events_dir): yaml_files = filter( lambda x: x.endswith('.yaml'), os.listdir(events_dir)) for x in yaml_files: with open(os.path.join(events_dir, x), 'r') as fd: for e in yaml.safe_load(fd.read()).get('events', {}): events.append(e) interfaces, interface_composite = Everything.get_interfaces( args.ifacesdir) extra_interfaces, extra_interface_composite = \ Everything.get_interfaces( os.path.join(args.inputdir, 'extra_interfaces.d')) interface_composite.update(extra_interface_composite) interface_composite = InterfaceComposite(interface_composite) # Update busname if configured differenly than the default busname = args.busname return Everything( *events, interfaces=interfaces + extra_interfaces, interface_composite=interface_composite) @staticmethod def get_interfaces(targetdir): '''Scan the interfaces directory for interfaces that PIM can create.''' yaml_files = [] interfaces = [] interface_composite = {} if targetdir and os.path.exists(targetdir): for directory, _, files in os.walk(targetdir): if not files: continue yaml_files += map( lambda f: os.path.relpath( os.path.join(directory, f), targetdir), filter(lambda f: f.endswith('.interface.yaml'), files)) for y in yaml_files: # parse only phosphor dbus related interface files if not y.startswith('xyz'): continue with open(os.path.join(targetdir, y)) as fd: i = y.replace('.interface.yaml', '').replace(os.sep, '.') # PIM can't create interfaces with methods. parsed = yaml.safe_load(fd.read()) if parsed.get('methods', None): continue # Cereal can't understand the type sdbusplus::object_path. This # type is a wrapper around std::string. Ignore interfaces having # a property of this type for now. The only interface that has a # property of this type now is xyz.openbmc_project.Association, # which is an unused interface. No inventory objects implement # this interface. # TODO via openbmc/openbmc#2123 : figure out how to make Cereal # understand sdbusplus::object_path. properties = parsed.get('properties', None) if properties: if any('path' in p['type'] for p in properties): continue interface_composite[i] = properties interfaces.append(i) return interfaces, interface_composite def __init__(self, *a, **kw): self.interfaces = \ [Interface(x) for x in kw.pop('interfaces', [])] self.interface_composite = \ kw.pop('interface_composite', {}) self.events = [ self.class_map[x['type']](**x) for x in a] super(Everything, self).__init__(**kw) def generate_cpp(self, loader): '''Render the template with the provided events and interfaces.''' with open(os.path.join( args.outputdir, 'generated.cpp'), 'w') as fd: fd.write( self.render( loader, 'generated.mako.cpp', events=self.events, interfaces=self.interfaces, indent=Indent())) def generate_serialization(self, loader): with open(os.path.join( args.outputdir, 'gen_serialization.hpp'), 'w') as fd: fd.write( self.render( loader, 'gen_serialization.mako.hpp', interfaces=self.interfaces, interface_composite=self.interface_composite)) if __name__ == '__main__': script_dir = os.path.dirname(os.path.realpath(__file__)) valid_commands = { 'generate-cpp': 'generate_cpp', 'generate-serialization': 'generate_serialization', } parser = argparse.ArgumentParser( description='Phosphor Inventory Manager (PIM) YAML ' 'scanner and code generator.') parser.add_argument( '-o', '--output-dir', dest='outputdir', default='.', help='Output directory.') parser.add_argument( '-i', '--interfaces-dir', dest='ifacesdir', help='Location of interfaces to be supported.') parser.add_argument( '-d', '--dir', dest='inputdir', default=os.path.join(script_dir, 'example'), help='Location of files to process.') parser.add_argument( '-b', '--bus-name', dest='busname', default='xyz.openbmc_project.Inventory.Manager', help='Inventory manager busname.') parser.add_argument( 'command', metavar='COMMAND', type=str, choices=valid_commands.keys(), help='%s.' % " | ".join(valid_commands.keys())) args = parser.parse_args() if sys.version_info < (3, 0): lookup = mako.lookup.TemplateLookup( directories=[script_dir], disable_unicode=True) else: lookup = mako.lookup.TemplateLookup( directories=[script_dir]) function = getattr( Everything.load(args), valid_commands[args.command]) function(lookup) # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
#!/usr/bin/env python '''Phosphor Inventory Manager YAML parser and code generator. The parser workflow is broken down as follows: 1 - Import YAML files as native python type(s) instance(s). 2 - Create an instance of the Everything class from the native python type instance(s) with the Everything.load method. 3 - The Everything class constructor orchestrates conversion of the native python type(s) instances(s) to render helper types. Each render helper type constructor imports its attributes from the native python type(s) instances(s). 4 - Present the converted YAML to the command processing method requested by the script user. ''' import sys import os import argparse import subprocess import yaml import mako.lookup import sdbusplus.property from sdbusplus.namedelement import NamedElement from sdbusplus.renderer import Renderer # Global busname for use within classes where necessary busname = "xyz.openbmc_project.Inventory.Manager" def cppTypeName(yaml_type): ''' Convert yaml types to cpp types.''' return sdbusplus.property.Property(type=yaml_type).cppTypeName class InterfaceComposite(object): '''Compose interface properties.''' def __init__(self, dict): self.dict = dict def properties(self, interface): return self.dict[interface] def interfaces(self): return self.dict.keys() def names(self, interface): names = [] if self.dict[interface]: names = [x["name"] for x in self.dict[interface]] return names class Interface(list): '''Provide various interface transformations.''' def __init__(self, iface): super(Interface, self).__init__(iface.split('.')) def namespace(self): '''Represent as an sdbusplus namespace.''' return '::'.join(['sdbusplus'] + self[:-1] + ['server', self[-1]]) def header(self): '''Represent as an sdbusplus server binding header.''' return os.sep.join(self + ['server.hpp']) def __str__(self): return '.'.join(self) class Indent(object): '''Help templates be depth agnostic.''' def __init__(self, depth=0): self.depth = depth def __add__(self, depth): return Indent(self.depth + depth) def __call__(self, depth): '''Render an indent at the current depth plus depth.''' return 4*' '*(depth + self.depth) class Template(NamedElement): '''Associate a template name with its namespace.''' def __init__(self, **kw): self.namespace = kw.pop('namespace', []) super(Template, self).__init__(**kw) def qualified(self): return '::'.join(self.namespace + [self.name]) class FixBool(object): '''Un-capitalize booleans.''' def __call__(self, arg): return '{0}'.format(arg.lower()) class Quote(object): '''Decorate an argument by quoting it.''' def __call__(self, arg): return '"{0}"'.format(arg) class Cast(object): '''Decorate an argument by casting it.''' def __init__(self, cast, target): '''cast is the cast type (static, const, etc...). target is the cast target type.''' self.cast = cast self.target = target def __call__(self, arg): return '{0}_cast<{1}>({2})'.format(self.cast, self.target, arg) class Literal(object): '''Decorate an argument with a literal operator.''' integer_types = [ 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64' ] def __init__(self, type): self.type = type def __call__(self, arg): if 'uint' in self.type: arg = '{0}ull'.format(arg) elif 'int' in self.type: arg = '{0}ll'.format(arg) if self.type in self.integer_types: return Cast('static', '{0}_t'.format(self.type))(arg) if self.type == 'string': return '{0}s'.format(arg) return arg class Argument(NamedElement, Renderer): '''Define argument type inteface.''' def __init__(self, **kw): self.type = kw.pop('type', None) super(Argument, self).__init__(**kw) def argument(self, loader, indent): raise NotImplementedError class TrivialArgument(Argument): '''Non-array type arguments.''' def __init__(self, **kw): self.value = kw.pop('value') self.decorators = kw.pop('decorators', []) if kw.get('type', None) == 'string': self.decorators.insert(0, Quote()) if kw.get('type', None) == 'boolean': self.decorators.insert(0, FixBool()) super(TrivialArgument, self).__init__(**kw) def argument(self, loader, indent): a = str(self.value) for d in self.decorators: a = d(a) return a class InitializerList(Argument): '''Initializer list arguments.''' def __init__(self, **kw): self.values = kw.pop('values') super(InitializerList, self).__init__(**kw) def argument(self, loader, indent): return self.render( loader, 'argument.mako.cpp', arg=self, indent=indent) class DbusSignature(Argument): '''DBus signature arguments.''' def __init__(self, **kw): self.sig = {x: y for x, y in kw.iteritems()} kw.clear() super(DbusSignature, self).__init__(**kw) def argument(self, loader, indent): return self.render( loader, 'signature.mako.cpp', signature=self, indent=indent) class MethodCall(Argument): '''Render syntatically correct c++ method calls.''' def __init__(self, **kw): self.namespace = kw.pop('namespace', []) self.templates = kw.pop('templates', []) self.args = kw.pop('args', []) super(MethodCall, self).__init__(**kw) def call(self, loader, indent): return self.render( loader, 'method.mako.cpp', method=self, indent=indent) def argument(self, loader, indent): return self.call(loader, indent) class Vector(MethodCall): '''Convenience type for vectors.''' def __init__(self, **kw): kw['name'] = 'vector' kw['namespace'] = ['std'] kw['args'] = [InitializerList(values=kw.pop('args'))] super(Vector, self).__init__(**kw) class Filter(MethodCall): '''Convenience type for filters''' def __init__(self, **kw): kw['name'] = 'make_filter' super(Filter, self).__init__(**kw) class Action(MethodCall): '''Convenience type for actions''' def __init__(self, **kw): kw['name'] = 'make_action' super(Action, self).__init__(**kw) class PathCondition(MethodCall): '''Convenience type for path conditions''' def __init__(self, **kw): kw['name'] = 'make_path_condition' super(PathCondition, self).__init__(**kw) class GetProperty(MethodCall): '''Convenience type for getting inventory properties''' def __init__(self, **kw): kw['name'] = 'make_get_property' super(GetProperty, self).__init__(**kw) class CreateObjects(MethodCall): '''Assemble a createObjects functor.''' def __init__(self, **kw): objs = [] for path, interfaces in kw.pop('objs').iteritems(): key_o = TrivialArgument( value=path, type='string', decorators=[Literal('string')]) value_i = [] for interface, properties, in interfaces.iteritems(): key_i = TrivialArgument(value=interface, type='string') value_p = [] if properties: for prop, value in properties.iteritems(): key_p = TrivialArgument(value=prop, type='string') value_v = TrivialArgument( decorators=[Literal(value.get('type', None))], **value) value_p.append(InitializerList(values=[key_p, value_v])) value_p = InitializerList(values=value_p) value_i.append(InitializerList(values=[key_i, value_p])) value_i = InitializerList(values=value_i) objs.append(InitializerList(values=[key_o, value_i])) kw['args'] = [InitializerList(values=objs)] kw['namespace'] = ['functor'] super(CreateObjects, self).__init__(**kw) class DestroyObjects(MethodCall): '''Assemble a destroyObject functor.''' def __init__(self, **kw): values = [{'value': x, 'type': 'string'} for x in kw.pop('paths')] conditions = [ Event.functor_map[ x['name']](**x) for x in kw.pop('conditions', [])] conditions = [PathCondition(args=[x]) for x in conditions] args = [InitializerList( values=[TrivialArgument(**x) for x in values])] args.append(InitializerList(values=conditions)) kw['args'] = args kw['namespace'] = ['functor'] super(DestroyObjects, self).__init__(**kw) class SetProperty(MethodCall): '''Assemble a setProperty functor.''' def __init__(self, **kw): args = [] value = kw.pop('value') prop = kw.pop('property') iface = kw.pop('interface') iface = Interface(iface) namespace = iface.namespace().split('::')[:-1] name = iface[-1] t = Template(namespace=namespace, name=iface[-1]) member = '&%s' % '::'.join( namespace + [name, NamedElement(name=prop).camelCase]) member_type = cppTypeName(value['type']) member_cast = '{0} ({1}::*)({0})'.format(member_type, t.qualified()) paths = [{'value': x, 'type': 'string'} for x in kw.pop('paths')] args.append(InitializerList( values=[TrivialArgument(**x) for x in paths])) conditions = [ Event.functor_map[ x['name']](**x) for x in kw.pop('conditions', [])] conditions = [PathCondition(args=[x]) for x in conditions] args.append(InitializerList(values=conditions)) args.append(TrivialArgument(value=str(iface), type='string')) args.append(TrivialArgument( value=member, decorators=[Cast('static', member_cast)])) args.append(TrivialArgument(**value)) kw['templates'] = [Template(name=name, namespace=namespace)] kw['args'] = args kw['namespace'] = ['functor'] super(SetProperty, self).__init__(**kw) class PropertyChanged(MethodCall): '''Assemble a propertyChanged functor.''' def __init__(self, **kw): args = [] args.append(TrivialArgument(value=kw.pop('interface'), type='string')) args.append(TrivialArgument(value=kw.pop('property'), type='string')) args.append(TrivialArgument( decorators=[ Literal(kw['value'].get('type', None))], **kw.pop('value'))) kw['args'] = args kw['namespace'] = ['functor'] super(PropertyChanged, self).__init__(**kw) class PropertyIs(MethodCall): '''Assemble a propertyIs functor.''' def __init__(self, **kw): args = [] path = kw.pop('path', None) if not path: path = TrivialArgument(value='nullptr') else: path = TrivialArgument(value=path, type='string') args.append(path) iface = TrivialArgument(value=kw.pop('interface'), type='string') args.append(iface) prop = TrivialArgument(value=kw.pop('property'), type='string') args.append(prop) args.append(TrivialArgument( decorators=[ Literal(kw['value'].get('type', None))], **kw.pop('value'))) service = kw.pop('service', None) if service: args.append(TrivialArgument(value=service, type='string')) dbusMember = kw.pop('dbusMember', None) if dbusMember: # Inventory manager's service name is required if not service or service != busname: args.append(TrivialArgument(value=busname, type='string')) gpArgs = [] gpArgs.append(path) gpArgs.append(iface) # Prepend '&' and append 'getPropertyByName' function on dbusMember gpArgs.append(TrivialArgument( value='&'+dbusMember+'::getPropertyByName')) gpArgs.append(prop) fArg = MethodCall( name='getProperty', namespace=['functor'], templates=[Template( name=dbusMember, namespace=[])], args=gpArgs) # Append getProperty functor args.append(GetProperty( templates=[Template( name=dbusMember+'::PropertiesVariant', namespace=[])], args=[fArg])) kw['args'] = args kw['namespace'] = ['functor'] super(PropertyIs, self).__init__(**kw) class Event(MethodCall): '''Assemble an inventory manager event.''' functor_map = { 'destroyObjects': DestroyObjects, 'createObjects': CreateObjects, 'propertyChangedTo': PropertyChanged, 'propertyIs': PropertyIs, 'setProperty': SetProperty, } def __init__(self, **kw): self.summary = kw.pop('name') filters = [ self.functor_map[x['name']](**x) for x in kw.pop('filters', [])] filters = [Filter(args=[x]) for x in filters] filters = Vector( templates=[Template(name='Filter', namespace=[])], args=filters) event = MethodCall( name='make_shared', namespace=['std'], templates=[Template( name=kw.pop('event'), namespace=kw.pop('event_namespace', []))], args=kw.pop('event_args', []) + [filters]) events = Vector( templates=[Template(name='EventBasePtr', namespace=[])], args=[event]) action_type = Template(name='Action', namespace=[]) action_args = [ self.functor_map[x['name']](**x) for x in kw.pop('actions', [])] action_args = [Action(args=[x]) for x in action_args] actions = Vector( templates=[action_type], args=action_args) kw['name'] = 'make_tuple' kw['namespace'] = ['std'] kw['args'] = [events, actions] super(Event, self).__init__(**kw) class MatchEvent(Event): '''Associate one or more dbus signal match signatures with a filter.''' def __init__(self, **kw): kw['event'] = 'DbusSignal' kw['event_namespace'] = [] kw['event_args'] = [ DbusSignature(**x) for x in kw.pop('signatures', [])] super(MatchEvent, self).__init__(**kw) class StartupEvent(Event): '''Assemble a startup event.''' def __init__(self, **kw): kw['event'] = 'StartupEvent' kw['event_namespace'] = [] super(StartupEvent, self).__init__(**kw) class Everything(Renderer): '''Parse/render entry point.''' class_map = { 'match': MatchEvent, 'startup': StartupEvent, } @staticmethod def load(args): # Aggregate all the event YAML in the events.d directory # into a single list of events. events = [] events_dir = os.path.join(args.inputdir, 'events.d') if os.path.exists(events_dir): yaml_files = filter( lambda x: x.endswith('.yaml'), os.listdir(events_dir)) for x in yaml_files: with open(os.path.join(events_dir, x), 'r') as fd: for e in yaml.safe_load(fd.read()).get('events', {}): events.append(e) interfaces, interface_composite = Everything.get_interfaces( args.ifacesdir) extra_interfaces, extra_interface_composite = \ Everything.get_interfaces( os.path.join(args.inputdir, 'extra_interfaces.d')) interface_composite.update(extra_interface_composite) interface_composite = InterfaceComposite(interface_composite) # Update busname if configured differenly than the default busname = args.busname return Everything( *events, interfaces=interfaces + extra_interfaces, interface_composite=interface_composite) @staticmethod def get_interfaces(targetdir): '''Scan the interfaces directory for interfaces that PIM can create.''' yaml_files = [] interfaces = [] interface_composite = {} if targetdir and os.path.exists(targetdir): for directory, _, files in os.walk(targetdir): if not files: continue yaml_files += map( lambda f: os.path.relpath( os.path.join(directory, f), targetdir), filter(lambda f: f.endswith('.interface.yaml'), files)) for y in yaml_files: # parse only phosphor dbus related interface files if not y.startswith('xyz'): continue with open(os.path.join(targetdir, y)) as fd: i = y.replace('.interface.yaml', '').replace(os.sep, '.') # PIM can't create interfaces with methods. parsed = yaml.safe_load(fd.read()) if parsed.get('methods', None): continue # Cereal can't understand the type sdbusplus::object_path. This # type is a wrapper around std::string. Ignore interfaces having # a property of this type for now. The only interface that has a # property of this type now is xyz.openbmc_project.Association, # which is an unused interface. No inventory objects implement # this interface. # TODO via openbmc/openbmc#2123 : figure out how to make Cereal # understand sdbusplus::object_path. properties = parsed.get('properties', None) if properties: if any('path' in p['type'] for p in properties): continue interface_composite[i] = properties interfaces.append(i) return interfaces, interface_composite def __init__(self, *a, **kw): self.interfaces = \ [Interface(x) for x in kw.pop('interfaces', [])] self.interface_composite = \ kw.pop('interface_composite', {}) self.events = [ self.class_map[x['type']](**x) for x in a] super(Everything, self).__init__(**kw) def generate_cpp(self, loader): '''Render the template with the provided events and interfaces.''' with open(os.path.join( args.outputdir, 'generated.cpp'), 'w') as fd: fd.write( self.render( loader, 'generated.mako.cpp', events=self.events, interfaces=self.interfaces, indent=Indent())) def generate_serialization(self, loader): with open(os.path.join( args.outputdir, 'gen_serialization.hpp'), 'w') as fd: fd.write( self.render( loader, 'gen_serialization.mako.hpp', interfaces=self.interfaces, interface_composite=self.interface_composite)) if __name__ == '__main__': script_dir = os.path.dirname(os.path.realpath(__file__)) valid_commands = { 'generate-cpp': 'generate_cpp', 'generate-serialization': 'generate_serialization', } parser = argparse.ArgumentParser( description='Phosphor Inventory Manager (PIM) YAML ' 'scanner and code generator.') parser.add_argument( '-o', '--output-dir', dest='outputdir', default='.', help='Output directory.') parser.add_argument( '-i', '--interfaces-dir', dest='ifacesdir', help='Location of interfaces to be supported.') parser.add_argument( '-d', '--dir', dest='inputdir', default=os.path.join(script_dir, 'example'), help='Location of files to process.') parser.add_argument( '-b', '--bus-name', dest='busname', default='xyz.openbmc_project.Inventory.Manager', help='Inventory manager busname.') parser.add_argument( 'command', metavar='COMMAND', type=str, choices=valid_commands.keys(), help='%s.' % " | ".join(valid_commands.keys())) args = parser.parse_args() if sys.version_info < (3, 0): lookup = mako.lookup.TemplateLookup( directories=[script_dir], disable_unicode=True) else: lookup = mako.lookup.TemplateLookup( directories=[script_dir]) function = getattr( Everything.load(args), valid_commands[args.command]) function(lookup) # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
en
0.767482
#!/usr/bin/env python Phosphor Inventory Manager YAML parser and code generator. The parser workflow is broken down as follows: 1 - Import YAML files as native python type(s) instance(s). 2 - Create an instance of the Everything class from the native python type instance(s) with the Everything.load method. 3 - The Everything class constructor orchestrates conversion of the native python type(s) instances(s) to render helper types. Each render helper type constructor imports its attributes from the native python type(s) instances(s). 4 - Present the converted YAML to the command processing method requested by the script user. # Global busname for use within classes where necessary Convert yaml types to cpp types. Compose interface properties. Provide various interface transformations. Represent as an sdbusplus namespace. Represent as an sdbusplus server binding header. Help templates be depth agnostic. Render an indent at the current depth plus depth. Associate a template name with its namespace. Un-capitalize booleans. Decorate an argument by quoting it. Decorate an argument by casting it. cast is the cast type (static, const, etc...). target is the cast target type. Decorate an argument with a literal operator. Define argument type inteface. Non-array type arguments. Initializer list arguments. DBus signature arguments. Render syntatically correct c++ method calls. Convenience type for vectors. Convenience type for filters Convenience type for actions Convenience type for path conditions Convenience type for getting inventory properties Assemble a createObjects functor. Assemble a destroyObject functor. Assemble a setProperty functor. Assemble a propertyChanged functor. Assemble a propertyIs functor. # Inventory manager's service name is required # Prepend '&' and append 'getPropertyByName' function on dbusMember # Append getProperty functor Assemble an inventory manager event. Associate one or more dbus signal match signatures with a filter. Assemble a startup event. Parse/render entry point. # Aggregate all the event YAML in the events.d directory # into a single list of events. # Update busname if configured differenly than the default Scan the interfaces directory for interfaces that PIM can create. # parse only phosphor dbus related interface files # PIM can't create interfaces with methods. # Cereal can't understand the type sdbusplus::object_path. This # type is a wrapper around std::string. Ignore interfaces having # a property of this type for now. The only interface that has a # property of this type now is xyz.openbmc_project.Association, # which is an unused interface. No inventory objects implement # this interface. # TODO via openbmc/openbmc#2123 : figure out how to make Cereal # understand sdbusplus::object_path. Render the template with the provided events and interfaces. # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
2.707089
3
award/models.py
ivxxi/Django3
0
6625828
from django.db import models from tinymce.models import HTMLField from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to='images/') bio = models.TextField(max_length=500) contact = models.CharField(max_length=200) def __str__(self): return self.bio def save_profile(self): self.save() def delete_profile(self): self.delete() class Project(models.Model): title = models.CharField(max_length=155) description = models.TextField(max_length=255) photo = models.ImageField(upload_to='pics/') user = models.ForeignKey(User) link = models.URLField(max_length=200) design = models.IntegerField(choices=list(zip(range(0,11), range(0,11))), default=0) usability = models.IntegerField(choices=list(zip(range(0,11), range(0,11))), default=0) content = models.IntegerField(choices=list(zip(range(0,11), range(0,11))), default=0) vote_submissions = models.IntegerField(default=0) def __str__(self): return f'{self.title}' def save_project(self): self.save() def delete_project(self): self.delete() @classmethod def search_by_title(cls,search_term): projects = cls.objects.filter(title__icontains=search_term) return projects @classmethod def get_all_images(cls): images=cls.objects.all().prefetch_related('comment_set') return images class Comment(models.Model): posted_by=models.ForeignKey(User, on_delete=models.CASCADE,null=True) comment_image=models.ForeignKey(Project,on_delete=models.CASCADE,null=True) comment=models.CharField(max_length=20,null=True) def __str__(self): return self.posted_by
from django.db import models from tinymce.models import HTMLField from django.contrib.auth.models import User # Create your models here. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_picture = models.ImageField(upload_to='images/') bio = models.TextField(max_length=500) contact = models.CharField(max_length=200) def __str__(self): return self.bio def save_profile(self): self.save() def delete_profile(self): self.delete() class Project(models.Model): title = models.CharField(max_length=155) description = models.TextField(max_length=255) photo = models.ImageField(upload_to='pics/') user = models.ForeignKey(User) link = models.URLField(max_length=200) design = models.IntegerField(choices=list(zip(range(0,11), range(0,11))), default=0) usability = models.IntegerField(choices=list(zip(range(0,11), range(0,11))), default=0) content = models.IntegerField(choices=list(zip(range(0,11), range(0,11))), default=0) vote_submissions = models.IntegerField(default=0) def __str__(self): return f'{self.title}' def save_project(self): self.save() def delete_project(self): self.delete() @classmethod def search_by_title(cls,search_term): projects = cls.objects.filter(title__icontains=search_term) return projects @classmethod def get_all_images(cls): images=cls.objects.all().prefetch_related('comment_set') return images class Comment(models.Model): posted_by=models.ForeignKey(User, on_delete=models.CASCADE,null=True) comment_image=models.ForeignKey(Project,on_delete=models.CASCADE,null=True) comment=models.CharField(max_length=20,null=True) def __str__(self): return self.posted_by
en
0.963489
# Create your models here.
2.257877
2
protonfixes/gamefixes/200260.py
Citiroller/protonfixes
213
6625829
""" Game fix Batman Arkham City """ #pylint: disable=C0103 from protonfixes import util from protonfixes.protonversion import DeprecatedSince @DeprecatedSince("5.0-3") def main(): """ Probably not needed when proton will be merged with newer wine """ util.protontricks('dotnet20') util.protontricks('dotnet35') util.protontricks('physx') util.protontricks('mdx') util.protontricks('d3dcompiler_43') util.protontricks('d3dx9_43') util.protontricks('win10') util._mk_syswow64() #pylint: disable=protected-access #TODO Checking possibly some tweak for language detection
""" Game fix Batman Arkham City """ #pylint: disable=C0103 from protonfixes import util from protonfixes.protonversion import DeprecatedSince @DeprecatedSince("5.0-3") def main(): """ Probably not needed when proton will be merged with newer wine """ util.protontricks('dotnet20') util.protontricks('dotnet35') util.protontricks('physx') util.protontricks('mdx') util.protontricks('d3dcompiler_43') util.protontricks('d3dx9_43') util.protontricks('win10') util._mk_syswow64() #pylint: disable=protected-access #TODO Checking possibly some tweak for language detection
en
0.745645
Game fix Batman Arkham City #pylint: disable=C0103 Probably not needed when proton will be merged with newer wine #pylint: disable=protected-access #TODO Checking possibly some tweak for language detection
1.441947
1
tests/components/mqtt/test_light.py
europrimus/core
0
6625830
<filename>tests/components/mqtt/test_light.py """The tests for the MQTT light platform. Configuration for RGB Version with brightness: light: platform: mqtt name: "Office Light RGB" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" rgb_state_topic: "office/rgb1/rgb/status" rgb_command_topic: "office/rgb1/rgb/set" qos: 0 payload_on: "on" payload_off: "off" Configuration for XY Version with brightness: light: platform: mqtt name: "Office Light XY" state_topic: "office/xy1/light/status" command_topic: "office/xy1/light/switch" brightness_state_topic: "office/xy1/brightness/status" brightness_command_topic: "office/xy1/brightness/set" xy_state_topic: "office/xy1/xy/status" xy_command_topic: "office/xy1/xy/set" qos: 0 payload_on: "on" payload_off: "off" config without RGB: light: platform: mqtt name: "Office Light" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" qos: 0 payload_on: "on" payload_off: "off" config without RGB and brightness: light: platform: mqtt name: "Office Light" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" qos: 0 payload_on: "on" payload_off: "off" config for RGB Version with brightness and scale: light: platform: mqtt name: "Office Light RGB" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" brightness_scale: 99 rgb_state_topic: "office/rgb1/rgb/status" rgb_command_topic: "office/rgb1/rgb/set" rgb_scale: 99 qos: 0 payload_on: "on" payload_off: "off" config with brightness and color temp light: platform: mqtt name: "Office Light Color Temp" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" brightness_scale: 99 color_temp_state_topic: "office/rgb1/color_temp/status" color_temp_command_topic: "office/rgb1/color_temp/set" qos: 0 payload_on: "on" payload_off: "off" config with brightness and effect light: platform: mqtt name: "Office Light Color Temp" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" brightness_scale: 99 effect_state_topic: "office/rgb1/effect/status" effect_command_topic: "office/rgb1/effect/set" effect_list: - rainbow - colorloop qos: 0 payload_on: "on" payload_off: "off" config for RGB Version with white value and scale: light: platform: mqtt name: "Office Light RGB" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" white_value_state_topic: "office/rgb1/white_value/status" white_value_command_topic: "office/rgb1/white_value/set" white_value_scale: 99 rgb_state_topic: "office/rgb1/rgb/status" rgb_command_topic: "office/rgb1/rgb/set" rgb_scale: 99 qos: 0 payload_on: "on" payload_off: "off" config for RGB Version with RGB command template: light: platform: mqtt name: "Office Light RGB" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" rgb_state_topic: "office/rgb1/rgb/status" rgb_command_topic: "office/rgb1/rgb/set" rgb_command_template: "{{ '#%02x%02x%02x' | format(red, green, blue)}}" qos: 0 payload_on: "on" payload_off: "off" Configuration for HS Version with brightness: light: platform: mqtt name: "Office Light HS" state_topic: "office/hs1/light/status" command_topic: "office/hs1/light/switch" brightness_state_topic: "office/hs1/brightness/status" brightness_command_topic: "office/hs1/brightness/set" hs_state_topic: "office/hs1/hs/status" hs_command_topic: "office/hs1/hs/set" qos: 0 payload_on: "on" payload_off: "off" Configuration with brightness command template: light: platform: mqtt name: "Office Light" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" brightness_command_template: '{ "brightness": "{{ value }}" }' qos: 0 payload_on: "on" payload_off: "off" Configuration with effect command template: light: platform: mqtt name: "Office Light Color Temp" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" effect_state_topic: "office/rgb1/effect/status" effect_command_topic: "office/rgb1/effect/set" effect_command_template: '{ "effect": "{{ value }}" }' effect_list: - rainbow - colorloop qos: 0 payload_on: "on" payload_off: "off" """ import copy from unittest.mock import call, patch import pytest from homeassistant.components import light from homeassistant.components.mqtt.light.schema_basic import ( CONF_BRIGHTNESS_COMMAND_TOPIC, CONF_COLOR_TEMP_COMMAND_TOPIC, CONF_EFFECT_COMMAND_TOPIC, CONF_EFFECT_LIST, CONF_HS_COMMAND_TOPIC, CONF_RGB_COMMAND_TOPIC, CONF_RGBW_COMMAND_TOPIC, CONF_RGBWW_COMMAND_TOPIC, CONF_WHITE_VALUE_COMMAND_TOPIC, CONF_XY_COMMAND_TOPIC, MQTT_LIGHT_ATTRIBUTES_BLOCKED, ) from homeassistant.const import ( ATTR_ASSUMED_STATE, ATTR_SUPPORTED_FEATURES, STATE_OFF, STATE_ON, STATE_UNKNOWN, ) import homeassistant.core as ha from homeassistant.setup import async_setup_component from .test_common import ( help_test_availability_when_connection_lost, help_test_availability_without_topic, help_test_custom_availability_payload, help_test_default_availability_payload, help_test_discovery_broken, help_test_discovery_removal, help_test_discovery_update, help_test_discovery_update_attr, help_test_discovery_update_unchanged, help_test_encoding_subscribable_topics, help_test_entity_debug_info_message, help_test_entity_device_info_remove, help_test_entity_device_info_update, help_test_entity_device_info_with_connection, help_test_entity_device_info_with_identifier, help_test_entity_id_update_discovery_update, help_test_entity_id_update_subscriptions, help_test_publishing_with_custom_encoding, help_test_reloadable, help_test_reloadable_late, help_test_setting_attribute_via_mqtt_json_message, help_test_setting_attribute_with_template, help_test_setting_blocked_attribute_via_mqtt_json_message, help_test_setup_manual_entity_from_yaml, help_test_unique_id, help_test_update_with_json_attrs_bad_JSON, help_test_update_with_json_attrs_not_dict, ) from tests.common import assert_setup_component, async_fire_mqtt_message from tests.components.light import common DEFAULT_CONFIG = { light.DOMAIN: {"platform": "mqtt", "name": "test", "command_topic": "test-topic"} } async def test_fail_setup_if_no_command_topic(hass, mqtt_mock_entry_no_yaml_config): """Test if command fails with command topic.""" assert await async_setup_component( hass, light.DOMAIN, {light.DOMAIN: {"platform": "mqtt", "name": "test"}} ) await hass.async_block_till_done() await mqtt_mock_entry_no_yaml_config() assert hass.states.get("light.test") is None async def test_legacy_rgb_white_light(hass, mqtt_mock_entry_with_yaml_config): """Test legacy RGB + white light flags brightness support.""" assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_rgb/set", "rgb_command_topic": "test_light_rgb/rgb/set", "white_value_command_topic": "test_light_rgb/white/set", } }, ) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") expected_features = ( light.SUPPORT_COLOR | light.SUPPORT_BRIGHTNESS | light.SUPPORT_WHITE_VALUE ) assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == expected_features assert state.attributes.get(light.ATTR_COLOR_MODE) is None assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == ["hs", "rgbw"] async def test_no_color_brightness_color_temp_hs_white_xy_if_no_topics( hass, mqtt_mock_entry_with_yaml_config ): """Test if there is no color and brightness if no topic.""" assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", } }, ) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("rgb_color") is None assert state.attributes.get("rgbw_color") is None assert state.attributes.get("rgbww_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) is None assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == ["onoff"] async_fire_mqtt_message(hass, "test_light_rgb/status", "ON") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("rgb_color") is None assert state.attributes.get("rgbw_color") is None assert state.attributes.get("rgbww_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) == "onoff" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == ["onoff"] async_fire_mqtt_message(hass, "test_light_rgb/status", "OFF") state = hass.states.get("light.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "test_light_rgb/status", "None") state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN async def test_legacy_controlling_state_via_topic( hass, mqtt_mock_entry_with_yaml_config ): """Test the controlling of the state via topic for legacy light (white_value).""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", "brightness_state_topic": "test_light_rgb/brightness/status", "brightness_command_topic": "test_light_rgb/brightness/set", "rgb_state_topic": "test_light_rgb/rgb/status", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_state_topic": "test_light_rgb/color_temp/status", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_state_topic": "test_light_rgb/effect/status", "effect_command_topic": "test_light_rgb/effect/set", "hs_state_topic": "test_light_rgb/hs/status", "hs_command_topic": "test_light_rgb/hs/set", "white_value_state_topic": "test_light_rgb/white_value/status", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_state_topic": "test_light_rgb/xy/status", "xy_command_topic": "test_light_rgb/xy/set", "qos": "0", "payload_on": 1, "payload_off": 0, } } color_modes = ["color_temp", "hs", "rgbw"] assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("rgb_color") is None assert state.attributes.get("rgbw_color") is None assert state.attributes.get("rgbww_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) is None assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_light_rgb/status", "1") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("rgb_color") is None assert state.attributes.get("rgbw_color") is None assert state.attributes.get("rgbww_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/status", "0") state = hass.states.get("light.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "test_light_rgb/status", "1") async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", "100") light_state = hass.states.get("light.test") assert light_state.attributes["brightness"] == 100 assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/color_temp/status", "300") light_state = hass.states.get("light.test") assert light_state.attributes.get("color_temp") is None assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/white_value/status", "100") light_state = hass.states.get("light.test") assert light_state.attributes["white_value"] == 100 assert light_state.attributes["color_temp"] == 300 assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "color_temp" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/effect/status", "rainbow") light_state = hass.states.get("light.test") assert light_state.attributes["effect"] == "rainbow" assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "color_temp" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/status", "1") async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", "125,125,125") light_state = hass.states.get("light.test") assert light_state.attributes.get("rgb_color") == (255, 187, 131) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "color_temp" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/white_value/status", "0") light_state = hass.states.get("light.test") assert light_state.attributes.get("rgb_color") == (255, 255, 255) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/hs/status", "200,50") light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (200, 50) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/xy/status", "0.675,0.322") light_state = hass.states.get("light.test") assert light_state.attributes.get("xy_color") == (0.672, 0.324) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async def test_controlling_state_via_topic(hass, mqtt_mock_entry_with_yaml_config): """Test the controlling of the state via topic.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", "brightness_state_topic": "test_light_rgb/brightness/status", "brightness_command_topic": "test_light_rgb/brightness/set", "rgb_state_topic": "test_light_rgb/rgb/status", "rgb_command_topic": "test_light_rgb/rgb/set", "rgbw_state_topic": "test_light_rgb/rgbw/status", "rgbw_command_topic": "test_light_rgb/rgbw/set", "rgbww_state_topic": "test_light_rgb/rgbww/status", "rgbww_command_topic": "test_light_rgb/rgbww/set", "color_temp_state_topic": "test_light_rgb/color_temp/status", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_state_topic": "test_light_rgb/effect/status", "effect_command_topic": "test_light_rgb/effect/set", "hs_state_topic": "test_light_rgb/hs/status", "hs_command_topic": "test_light_rgb/hs/set", "xy_state_topic": "test_light_rgb/xy/status", "xy_command_topic": "test_light_rgb/xy/set", "qos": "0", "payload_on": 1, "payload_off": 0, } } color_modes = ["color_temp", "hs", "rgb", "rgbw", "rgbww", "xy"] assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("rgb_color") is None assert state.attributes.get("rgbw_color") is None assert state.attributes.get("rgbww_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) is None assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_light_rgb/status", "1") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("rgb_color") is None assert state.attributes.get("rgbw_color") is None assert state.attributes.get("rgbww_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/status", "0") state = hass.states.get("light.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "test_light_rgb/status", "1") async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", "100") light_state = hass.states.get("light.test") assert light_state.attributes.get("brightness") is None assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/color_temp/status", "300") light_state = hass.states.get("light.test") assert light_state.attributes.get("brightness") == 100 assert light_state.attributes["color_temp"] == 300 assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "color_temp" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/effect/status", "rainbow") light_state = hass.states.get("light.test") assert light_state.attributes["effect"] == "rainbow" assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "color_temp" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", "125,125,125") light_state = hass.states.get("light.test") assert light_state.attributes.get("rgb_color") == (125, 125, 125) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "rgb" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/rgbw/status", "80,40,20,10") light_state = hass.states.get("light.test") assert light_state.attributes.get("rgbw_color") == (80, 40, 20, 10) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "rgbw" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/rgbww/status", "80,40,20,10,8") light_state = hass.states.get("light.test") assert light_state.attributes.get("rgbww_color") == (80, 40, 20, 10, 8) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "rgbww" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/hs/status", "200,50") light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (200, 50) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/xy/status", "0.675,0.322") light_state = hass.states.get("light.test") assert light_state.attributes.get("xy_color") == (0.675, 0.322) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "xy" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async def test_legacy_invalid_state_via_topic( hass, mqtt_mock_entry_with_yaml_config, caplog ): """Test handling of empty data via topic.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", "brightness_state_topic": "test_light_rgb/brightness/status", "brightness_command_topic": "test_light_rgb/brightness/set", "rgb_state_topic": "test_light_rgb/rgb/status", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_state_topic": "test_light_rgb/color_temp/status", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_state_topic": "test_light_rgb/effect/status", "effect_command_topic": "test_light_rgb/effect/set", "hs_state_topic": "test_light_rgb/hs/status", "hs_command_topic": "test_light_rgb/hs/set", "white_value_state_topic": "test_light_rgb/white_value/status", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_state_topic": "test_light_rgb/xy/status", "xy_command_topic": "test_light_rgb/xy/set", "qos": "0", "payload_on": 1, "payload_off": 0, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_light_rgb/status", "1") async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", "255,255,255") async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", "255") async_fire_mqtt_message(hass, "test_light_rgb/effect/status", "none") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (255, 255, 255) assert state.attributes.get("brightness") == 255 assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") == "none" assert state.attributes.get("hs_color") == (0, 0) assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") == (0.323, 0.329) async_fire_mqtt_message(hass, "test_light_rgb/status", "") assert "Ignoring empty state message" in caplog.text light_state = hass.states.get("light.test") assert state.state == STATE_ON async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", "") assert "Ignoring empty brightness message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes["brightness"] == 255 async_fire_mqtt_message(hass, "test_light_rgb/effect/status", "") assert "Ignoring empty effect message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes["effect"] == "none" async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", "") assert "Ignoring empty rgb message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("rgb_color") == (255, 255, 255) async_fire_mqtt_message(hass, "test_light_rgb/hs/status", "") assert "Ignoring empty hs message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (0, 0) async_fire_mqtt_message(hass, "test_light_rgb/hs/status", "bad,bad") assert "Failed to parse hs state update" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (0, 0) async_fire_mqtt_message(hass, "test_light_rgb/xy/status", "") assert "Ignoring empty xy-color message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("xy_color") == (0.323, 0.329) async_fire_mqtt_message(hass, "test_light_rgb/color_temp/status", "153") async_fire_mqtt_message(hass, "test_light_rgb/white_value/status", "255") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (255, 254, 250) assert state.attributes.get("brightness") == 255 assert state.attributes.get("color_temp") == 153 assert state.attributes.get("effect") == "none" assert state.attributes.get("hs_color") == (54.768, 1.6) assert state.attributes.get("white_value") == 255 assert state.attributes.get("xy_color") == (0.326, 0.333) async_fire_mqtt_message(hass, "test_light_rgb/color_temp/status", "") assert "Ignoring empty color temp message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes["color_temp"] == 153 async_fire_mqtt_message(hass, "test_light_rgb/white_value/status", "") assert "Ignoring empty white value message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes["white_value"] == 255 async def test_invalid_state_via_topic(hass, mqtt_mock_entry_with_yaml_config, caplog): """Test handling of empty data via topic.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", "brightness_state_topic": "test_light_rgb/brightness/status", "brightness_command_topic": "test_light_rgb/brightness/set", "color_mode_state_topic": "test_light_rgb/color_mode/status", "rgb_state_topic": "test_light_rgb/rgb/status", "rgb_command_topic": "test_light_rgb/rgb/set", "rgbw_state_topic": "test_light_rgb/rgbw/status", "rgbw_command_topic": "test_light_rgb/rgbw/set", "rgbww_state_topic": "test_light_rgb/rgbww/status", "rgbww_command_topic": "test_light_rgb/rgbww/set", "color_temp_state_topic": "test_light_rgb/color_temp/status", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_state_topic": "test_light_rgb/effect/status", "effect_command_topic": "test_light_rgb/effect/set", "hs_state_topic": "test_light_rgb/hs/status", "hs_command_topic": "test_light_rgb/hs/set", "xy_state_topic": "test_light_rgb/xy/status", "xy_command_topic": "test_light_rgb/xy/set", "qos": "0", "payload_on": 1, "payload_off": 0, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("rgb_color") is None assert state.attributes.get("rgbw_color") is None assert state.attributes.get("rgbww_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("xy_color") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_light_rgb/status", "1") async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "rgb") async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", "255,255,255") async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", "255") async_fire_mqtt_message(hass, "test_light_rgb/effect/status", "none") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (255, 255, 255) assert state.attributes.get("brightness") == 255 assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") == "none" assert state.attributes.get("hs_color") == (0, 0) assert state.attributes.get("xy_color") == (0.323, 0.329) assert state.attributes.get("color_mode") == "rgb" async_fire_mqtt_message(hass, "test_light_rgb/status", "") assert "Ignoring empty state message" in caplog.text light_state = hass.states.get("light.test") assert state.state == STATE_ON async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", "") assert "Ignoring empty brightness message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes["brightness"] == 255 async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "") assert "Ignoring empty color mode message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes["effect"] == "none" async_fire_mqtt_message(hass, "test_light_rgb/effect/status", "") assert "Ignoring empty effect message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes["effect"] == "none" async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", "") assert "Ignoring empty rgb message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("rgb_color") == (255, 255, 255) async_fire_mqtt_message(hass, "test_light_rgb/hs/status", "") assert "Ignoring empty hs message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (0, 0) async_fire_mqtt_message(hass, "test_light_rgb/hs/status", "bad,bad") assert "Failed to parse hs state update" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (0, 0) async_fire_mqtt_message(hass, "test_light_rgb/xy/status", "") assert "Ignoring empty xy-color message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("xy_color") == (0.323, 0.329) async_fire_mqtt_message(hass, "test_light_rgb/rgbw/status", "255,255,255,1") async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "rgbw") async_fire_mqtt_message(hass, "test_light_rgb/rgbw/status", "") assert "Ignoring empty rgbw message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("rgbw_color") == (255, 255, 255, 1) async_fire_mqtt_message(hass, "test_light_rgb/rgbww/status", "255,255,255,1,2") async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "rgbww") async_fire_mqtt_message(hass, "test_light_rgb/rgbww/status", "") assert "Ignoring empty rgbww message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("rgbww_color") == (255, 255, 255, 1, 2) async_fire_mqtt_message(hass, "test_light_rgb/color_temp/status", "153") async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "color_temp") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (255, 254, 250) assert state.attributes.get("brightness") == 255 assert state.attributes.get("color_temp") == 153 assert state.attributes.get("effect") == "none" assert state.attributes.get("hs_color") == (54.768, 1.6) assert state.attributes.get("xy_color") == (0.326, 0.333) async_fire_mqtt_message(hass, "test_light_rgb/color_temp/status", "") assert "Ignoring empty color temp message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes["color_temp"] == 153 async def test_brightness_controlling_scale(hass, mqtt_mock_entry_with_yaml_config): """Test the brightness controlling scale.""" with assert_setup_component(1, light.DOMAIN): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_scale/status", "command_topic": "test_scale/set", "brightness_state_topic": "test_scale/brightness/status", "brightness_command_topic": "test_scale/brightness/set", "brightness_scale": "99", "qos": 0, "payload_on": "on", "payload_off": "off", } }, ) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("brightness") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_scale/status", "on") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") is None async_fire_mqtt_message(hass, "test_scale/status", "off") state = hass.states.get("light.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "test_scale/status", "on") async_fire_mqtt_message(hass, "test_scale/brightness/status", "99") light_state = hass.states.get("light.test") assert light_state.attributes["brightness"] == 255 async def test_brightness_from_rgb_controlling_scale( hass, mqtt_mock_entry_with_yaml_config ): """Test the brightness controlling scale.""" with assert_setup_component(1, light.DOMAIN): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_scale_rgb/status", "command_topic": "test_scale_rgb/set", "rgb_state_topic": "test_scale_rgb/rgb/status", "rgb_command_topic": "test_scale_rgb/rgb/set", "qos": 0, "payload_on": "on", "payload_off": "off", } }, ) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("brightness") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_scale_rgb/status", "on") async_fire_mqtt_message(hass, "test_scale_rgb/rgb/status", "255,0,0") state = hass.states.get("light.test") assert state.attributes.get("brightness") == 255 async_fire_mqtt_message(hass, "test_scale_rgb/rgb/status", "127,0,0") state = hass.states.get("light.test") assert state.attributes.get("brightness") == 127 async def test_legacy_white_value_controlling_scale( hass, mqtt_mock_entry_with_yaml_config ): """Test the white_value controlling scale.""" with assert_setup_component(1, light.DOMAIN): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_scale/status", "command_topic": "test_scale/set", "white_value_state_topic": "test_scale/white_value/status", "white_value_command_topic": "test_scale/white_value/set", "white_value_scale": "99", "qos": 0, "payload_on": "on", "payload_off": "off", } }, ) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("white_value") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_scale/status", "on") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("white_value") is None async_fire_mqtt_message(hass, "test_scale/status", "off") state = hass.states.get("light.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "test_scale/status", "on") async_fire_mqtt_message(hass, "test_scale/white_value/status", "99") light_state = hass.states.get("light.test") assert light_state.attributes["white_value"] == 255 async def test_legacy_controlling_state_via_topic_with_templates( hass, mqtt_mock_entry_with_yaml_config ): """Test the setting of the state with a template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/brightness/set", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_command_topic": "test_light_rgb/xy/set", "brightness_state_topic": "test_light_rgb/brightness/status", "color_temp_state_topic": "test_light_rgb/color_temp/status", "effect_state_topic": "test_light_rgb/effect/status", "hs_state_topic": "test_light_rgb/hs/status", "rgb_state_topic": "test_light_rgb/rgb/status", "white_value_state_topic": "test_light_rgb/white_value/status", "xy_state_topic": "test_light_rgb/xy/status", "state_value_template": "{{ value_json.hello }}", "brightness_value_template": "{{ value_json.hello }}", "color_temp_value_template": "{{ value_json.hello }}", "effect_value_template": "{{ value_json.hello }}", "hs_value_template": '{{ value_json.hello | join(",") }}', "rgb_value_template": '{{ value_json.hello | join(",") }}', "white_value_template": "{{ value_json.hello }}", "xy_value_template": '{{ value_json.hello | join(",") }}', } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("brightness") is None assert state.attributes.get("rgb_color") is None async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", '{"hello": [1, 2, 3]}') async_fire_mqtt_message(hass, "test_light_rgb/status", '{"hello": "ON"}') async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", '{"hello": "50"}') async_fire_mqtt_message( hass, "test_light_rgb/color_temp/status", '{"hello": "300"}' ) async_fire_mqtt_message( hass, "test_light_rgb/effect/status", '{"hello": "rainbow"}' ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 50 assert state.attributes.get("rgb_color") == (84, 169, 255) assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") == "rainbow" assert state.attributes.get("white_value") is None async_fire_mqtt_message( hass, "test_light_rgb/white_value/status", '{"hello": "75"}' ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 50 assert state.attributes.get("rgb_color") == (255, 187, 131) assert state.attributes.get("color_temp") == 300 assert state.attributes.get("effect") == "rainbow" assert state.attributes.get("white_value") == 75 async_fire_mqtt_message(hass, "test_light_rgb/hs/status", '{"hello": [100,50]}') async_fire_mqtt_message(hass, "test_light_rgb/white_value/status", '{"hello": "0"}') state = hass.states.get("light.test") assert state.attributes.get("hs_color") == (100, 50) async_fire_mqtt_message( hass, "test_light_rgb/xy/status", '{"hello": [0.123,0.123]}' ) state = hass.states.get("light.test") assert state.attributes.get("xy_color") == (0.14, 0.131) async_fire_mqtt_message(hass, "test_light_rgb/status", '{"hello": null}') state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN async def test_controlling_state_via_topic_with_templates( hass, mqtt_mock_entry_with_yaml_config ): """Test the setting of the state with a template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/brightness/set", "rgb_command_topic": "test_light_rgb/rgb/set", "rgbw_command_topic": "test_light_rgb/rgbw/set", "rgbww_command_topic": "test_light_rgb/rgbw/set", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "xy_command_topic": "test_light_rgb/xy/set", "brightness_state_topic": "test_light_rgb/brightness/status", "color_temp_state_topic": "test_light_rgb/color_temp/status", "effect_state_topic": "test_light_rgb/effect/status", "hs_state_topic": "test_light_rgb/hs/status", "rgb_state_topic": "test_light_rgb/rgb/status", "rgbw_state_topic": "test_light_rgb/rgbw/status", "rgbww_state_topic": "test_light_rgb/rgbww/status", "xy_state_topic": "test_light_rgb/xy/status", "state_value_template": "{{ value_json.hello }}", "brightness_value_template": "{{ value_json.hello }}", "color_temp_value_template": "{{ value_json.hello }}", "effect_value_template": "{{ value_json.hello }}", "hs_value_template": '{{ value_json.hello | join(",") }}', "rgb_value_template": '{{ value_json.hello | join(",") }}', "rgbw_value_template": '{{ value_json.hello | join(",") }}', "rgbww_value_template": '{{ value_json.hello | join(",") }}', "xy_value_template": '{{ value_json.hello | join(",") }}', } } color_modes = ["color_temp", "hs", "rgb", "rgbw", "rgbww", "xy"] assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("brightness") is None assert state.attributes.get("rgb_color") is None async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", '{"hello": [1, 2, 3]}') async_fire_mqtt_message(hass, "test_light_rgb/status", '{"hello": "ON"}') async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", '{"hello": "50"}') async_fire_mqtt_message( hass, "test_light_rgb/effect/status", '{"hello": "rainbow"}' ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 50 assert state.attributes.get("rgb_color") == (1, 2, 3) assert state.attributes.get("effect") == "rainbow" assert state.attributes.get(light.ATTR_COLOR_MODE) == "rgb" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message( hass, "test_light_rgb/rgbw/status", '{"hello": [1, 2, 3, 4]}' ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgbw_color") == (1, 2, 3, 4) assert state.attributes.get(light.ATTR_COLOR_MODE) == "rgbw" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message( hass, "test_light_rgb/rgbww/status", '{"hello": [1, 2, 3, 4, 5]}' ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgbww_color") == (1, 2, 3, 4, 5) assert state.attributes.get(light.ATTR_COLOR_MODE) == "rgbww" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message( hass, "test_light_rgb/color_temp/status", '{"hello": "300"}' ) state = hass.states.get("light.test") assert state.attributes.get("color_temp") == 300 assert state.attributes.get(light.ATTR_COLOR_MODE) == "color_temp" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/hs/status", '{"hello": [100,50]}') state = hass.states.get("light.test") assert state.attributes.get("hs_color") == (100, 50) assert state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message( hass, "test_light_rgb/xy/status", '{"hello": [0.123,0.123]}' ) state = hass.states.get("light.test") assert state.attributes.get("xy_color") == (0.123, 0.123) assert state.attributes.get(light.ATTR_COLOR_MODE) == "xy" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async def test_legacy_sending_mqtt_commands_and_optimistic( hass, mqtt_mock_entry_with_yaml_config ): """Test the sending of command in optimistic mode.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/brightness/set", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_command_topic": "test_light_rgb/xy/set", "effect_list": ["colorloop", "random"], "qos": 2, "payload_on": "on", "payload_off": "off", } } color_modes = ["color_temp", "hs", "rgbw"] fake_state = ha.State( "light.test", "on", { "brightness": 95, "hs_color": [100, 100], "effect": "random", "color_temp": 100, # TODO: Test restoring state with white_value "white_value": 0, }, ) with patch( "homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state", return_value=fake_state, ), assert_setup_component(1, light.DOMAIN): assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 95 assert state.attributes.get("hs_color") == (100, 100) assert state.attributes.get("effect") == "random" assert state.attributes.get("color_temp") is None assert state.attributes.get("white_value") is None assert state.attributes.get(ATTR_ASSUMED_STATE) assert state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_on(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", "on", 2, False ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", "off", 2, False ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_OFF mqtt_mock.reset_mock() await common.async_turn_on( hass, "light.test", brightness=50, xy_color=[0.123, 0.123] ) state = hass.states.get("light.test") assert state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_on(hass, "light.test", brightness=50, hs_color=[359, 78]) state = hass.states.get("light.test") assert state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_on(hass, "light.test", rgb_color=[255, 128, 0]) state = hass.states.get("light.test") assert state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 2, False), call("test_light_rgb/rgb/set", "255,128,0", 2, False), call("test_light_rgb/brightness/set", "50", 2, False), call("test_light_rgb/hs/set", "359.0,78.0", 2, False), call("test_light_rgb/xy/set", "0.14,0.131", 2, False), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes["rgb_color"] == (255, 128, 0) assert state.attributes["brightness"] == 50 assert state.attributes["hs_color"] == (30.118, 100) assert state.attributes.get("white_value") is None assert state.attributes["xy_color"] == (0.611, 0.375) assert state.attributes.get("color_temp") is None await common.async_turn_on(hass, "light.test", white_value=80, color_temp=125) state = hass.states.get("light.test") assert state.attributes.get(light.ATTR_COLOR_MODE) == "color_temp" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/white_value/set", "80", 2, False), call("test_light_rgb/color_temp/set", "125", 2, False), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (221, 229, 255) assert state.attributes["brightness"] == 50 assert state.attributes.get("hs_color") == (224.772, 13.249) assert state.attributes["white_value"] == 80 assert state.attributes.get("xy_color") == (0.296, 0.301) assert state.attributes["color_temp"] == 125 async def test_sending_mqtt_commands_and_optimistic( hass, mqtt_mock_entry_with_yaml_config ): """Test the sending of command in optimistic mode.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/brightness/set", "rgb_command_topic": "test_light_rgb/rgb/set", "rgbw_command_topic": "test_light_rgb/rgbw/set", "rgbww_command_topic": "test_light_rgb/rgbww/set", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "xy_command_topic": "test_light_rgb/xy/set", "effect_list": ["colorloop", "random"], "qos": 2, "payload_on": "on", "payload_off": "off", } } color_modes = ["color_temp", "hs", "rgb", "rgbw", "rgbww", "xy"] fake_state = ha.State( "light.test", "on", { "brightness": 95, "hs_color": [100, 100], "effect": "random", "color_temp": 100, "color_mode": "hs", }, ) with patch( "homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state", return_value=fake_state, ), assert_setup_component(1, light.DOMAIN): assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 95 assert state.attributes.get("hs_color") == (100, 100) assert state.attributes.get("effect") == "random" assert state.attributes.get("color_temp") is None assert state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes assert state.attributes.get(ATTR_ASSUMED_STATE) await common.async_turn_on(hass, "light.test", effect="colorloop") mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 2, False), call("test_light_rgb/effect/set", "colorloop", 2, False), ], any_order=True, ) assert mqtt_mock.async_publish.call_count == 2 mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("effect") == "colorloop" assert state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", "off", 2, False ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get(light.ATTR_COLOR_MODE) is None assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_on( hass, "light.test", brightness=10, rgb_color=[80, 40, 20] ) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 2, False), call("test_light_rgb/brightness/set", "10", 2, False), call("test_light_rgb/rgb/set", "80,40,20", 2, False), ], any_order=True, ) assert mqtt_mock.async_publish.call_count == 3 mqtt_mock.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 10 assert state.attributes.get("rgb_color") == (80, 40, 20) assert state.attributes.get(light.ATTR_COLOR_MODE) == "rgb" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_on( hass, "light.test", brightness=20, rgbw_color=[80, 40, 20, 10] ) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 2, False), call("test_light_rgb/brightness/set", "20", 2, False), call("test_light_rgb/rgbw/set", "80,40,20,10", 2, False), ], any_order=True, ) assert mqtt_mock.async_publish.call_count == 3 mqtt_mock.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 20 assert state.attributes.get("rgbw_color") == (80, 40, 20, 10) assert state.attributes.get(light.ATTR_COLOR_MODE) == "rgbw" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_on( hass, "light.test", brightness=40, rgbww_color=[80, 40, 20, 10, 8] ) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 2, False), call("test_light_rgb/brightness/set", "40", 2, False), call("test_light_rgb/rgbww/set", "80,40,20,10,8", 2, False), ], any_order=True, ) assert mqtt_mock.async_publish.call_count == 3 mqtt_mock.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 40 assert state.attributes.get("rgbww_color") == (80, 40, 20, 10, 8) assert state.attributes.get(light.ATTR_COLOR_MODE) == "rgbww" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_on(hass, "light.test", brightness=50, hs_color=[359, 78]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 2, False), call("test_light_rgb/brightness/set", "50", 2, False), call("test_light_rgb/hs/set", "359.0,78.0", 2, False), ], any_order=True, ) assert mqtt_mock.async_publish.call_count == 3 mqtt_mock.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 50 assert state.attributes.get("hs_color") == (359.0, 78.0) assert state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_on(hass, "light.test", brightness=60, xy_color=[0.2, 0.3]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 2, False), call("test_light_rgb/brightness/set", "60", 2, False), call("test_light_rgb/xy/set", "0.2,0.3", 2, False), ], any_order=True, ) assert mqtt_mock.async_publish.call_count == 3 mqtt_mock.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 60 assert state.attributes.get("xy_color") == (0.2, 0.3) assert state.attributes.get(light.ATTR_COLOR_MODE) == "xy" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_on(hass, "light.test", color_temp=125) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/color_temp/set", "125", 2, False), ], any_order=True, ) assert mqtt_mock.async_publish.call_count == 2 mqtt_mock.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 60 assert state.attributes.get("color_temp") == 125 assert state.attributes.get(light.ATTR_COLOR_MODE) == "color_temp" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async def test_sending_mqtt_rgb_command_with_template( hass, mqtt_mock_entry_with_yaml_config ): """Test the sending of RGB command with template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_rgb/set", "rgb_command_topic": "test_light_rgb/rgb/set", "rgb_command_template": '{{ "#%02x%02x%02x" | ' "format(red, green, blue)}}", "payload_on": "on", "payload_off": "off", "qos": 0, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", rgb_color=[255, 128, 64]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 0, False), call("test_light_rgb/rgb/set", "#ff8040", 0, False), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes["rgb_color"] == (255, 128, 64) async def test_sending_mqtt_rgbw_command_with_template( hass, mqtt_mock_entry_with_yaml_config ): """Test the sending of RGBW command with template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_rgb/set", "rgbw_command_topic": "test_light_rgb/rgbw/set", "rgbw_command_template": '{{ "#%02x%02x%02x%02x" | ' "format(red, green, blue, white)}}", "payload_on": "on", "payload_off": "off", "qos": 0, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", rgbw_color=[255, 128, 64, 32]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 0, False), call("test_light_rgb/rgbw/set", "#ff804020", 0, False), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes["rgbw_color"] == (255, 128, 64, 32) async def test_sending_mqtt_rgbww_command_with_template( hass, mqtt_mock_entry_with_yaml_config ): """Test the sending of RGBWW command with template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_rgb/set", "rgbww_command_topic": "test_light_rgb/rgbww/set", "rgbww_command_template": '{{ "#%02x%02x%02x%02x%02x" | ' "format(red, green, blue, cold_white, warm_white)}}", "payload_on": "on", "payload_off": "off", "qos": 0, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", rgbww_color=[255, 128, 64, 32, 16]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 0, False), call("test_light_rgb/rgbww/set", "#ff80402010", 0, False), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes["rgbww_color"] == (255, 128, 64, 32, 16) async def test_sending_mqtt_color_temp_command_with_template( hass, mqtt_mock_entry_with_yaml_config ): """Test the sending of Color Temp command with template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_color_temp/set", "color_temp_command_topic": "test_light_color_temp/color_temp/set", "color_temp_command_template": "{{ (1000 / value) | round(0) }}", "payload_on": "on", "payload_off": "off", "qos": 0, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", color_temp=100) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_color_temp/set", "on", 0, False), call("test_light_color_temp/color_temp/set", "10", 0, False), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes["color_temp"] == 100 async def test_on_command_first(hass, mqtt_mock_entry_with_yaml_config): """Test on command being sent before brightness.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "brightness_command_topic": "test_light/bright", "on_command_type": "first", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", brightness=50) # Should get the following MQTT messages. # test_light/set: 'ON' # test_light/bright: 50 mqtt_mock.async_publish.assert_has_calls( [ call("test_light/set", "ON", 0, False), call("test_light/bright", "50", 0, False), ], ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) async def test_on_command_last(hass, mqtt_mock_entry_with_yaml_config): """Test on command being sent after brightness.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "brightness_command_topic": "test_light/bright", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", brightness=50) # Should get the following MQTT messages. # test_light/bright: 50 # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/bright", "50", 0, False), call("test_light/set", "ON", 0, False), ], ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) async def test_on_command_brightness(hass, mqtt_mock_entry_with_yaml_config): """Test on command being sent as only brightness.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "brightness_command_topic": "test_light/bright", "rgb_command_topic": "test_light/rgb", "on_command_type": "brightness", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN # Turn on w/ no brightness - should set to max await common.async_turn_on(hass, "light.test") # Should get the following MQTT messages. # test_light/bright: 255 mqtt_mock.async_publish.assert_called_once_with( "test_light/bright", "255", 0, False ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) mqtt_mock.async_publish.reset_mock() # Turn on w/ brightness await common.async_turn_on(hass, "light.test", brightness=50) mqtt_mock.async_publish.assert_called_once_with("test_light/bright", "50", 0, False) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") # Turn on w/ just a color to ensure brightness gets # added and sent. await common.async_turn_on(hass, "light.test", rgb_color=[255, 128, 0]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "255,128,0", 0, False), call("test_light/bright", "50", 0, False), ], any_order=True, ) async def test_on_command_brightness_scaled(hass, mqtt_mock_entry_with_yaml_config): """Test brightness scale.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "brightness_command_topic": "test_light/bright", "brightness_scale": 100, "rgb_command_topic": "test_light/rgb", "on_command_type": "brightness", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN # Turn on w/ no brightness - should set to max await common.async_turn_on(hass, "light.test") # Should get the following MQTT messages. # test_light/bright: 100 mqtt_mock.async_publish.assert_called_once_with( "test_light/bright", "100", 0, False ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) mqtt_mock.async_publish.reset_mock() # Turn on w/ brightness await common.async_turn_on(hass, "light.test", brightness=50) mqtt_mock.async_publish.assert_called_once_with("test_light/bright", "20", 0, False) mqtt_mock.async_publish.reset_mock() # Turn on w/ max brightness await common.async_turn_on(hass, "light.test", brightness=255) mqtt_mock.async_publish.assert_called_once_with( "test_light/bright", "100", 0, False ) mqtt_mock.async_publish.reset_mock() # Turn on w/ min brightness await common.async_turn_on(hass, "light.test", brightness=1) mqtt_mock.async_publish.assert_called_once_with("test_light/bright", "1", 0, False) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") # Turn on w/ just a color to ensure brightness gets # added and sent. await common.async_turn_on(hass, "light.test", rgb_color=[255, 128, 0]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "255,128,0", 0, False), call("test_light/bright", "1", 0, False), ], any_order=True, ) async def test_legacy_on_command_rgb(hass, mqtt_mock_entry_with_yaml_config): """Test on command in RGB brightness mode.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "rgb_command_topic": "test_light/rgb", "white_value_command_topic": "test_light/white_value", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", brightness=127) # Should get the following MQTT messages. # test_light/rgb: '127,127,127' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "127,127,127", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=255) # Should get the following MQTT messages. # test_light/rgb: '255,255,255' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "255,255,255", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=1) # Should get the following MQTT messages. # test_light/rgb: '1,1,1' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "1,1,1", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) # Ensure color gets scaled with brightness. await common.async_turn_on(hass, "light.test", rgb_color=[255, 128, 0]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "1,0,0", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=255) # Should get the following MQTT messages. # test_light/rgb: '255,128,0' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "255,128,0", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() async def test_on_command_rgb(hass, mqtt_mock_entry_with_yaml_config): """Test on command in RGB brightness mode.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "rgb_command_topic": "test_light/rgb", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", brightness=127) # Should get the following MQTT messages. # test_light/rgb: '127,127,127' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "127,127,127", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=255) # Should get the following MQTT messages. # test_light/rgb: '255,255,255' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "255,255,255", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=1) # Should get the following MQTT messages. # test_light/rgb: '1,1,1' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "1,1,1", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) # Ensure color gets scaled with brightness. await common.async_turn_on(hass, "light.test", rgb_color=[255, 128, 0]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "1,0,0", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=255) # Should get the following MQTT messages. # test_light/rgb: '255,128,0' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "255,128,0", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() async def test_on_command_rgbw(hass, mqtt_mock_entry_with_yaml_config): """Test on command in RGBW brightness mode.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "rgbw_command_topic": "test_light/rgbw", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", brightness=127) # Should get the following MQTT messages. # test_light/rgbw: '127,127,127,127' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbw", "127,127,127,127", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=255) # Should get the following MQTT messages. # test_light/rgbw: '255,255,255,255' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbw", "255,255,255,255", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=1) # Should get the following MQTT messages. # test_light/rgbw: '1,1,1,1' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbw", "1,1,1,1", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) # Ensure color gets scaled with brightness. await common.async_turn_on(hass, "light.test", rgbw_color=[255, 128, 0, 16]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbw", "1,0,0,0", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=255) # Should get the following MQTT messages. # test_light/rgbw: '255,128,0' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbw", "255,128,0,16", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() async def test_on_command_rgbww(hass, mqtt_mock_entry_with_yaml_config): """Test on command in RGBWW brightness mode.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "rgbww_command_topic": "test_light/rgbww", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", brightness=127) # Should get the following MQTT messages. # test_light/rgbww: '127,127,127,127,127' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbww", "127,127,127,127,127", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=255) # Should get the following MQTT messages. # test_light/rgbww: '255,255,255,255,255' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbww", "255,255,255,255,255", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=1) # Should get the following MQTT messages. # test_light/rgbww: '1,1,1,1,1' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbww", "1,1,1,1,1", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) # Ensure color gets scaled with brightness. await common.async_turn_on(hass, "light.test", rgbww_color=[255, 128, 0, 16, 32]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbww", "1,0,0,0,0", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=255) # Should get the following MQTT messages. # test_light/rgbww: '255,128,0,16,32' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbww", "255,128,0,16,32", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() async def test_on_command_rgb_template(hass, mqtt_mock_entry_with_yaml_config): """Test on command in RGB brightness mode with RGB template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "rgb_command_topic": "test_light/rgb", "rgb_command_template": "{{ red }}/{{ green }}/{{ blue }}", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", brightness=127) # Should get the following MQTT messages. # test_light/rgb: '127/127/127' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "127/127/127", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) async def test_on_command_rgbw_template(hass, mqtt_mock_entry_with_yaml_config): """Test on command in RGBW brightness mode with RGBW template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "rgbw_command_topic": "test_light/rgbw", "rgbw_command_template": "{{ red }}/{{ green }}/{{ blue }}/{{ white }}", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", brightness=127) # Should get the following MQTT messages. # test_light/rgb: '127/127/127/127' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbw", "127/127/127/127", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) async def test_on_command_rgbww_template(hass, mqtt_mock_entry_with_yaml_config): """Test on command in RGBWW brightness mode with RGBWW template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "rgbww_command_topic": "test_light/rgbww", "rgbww_command_template": "{{ red }}/{{ green }}/{{ blue }}/{{ cold_white }}/{{ warm_white }}", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", brightness=127) # Should get the following MQTT messages. # test_light/rgb: '127/127/127/127/127' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbww", "127/127/127/127/127", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) async def test_on_command_white(hass, mqtt_mock_entry_with_yaml_config): """Test sending commands for RGB + white light.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "tasmota_B94927/cmnd/POWER", "state_value_template": "{{ value_json.POWER }}", "payload_off": "OFF", "payload_on": "ON", "brightness_command_topic": "tasmota_B94927/cmnd/Dimmer", "brightness_scale": 100, "on_command_type": "brightness", "brightness_value_template": "{{ value_json.Dimmer }}", "rgb_command_topic": "tasmota_B94927/cmnd/Color2", "rgb_value_template": "{{value_json.Color.split(',')[0:3]|join(',')}}", "white_command_topic": "tasmota_B94927/cmnd/White", "white_scale": 100, "color_mode_value_template": "{% if value_json.White %} white {% else %} rgb {% endif %}", "qos": "0", } } color_modes = ["rgb", "white"] assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("brightness") is None assert state.attributes.get("rgb_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) is None assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes assert state.attributes.get(ATTR_ASSUMED_STATE) await common.async_turn_on(hass, "light.test", brightness=192) mqtt_mock.async_publish.assert_has_calls( [ call("tasmota_B94927/cmnd/Dimmer", "75", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", white=255) mqtt_mock.async_publish.assert_has_calls( [ call("tasmota_B94927/cmnd/White", "100", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", white=64) mqtt_mock.async_publish.assert_has_calls( [ call("tasmota_B94927/cmnd/White", "25", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test") mqtt_mock.async_publish.assert_has_calls( [ call("tasmota_B94927/cmnd/Dimmer", "25", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with( "tasmota_B94927/cmnd/POWER", "OFF", 0, False ) async def test_explicit_color_mode(hass, mqtt_mock_entry_with_yaml_config): """Test explicit color mode over mqtt.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", "color_mode_state_topic": "test_light_rgb/color_mode/status", "brightness_state_topic": "test_light_rgb/brightness/status", "brightness_command_topic": "test_light_rgb/brightness/set", "rgb_state_topic": "test_light_rgb/rgb/status", "rgb_command_topic": "test_light_rgb/rgb/set", "rgbw_state_topic": "test_light_rgb/rgbw/status", "rgbw_command_topic": "test_light_rgb/rgbw/set", "rgbww_state_topic": "test_light_rgb/rgbww/status", "rgbww_command_topic": "test_light_rgb/rgbww/set", "color_temp_state_topic": "test_light_rgb/color_temp/status", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_state_topic": "test_light_rgb/effect/status", "effect_command_topic": "test_light_rgb/effect/set", "hs_state_topic": "test_light_rgb/hs/status", "hs_command_topic": "test_light_rgb/hs/set", "xy_state_topic": "test_light_rgb/xy/status", "xy_command_topic": "test_light_rgb/xy/set", "qos": "0", "payload_on": 1, "payload_off": 0, } } color_modes = ["color_temp", "hs", "rgb", "rgbw", "rgbww", "xy"] assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("rgb_color") is None assert state.attributes.get("rgbw_color") is None assert state.attributes.get("rgbww_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) is None assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_light_rgb/status", "1") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("rgb_color") is None assert state.attributes.get("rgbw_color") is None assert state.attributes.get("rgbww_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/status", "0") state = hass.states.get("light.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "test_light_rgb/status", "1") async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", "100") light_state = hass.states.get("light.test") assert light_state.attributes.get("brightness") is None assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/color_temp/status", "300") light_state = hass.states.get("light.test") assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/effect/status", "rainbow") light_state = hass.states.get("light.test") assert light_state.attributes["effect"] == "rainbow" assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", "125,125,125") light_state = hass.states.get("light.test") assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/rgbw/status", "80,40,20,10") light_state = hass.states.get("light.test") assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/rgbww/status", "80,40,20,10,8") light_state = hass.states.get("light.test") assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/hs/status", "200,50") light_state = hass.states.get("light.test") assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/xy/status", "0.675,0.322") light_state = hass.states.get("light.test") assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "color_temp") light_state = hass.states.get("light.test") assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "color_temp" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "rgb") light_state = hass.states.get("light.test") assert light_state.attributes.get("rgb_color") == (125, 125, 125) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "rgb" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "rgbw") light_state = hass.states.get("light.test") assert light_state.attributes.get("rgbw_color") == (80, 40, 20, 10) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "rgbw" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "rgbww") light_state = hass.states.get("light.test") assert light_state.attributes.get("rgbww_color") == (80, 40, 20, 10, 8) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "rgbww" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "hs") light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (200, 50) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "xy") light_state = hass.states.get("light.test") assert light_state.attributes.get("xy_color") == (0.675, 0.322) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "xy" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async def test_explicit_color_mode_templated(hass, mqtt_mock_entry_with_yaml_config): """Test templated explicit color mode over mqtt.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", "color_mode_state_topic": "test_light_rgb/color_mode/status", "color_mode_value_template": "{{ value_json.color_mode }}", "brightness_state_topic": "test_light_rgb/brightness/status", "brightness_command_topic": "test_light_rgb/brightness/set", "color_temp_state_topic": "test_light_rgb/color_temp/status", "color_temp_command_topic": "test_light_rgb/color_temp/set", "hs_state_topic": "test_light_rgb/hs/status", "hs_command_topic": "test_light_rgb/hs/set", "qos": "0", "payload_on": 1, "payload_off": 0, } } color_modes = ["color_temp", "hs"] assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("hs_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) is None assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_light_rgb/status", "1") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("hs_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/status", "0") state = hass.states.get("light.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "test_light_rgb/status", "1") async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", "100") light_state = hass.states.get("light.test") assert light_state.attributes.get("brightness") is None assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/color_temp/status", "300") light_state = hass.states.get("light.test") assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/hs/status", "200,50") light_state = hass.states.get("light.test") assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message( hass, "test_light_rgb/color_mode/status", '{"color_mode":"color_temp"}' ) light_state = hass.states.get("light.test") assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "color_temp" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message( hass, "test_light_rgb/color_mode/status", '{"color_mode":"hs"}' ) light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (200, 50) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async def test_white_state_update(hass, mqtt_mock_entry_with_yaml_config): """Test state updates for RGB + white light.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "tasmota_B94927/tele/STATE", "command_topic": "tasmota_B94927/cmnd/POWER", "state_value_template": "{{ value_json.POWER }}", "payload_off": "OFF", "payload_on": "ON", "brightness_command_topic": "tasmota_B94927/cmnd/Dimmer", "brightness_state_topic": "tasmota_B94927/tele/STATE", "brightness_scale": 100, "on_command_type": "brightness", "brightness_value_template": "{{ value_json.Dimmer }}", "rgb_command_topic": "tasmota_B94927/cmnd/Color2", "rgb_state_topic": "tasmota_B94927/tele/STATE", "rgb_value_template": "{{value_json.Color.split(',')[0:3]|join(',')}}", "white_command_topic": "tasmota_B94927/cmnd/White", "white_scale": 100, "color_mode_state_topic": "tasmota_B94927/tele/STATE", "color_mode_value_template": "{% if value_json.White %} white {% else %} rgb {% endif %}", "qos": "0", } } color_modes = ["rgb", "white"] assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("brightness") is None assert state.attributes.get("rgb_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) is None assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message( hass, "tasmota_B94927/tele/STATE", '{"POWER":"ON","Dimmer":50,"Color":"0,0,0,128","White":50}', ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 128 assert state.attributes.get("rgb_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) == "white" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message( hass, "tasmota_B94927/tele/STATE", '{"POWER":"ON","Dimmer":50,"Color":"128,64,32,0","White":0}', ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 128 assert state.attributes.get("rgb_color") == (128, 64, 32) assert state.attributes.get(light.ATTR_COLOR_MODE) == "rgb" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async def test_effect(hass, mqtt_mock_entry_with_yaml_config): """Test effect.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "effect_command_topic": "test_light/effect/set", "effect_list": ["rainbow", "colorloop"], } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", effect="rainbow") # Should get the following MQTT messages. # test_light/effect/set: 'rainbow' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/effect/set", "rainbow", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) async def test_availability_when_connection_lost( hass, mqtt_mock_entry_with_yaml_config ): """Test availability after MQTT disconnection.""" await help_test_availability_when_connection_lost( hass, mqtt_mock_entry_with_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_availability_without_topic(hass, mqtt_mock_entry_with_yaml_config): """Test availability without defined availability topic.""" await help_test_availability_without_topic( hass, mqtt_mock_entry_with_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_default_availability_payload(hass, mqtt_mock_entry_with_yaml_config): """Test availability by default payload with defined topic.""" await help_test_default_availability_payload( hass, mqtt_mock_entry_with_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_custom_availability_payload(hass, mqtt_mock_entry_with_yaml_config): """Test availability by custom payload with defined topic.""" await help_test_custom_availability_payload( hass, mqtt_mock_entry_with_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_setting_attribute_via_mqtt_json_message( hass, mqtt_mock_entry_with_yaml_config ): """Test the setting of attribute via MQTT with JSON payload.""" await help_test_setting_attribute_via_mqtt_json_message( hass, mqtt_mock_entry_with_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_setting_blocked_attribute_via_mqtt_json_message( hass, mqtt_mock_entry_no_yaml_config ): """Test the setting of attribute via MQTT with JSON payload.""" await help_test_setting_blocked_attribute_via_mqtt_json_message( hass, mqtt_mock_entry_no_yaml_config, light.DOMAIN, DEFAULT_CONFIG, MQTT_LIGHT_ATTRIBUTES_BLOCKED, ) async def test_setting_attribute_with_template(hass, mqtt_mock_entry_with_yaml_config): """Test the setting of attribute via MQTT with JSON payload.""" await help_test_setting_attribute_with_template( hass, mqtt_mock_entry_with_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_update_with_json_attrs_not_dict( hass, mqtt_mock_entry_with_yaml_config, caplog ): """Test attributes get extracted from a JSON result.""" await help_test_update_with_json_attrs_not_dict( hass, mqtt_mock_entry_with_yaml_config, caplog, light.DOMAIN, DEFAULT_CONFIG ) async def test_update_with_json_attrs_bad_JSON( hass, mqtt_mock_entry_with_yaml_config, caplog ): """Test attributes get extracted from a JSON result.""" await help_test_update_with_json_attrs_bad_JSON( hass, mqtt_mock_entry_with_yaml_config, caplog, light.DOMAIN, DEFAULT_CONFIG ) async def test_discovery_update_attr(hass, mqtt_mock_entry_no_yaml_config, caplog): """Test update of discovered MQTTAttributes.""" await help_test_discovery_update_attr( hass, mqtt_mock_entry_no_yaml_config, caplog, light.DOMAIN, DEFAULT_CONFIG ) async def test_unique_id(hass, mqtt_mock_entry_with_yaml_config): """Test unique id option only creates one light per unique_id.""" config = { light.DOMAIN: [ { "platform": "mqtt", "name": "Test 1", "state_topic": "test-topic", "command_topic": "test_topic", "unique_id": "TOTALLY_UNIQUE", }, { "platform": "mqtt", "name": "<NAME>", "state_topic": "test-topic", "command_topic": "test_topic", "unique_id": "TOTALLY_UNIQUE", }, ] } await help_test_unique_id( hass, mqtt_mock_entry_with_yaml_config, light.DOMAIN, config ) async def test_discovery_removal_light(hass, mqtt_mock_entry_no_yaml_config, caplog): """Test removal of discovered light.""" data = ( '{ "name": "test",' ' "state_topic": "test_topic",' ' "command_topic": "test_topic" }' ) await help_test_discovery_removal( hass, mqtt_mock_entry_no_yaml_config, caplog, light.DOMAIN, data ) async def test_discovery_deprecated(hass, mqtt_mock_entry_no_yaml_config, caplog): """Test discovery of mqtt light with deprecated platform option.""" await mqtt_mock_entry_no_yaml_config() data = ( '{ "name": "Beer",' ' "platform": "mqtt",' ' "command_topic": "test_topic"}' ) async_fire_mqtt_message(hass, "homeassistant/light/bla/config", data) await hass.async_block_till_done() state = hass.states.get("light.beer") assert state is not None assert state.name == "Beer" async def test_discovery_update_light_topic_and_template( hass, mqtt_mock_entry_no_yaml_config, caplog ): """Test update of discovered light.""" config1 = { "name": "Beer", "state_topic": "test_light_rgb/state1", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/state1", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_command_topic": "test_light_rgb/state1", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_command_topic": "test_light_rgb/xy/set", "brightness_state_topic": "test_light_rgb/state1", "color_temp_state_topic": "test_light_rgb/state1", "effect_state_topic": "test_light_rgb/state1", "hs_state_topic": "test_light_rgb/state1", "rgb_state_topic": "test_light_rgb/state1", "white_value_state_topic": "test_light_rgb/state1", "xy_state_topic": "test_light_rgb/state1", "state_value_template": "{{ value_json.state1.state }}", "brightness_value_template": "{{ value_json.state1.brightness }}", "color_temp_value_template": "{{ value_json.state1.ct }}", "effect_value_template": "{{ value_json.state1.fx }}", "hs_value_template": "{{ value_json.state1.hs }}", "rgb_value_template": "{{ value_json.state1.rgb }}", "white_value_template": "{{ value_json.state1.white }}", "xy_value_template": "{{ value_json.state1.xy }}", } config2 = { "name": "Milk", "state_topic": "test_light_rgb/state2", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/state2", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_command_topic": "test_light_rgb/state2", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_command_topic": "test_light_rgb/xy/set", "brightness_state_topic": "test_light_rgb/state2", "color_temp_state_topic": "test_light_rgb/state2", "effect_state_topic": "test_light_rgb/state2", "hs_state_topic": "test_light_rgb/state2", "rgb_state_topic": "test_light_rgb/state2", "white_value_state_topic": "test_light_rgb/state2", "xy_state_topic": "test_light_rgb/state2", "state_value_template": "{{ value_json.state2.state }}", "brightness_value_template": "{{ value_json.state2.brightness }}", "color_temp_value_template": "{{ value_json.state2.ct }}", "effect_value_template": "{{ value_json.state2.fx }}", "hs_value_template": "{{ value_json.state2.hs }}", "rgb_value_template": "{{ value_json.state2.rgb }}", "white_value_template": "{{ value_json.state2.white }}", "xy_value_template": "{{ value_json.state2.xy }}", } state_data1 = [ ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "brightness":100, "ct":123, "white":100, "fx":"cycle"}}', ) ], "on", [ ("brightness", 100), ("color_temp", 123), ("white_value", 100), ("effect", "cycle"), ], ), ( [("test_light_rgb/state1", '{"state1":{"state":"OFF"}}')], "off", None, ), ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "hs":"1,2", "white":0}}', ) ], "on", [("hs_color", (1, 2)), ("white_value", None)], ), ( [ ( "test_light_rgb/state1", '{"state1":{"rgb":"255,127,63"}}', ) ], "on", [("rgb_color", (255, 127, 63))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"xy":"0.3, 0.4"}}', ) ], "on", [("xy_color", (0.3, 0.401))], ), ] state_data2 = [ ( [ ( "test_light_rgb/state2", '{"state2":{"state":"ON", "brightness":50, "ct":200, "white":50, "fx":"loop"}}', ) ], "on", [ ("brightness", 50), ("color_temp", 200), ("white_value", 50), ("effect", "loop"), ], ), ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "brightness":100, "ct":123, "fx":"cycle"}}', ), ( "test_light_rgb/state1", '{"state2":{"state":"ON", "brightness":100, "ct":123, "fx":"cycle"}}', ), ( "test_light_rgb/state2", '{"state1":{"state":"ON", "brightness":100, "ct":123, "fx":"cycle"}}', ), ], "on", [("brightness", 50), ("color_temp", 200), ("effect", "loop")], ), ( [("test_light_rgb/state1", '{"state1":{"state":"OFF"}}')], "on", None, ), ( [("test_light_rgb/state1", '{"state2":{"state":"OFF"}}')], "on", None, ), ( [("test_light_rgb/state2", '{"state1":{"state":"OFF"}}')], "on", None, ), ( [("test_light_rgb/state2", '{"state2":{"state":"OFF"}}')], "off", None, ), ( [ ( "test_light_rgb/state2", '{"state2":{"state":"ON", "hs":"1.2,2.2", "white":0}}', ) ], "on", [("hs_color", (1.2, 2.2)), ("white_value", None)], ), ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "hs":"1,2"}}', ), ( "test_light_rgb/state1", '{"state2":{"state":"ON", "hs":"1,2"}}', ), ( "test_light_rgb/state2", '{"state1":{"state":"ON", "hs":"1,2"}}', ), ], "on", [("hs_color", (1.2, 2.2))], ), ( [ ( "test_light_rgb/state2", '{"state2":{"rgb":"63,127,255"}}', ) ], "on", [("rgb_color", (63, 127, 255))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"rgb":"255,127,63"}}', ), ( "test_light_rgb/state1", '{"state2":{"rgb":"255,127,63"}}', ), ( "test_light_rgb/state2", '{"state1":{"rgb":"255,127,63"}}', ), ], "on", [("rgb_color", (63, 127, 255))], ), ( [ ( "test_light_rgb/state2", '{"state2":{"xy":"0.4, 0.3"}}', ) ], "on", [("xy_color", (0.4, 0.3))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"white":50, "xy":"0.3, 0.4"}}', ), ( "test_light_rgb/state1", '{"state2":{"white":50, "xy":"0.3, 0.4"}}', ), ( "test_light_rgb/state2", '{"state1":{"white":50, "xy":"0.3, 0.4"}}', ), ], "on", [("xy_color", (0.4, 0.3))], ), ] await help_test_discovery_update( hass, mqtt_mock_entry_no_yaml_config, caplog, light.DOMAIN, config1, config2, state_data1=state_data1, state_data2=state_data2, ) async def test_discovery_update_light_template( hass, mqtt_mock_entry_no_yaml_config, caplog ): """Test update of discovered light.""" config1 = { "name": "Beer", "state_topic": "test_light_rgb/state1", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/state1", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_command_topic": "test_light_rgb/state1", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_command_topic": "test_light_rgb/xy/set", "brightness_state_topic": "test_light_rgb/state1", "color_temp_state_topic": "test_light_rgb/state1", "effect_state_topic": "test_light_rgb/state1", "hs_state_topic": "test_light_rgb/state1", "rgb_state_topic": "test_light_rgb/state1", "white_value_state_topic": "test_light_rgb/state1", "xy_state_topic": "test_light_rgb/state1", "state_value_template": "{{ value_json.state1.state }}", "brightness_value_template": "{{ value_json.state1.brightness }}", "color_temp_value_template": "{{ value_json.state1.ct }}", "effect_value_template": "{{ value_json.state1.fx }}", "hs_value_template": "{{ value_json.state1.hs }}", "rgb_value_template": "{{ value_json.state1.rgb }}", "white_value_template": "{{ value_json.state1.white }}", "xy_value_template": "{{ value_json.state1.xy }}", } config2 = { "name": "Milk", "state_topic": "test_light_rgb/state1", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/state1", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_command_topic": "test_light_rgb/state1", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_command_topic": "test_light_rgb/xy/set", "brightness_state_topic": "test_light_rgb/state1", "color_temp_state_topic": "test_light_rgb/state1", "effect_state_topic": "test_light_rgb/state1", "hs_state_topic": "test_light_rgb/state1", "rgb_state_topic": "test_light_rgb/state1", "white_value_state_topic": "test_light_rgb/state1", "xy_state_topic": "test_light_rgb/state1", "state_value_template": "{{ value_json.state2.state }}", "brightness_value_template": "{{ value_json.state2.brightness }}", "color_temp_value_template": "{{ value_json.state2.ct }}", "effect_value_template": "{{ value_json.state2.fx }}", "hs_value_template": "{{ value_json.state2.hs }}", "rgb_value_template": "{{ value_json.state2.rgb }}", "white_value_template": "{{ value_json.state2.white }}", "xy_value_template": "{{ value_json.state2.xy }}", } state_data1 = [ ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "brightness":100, "ct":123, "white":100, "fx":"cycle"}}', ) ], "on", [ ("brightness", 100), ("color_temp", 123), ("white_value", 100), ("effect", "cycle"), ], ), ( [("test_light_rgb/state1", '{"state1":{"state":"OFF"}}')], "off", None, ), ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "hs":"1,2", "white":0}}', ) ], "on", [("hs_color", (1, 2))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"rgb":"255,127,63"}}', ) ], "on", [("rgb_color", (255, 127, 63))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"white":0, "xy":"0.3, 0.4"}}', ) ], "on", [("white_value", None), ("xy_color", (0.3, 0.401))], ), ] state_data2 = [ ( [ ( "test_light_rgb/state1", '{"state2":{"state":"ON", "brightness":50, "ct":200, "white":50, "fx":"loop"}}', ) ], "on", [ ("brightness", 50), ("color_temp", 200), ("white_value", 50), ("effect", "loop"), ], ), ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "brightness":100, "ct":123, "fx":"cycle"}}', ), ], "on", [("brightness", 50), ("color_temp", 200), ("effect", "loop")], ), ( [("test_light_rgb/state1", '{"state1":{"state":"OFF"}}')], "on", None, ), ( [("test_light_rgb/state1", '{"state2":{"state":"OFF"}}')], "off", None, ), ( [ ( "test_light_rgb/state1", '{"state2":{"state":"ON", "hs":"1.2,2.2", "white":0}}', ) ], "on", [("hs_color", (1.2, 2.2))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "hs":"1,2"}}', ) ], "on", [("hs_color", (1.2, 2.2))], ), ( [ ( "test_light_rgb/state1", '{"state2":{"rgb":"63,127,255"}}', ) ], "on", [("rgb_color", (63, 127, 255))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"rgb":"255,127,63"}}', ) ], "on", [("rgb_color", (63, 127, 255))], ), ( [ ( "test_light_rgb/state1", '{"state2":{"xy":"0.4, 0.3"}}', ) ], "on", [("white_value", None), ("xy_color", (0.4, 0.3))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"white":50, "xy":"0.3, 0.4"}}', ) ], "on", [("white_value", None), ("xy_color", (0.4, 0.3))], ), ] await help_test_discovery_update( hass, mqtt_mock_entry_no_yaml_config, caplog, light.DOMAIN, config1, config2, state_data1=state_data1, state_data2=state_data2, ) async def test_discovery_update_unchanged_light( hass, mqtt_mock_entry_no_yaml_config, caplog ): """Test update of discovered light.""" data1 = ( '{ "name": "Beer",' ' "state_topic": "test_topic",' ' "command_topic": "test_topic" }' ) with patch( "homeassistant.components.mqtt.light.schema_basic.MqttLight.discovery_update" ) as discovery_update: await help_test_discovery_update_unchanged( hass, mqtt_mock_entry_no_yaml_config, caplog, light.DOMAIN, data1, discovery_update, ) @pytest.mark.no_fail_on_log_exception async def test_discovery_broken(hass, mqtt_mock_entry_no_yaml_config, caplog): """Test handling of bad discovery message.""" data1 = '{ "name": "Beer" }' data2 = ( '{ "name": "Milk",' ' "state_topic": "test_topic",' ' "command_topic": "test_topic" }' ) await help_test_discovery_broken( hass, mqtt_mock_entry_no_yaml_config, caplog, light.DOMAIN, data1, data2 ) async def test_entity_device_info_with_connection(hass, mqtt_mock_entry_no_yaml_config): """Test MQTT light device registry integration.""" await help_test_entity_device_info_with_connection( hass, mqtt_mock_entry_no_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_device_info_with_identifier(hass, mqtt_mock_entry_no_yaml_config): """Test MQTT light device registry integration.""" await help_test_entity_device_info_with_identifier( hass, mqtt_mock_entry_no_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_device_info_update(hass, mqtt_mock_entry_no_yaml_config): """Test device registry update.""" await help_test_entity_device_info_update( hass, mqtt_mock_entry_no_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_device_info_remove(hass, mqtt_mock_entry_no_yaml_config): """Test device registry remove.""" await help_test_entity_device_info_remove( hass, mqtt_mock_entry_no_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_id_update_subscriptions(hass, mqtt_mock_entry_with_yaml_config): """Test MQTT subscriptions are managed when entity_id is updated.""" await help_test_entity_id_update_subscriptions( hass, mqtt_mock_entry_with_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_id_update_discovery_update(hass, mqtt_mock_entry_no_yaml_config): """Test MQTT discovery update when entity_id is updated.""" await help_test_entity_id_update_discovery_update( hass, mqtt_mock_entry_no_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_debug_info_message(hass, mqtt_mock_entry_no_yaml_config): """Test MQTT debug info.""" await help_test_entity_debug_info_message( hass, mqtt_mock_entry_no_yaml_config, light.DOMAIN, DEFAULT_CONFIG, light.SERVICE_TURN_ON, ) async def test_max_mireds(hass, mqtt_mock_entry_with_yaml_config): """Test setting min_mireds and max_mireds.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_max_mireds/set", "color_temp_command_topic": "test_max_mireds/color_temp/set", "max_mireds": 370, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.attributes.get("min_mireds") == 153 assert state.attributes.get("max_mireds") == 370 @pytest.mark.parametrize( "service,topic,parameters,payload,template,tpl_par,tpl_output", [ ( light.SERVICE_TURN_ON, "command_topic", None, "ON", None, None, None, ), ( light.SERVICE_TURN_ON, "white_command_topic", {"white": "255"}, 255, None, None, None, ), ( light.SERVICE_TURN_ON, "brightness_command_topic", {"color_temp": "200", "brightness": "50"}, 50, "brightness_command_template", "value", b"5", ), ( light.SERVICE_TURN_ON, "effect_command_topic", {"rgb_color": [255, 128, 0], "effect": "color_loop"}, "color_loop", "effect_command_template", "value", b"c", ), ( light.SERVICE_TURN_ON, "color_temp_command_topic", {"color_temp": "200"}, 200, "color_temp_command_template", "value", b"2", ), ( light.SERVICE_TURN_ON, "rgb_command_topic", {"rgb_color": [255, 128, 0]}, "255,128,0", "rgb_command_template", "red", b"2", ), ( light.SERVICE_TURN_ON, "hs_command_topic", {"rgb_color": [255, 128, 0]}, "30.118,100.0", None, None, None, ), ( light.SERVICE_TURN_ON, "xy_command_topic", {"hs_color": [30.118, 100.0]}, "0.611,0.375", None, None, None, ), ( light.SERVICE_TURN_OFF, "command_topic", None, "OFF", None, None, None, ), ], ) async def test_publishing_with_custom_encoding( hass, mqtt_mock_entry_with_yaml_config, caplog, service, topic, parameters, payload, template, tpl_par, tpl_output, ): """Test publishing MQTT payload with different encoding.""" domain = light.DOMAIN config = copy.deepcopy(DEFAULT_CONFIG[domain]) if topic == "effect_command_topic": config["effect_list"] = ["random", "color_loop"] elif topic == "white_command_topic": config["rgb_command_topic"] = "some-cmd-topic" await help_test_publishing_with_custom_encoding( hass, mqtt_mock_entry_with_yaml_config, caplog, domain, config, service, topic, parameters, payload, template, tpl_par=tpl_par, tpl_output=tpl_output, ) async def test_reloadable(hass, mqtt_mock_entry_with_yaml_config, caplog, tmp_path): """Test reloading the MQTT platform.""" domain = light.DOMAIN config = DEFAULT_CONFIG[domain] await help_test_reloadable( hass, mqtt_mock_entry_with_yaml_config, caplog, tmp_path, domain, config ) async def test_reloadable_late(hass, mqtt_client_mock, caplog, tmp_path): """Test reloading the MQTT platform with late entry setup.""" domain = light.DOMAIN config = DEFAULT_CONFIG[domain] await help_test_reloadable_late(hass, caplog, tmp_path, domain, config) @pytest.mark.parametrize( "topic,value,attribute,attribute_value,init_payload", [ ("state_topic", "ON", None, "on", None), ("brightness_state_topic", "60", "brightness", 60, ("state_topic", "ON")), ( "color_mode_state_topic", "200", "color_mode", "200", ("state_topic", "ON"), ), ("color_temp_state_topic", "200", "color_temp", 200, ("state_topic", "ON")), ("effect_state_topic", "random", "effect", "random", ("state_topic", "ON")), ("hs_state_topic", "200,50", "hs_color", (200, 50), ("state_topic", "ON")), ( "xy_state_topic", "128,128", "xy_color", (128, 128), ("state_topic", "ON"), ), ( "rgb_state_topic", "255,0,240", "rgb_color", (255, 0, 240), ("state_topic", "ON"), ), ], ) async def test_encoding_subscribable_topics( hass, mqtt_mock_entry_with_yaml_config, caplog, topic, value, attribute, attribute_value, init_payload, ): """Test handling of incoming encoded payload.""" config = copy.deepcopy(DEFAULT_CONFIG[light.DOMAIN]) config[CONF_EFFECT_COMMAND_TOPIC] = "light/CONF_EFFECT_COMMAND_TOPIC" config[CONF_RGB_COMMAND_TOPIC] = "light/CONF_RGB_COMMAND_TOPIC" config[CONF_BRIGHTNESS_COMMAND_TOPIC] = "light/CONF_BRIGHTNESS_COMMAND_TOPIC" config[CONF_COLOR_TEMP_COMMAND_TOPIC] = "light/CONF_COLOR_TEMP_COMMAND_TOPIC" config[CONF_HS_COMMAND_TOPIC] = "light/CONF_HS_COMMAND_TOPIC" config[CONF_RGB_COMMAND_TOPIC] = "light/CONF_RGB_COMMAND_TOPIC" config[CONF_RGBW_COMMAND_TOPIC] = "light/CONF_RGBW_COMMAND_TOPIC" config[CONF_RGBWW_COMMAND_TOPIC] = "light/CONF_RGBWW_COMMAND_TOPIC" config[CONF_XY_COMMAND_TOPIC] = "light/CONF_XY_COMMAND_TOPIC" config[CONF_EFFECT_LIST] = ["colorloop", "random"] if attribute and attribute == "brightness": config[CONF_WHITE_VALUE_COMMAND_TOPIC] = "light/CONF_WHITE_VALUE_COMMAND_TOPIC" await help_test_encoding_subscribable_topics( hass, mqtt_mock_entry_with_yaml_config, caplog, light.DOMAIN, config, topic, value, attribute, attribute_value, init_payload, ) async def test_sending_mqtt_brightness_command_with_template( hass, mqtt_mock_entry_with_yaml_config ): """Test the sending of Brightness command with template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_brightness/set", "brightness_command_topic": "test_light_brightness/brightness/set", "brightness_command_template": "{{ (1000 / value) | round(0) }}", "payload_on": "on", "payload_off": "off", "qos": 0, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", brightness=100) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_brightness/set", "on", 0, False), call("test_light_brightness/brightness/set", "10", 0, False), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes["brightness"] == 100 async def test_sending_mqtt_effect_command_with_template( hass, mqtt_mock_entry_with_yaml_config ): """Test the sending of Effect command with template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_brightness/set", "brightness_command_topic": "test_light_brightness/brightness/set", "effect_command_topic": "test_light_brightness/effect/set", "effect_command_template": '{ "effect": "{{ value }}" }', "effect_list": ["colorloop", "random"], "payload_on": "on", "payload_off": "off", "qos": 0, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", effect="colorloop") mqtt_mock.async_publish.assert_has_calls( [ call("test_light_brightness/set", "on", 0, False), call( "test_light_brightness/effect/set", '{ "effect": "colorloop" }', 0, False, ), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("effect") == "colorloop" async def test_setup_manual_entity_from_yaml(hass): """Test setup manual configured MQTT entity.""" platform = light.DOMAIN config = copy.deepcopy(DEFAULT_CONFIG[platform]) config["name"] = "test" del config["platform"] await help_test_setup_manual_entity_from_yaml(hass, platform, config) assert hass.states.get(f"{platform}.test") is not None
<filename>tests/components/mqtt/test_light.py """The tests for the MQTT light platform. Configuration for RGB Version with brightness: light: platform: mqtt name: "Office Light RGB" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" rgb_state_topic: "office/rgb1/rgb/status" rgb_command_topic: "office/rgb1/rgb/set" qos: 0 payload_on: "on" payload_off: "off" Configuration for XY Version with brightness: light: platform: mqtt name: "Office Light XY" state_topic: "office/xy1/light/status" command_topic: "office/xy1/light/switch" brightness_state_topic: "office/xy1/brightness/status" brightness_command_topic: "office/xy1/brightness/set" xy_state_topic: "office/xy1/xy/status" xy_command_topic: "office/xy1/xy/set" qos: 0 payload_on: "on" payload_off: "off" config without RGB: light: platform: mqtt name: "Office Light" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" qos: 0 payload_on: "on" payload_off: "off" config without RGB and brightness: light: platform: mqtt name: "Office Light" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" qos: 0 payload_on: "on" payload_off: "off" config for RGB Version with brightness and scale: light: platform: mqtt name: "Office Light RGB" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" brightness_scale: 99 rgb_state_topic: "office/rgb1/rgb/status" rgb_command_topic: "office/rgb1/rgb/set" rgb_scale: 99 qos: 0 payload_on: "on" payload_off: "off" config with brightness and color temp light: platform: mqtt name: "Office Light Color Temp" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" brightness_scale: 99 color_temp_state_topic: "office/rgb1/color_temp/status" color_temp_command_topic: "office/rgb1/color_temp/set" qos: 0 payload_on: "on" payload_off: "off" config with brightness and effect light: platform: mqtt name: "Office Light Color Temp" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" brightness_scale: 99 effect_state_topic: "office/rgb1/effect/status" effect_command_topic: "office/rgb1/effect/set" effect_list: - rainbow - colorloop qos: 0 payload_on: "on" payload_off: "off" config for RGB Version with white value and scale: light: platform: mqtt name: "Office Light RGB" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" white_value_state_topic: "office/rgb1/white_value/status" white_value_command_topic: "office/rgb1/white_value/set" white_value_scale: 99 rgb_state_topic: "office/rgb1/rgb/status" rgb_command_topic: "office/rgb1/rgb/set" rgb_scale: 99 qos: 0 payload_on: "on" payload_off: "off" config for RGB Version with RGB command template: light: platform: mqtt name: "Office Light RGB" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" rgb_state_topic: "office/rgb1/rgb/status" rgb_command_topic: "office/rgb1/rgb/set" rgb_command_template: "{{ '#%02x%02x%02x' | format(red, green, blue)}}" qos: 0 payload_on: "on" payload_off: "off" Configuration for HS Version with brightness: light: platform: mqtt name: "Office Light HS" state_topic: "office/hs1/light/status" command_topic: "office/hs1/light/switch" brightness_state_topic: "office/hs1/brightness/status" brightness_command_topic: "office/hs1/brightness/set" hs_state_topic: "office/hs1/hs/status" hs_command_topic: "office/hs1/hs/set" qos: 0 payload_on: "on" payload_off: "off" Configuration with brightness command template: light: platform: mqtt name: "Office Light" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" brightness_command_template: '{ "brightness": "{{ value }}" }' qos: 0 payload_on: "on" payload_off: "off" Configuration with effect command template: light: platform: mqtt name: "Office Light Color Temp" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" effect_state_topic: "office/rgb1/effect/status" effect_command_topic: "office/rgb1/effect/set" effect_command_template: '{ "effect": "{{ value }}" }' effect_list: - rainbow - colorloop qos: 0 payload_on: "on" payload_off: "off" """ import copy from unittest.mock import call, patch import pytest from homeassistant.components import light from homeassistant.components.mqtt.light.schema_basic import ( CONF_BRIGHTNESS_COMMAND_TOPIC, CONF_COLOR_TEMP_COMMAND_TOPIC, CONF_EFFECT_COMMAND_TOPIC, CONF_EFFECT_LIST, CONF_HS_COMMAND_TOPIC, CONF_RGB_COMMAND_TOPIC, CONF_RGBW_COMMAND_TOPIC, CONF_RGBWW_COMMAND_TOPIC, CONF_WHITE_VALUE_COMMAND_TOPIC, CONF_XY_COMMAND_TOPIC, MQTT_LIGHT_ATTRIBUTES_BLOCKED, ) from homeassistant.const import ( ATTR_ASSUMED_STATE, ATTR_SUPPORTED_FEATURES, STATE_OFF, STATE_ON, STATE_UNKNOWN, ) import homeassistant.core as ha from homeassistant.setup import async_setup_component from .test_common import ( help_test_availability_when_connection_lost, help_test_availability_without_topic, help_test_custom_availability_payload, help_test_default_availability_payload, help_test_discovery_broken, help_test_discovery_removal, help_test_discovery_update, help_test_discovery_update_attr, help_test_discovery_update_unchanged, help_test_encoding_subscribable_topics, help_test_entity_debug_info_message, help_test_entity_device_info_remove, help_test_entity_device_info_update, help_test_entity_device_info_with_connection, help_test_entity_device_info_with_identifier, help_test_entity_id_update_discovery_update, help_test_entity_id_update_subscriptions, help_test_publishing_with_custom_encoding, help_test_reloadable, help_test_reloadable_late, help_test_setting_attribute_via_mqtt_json_message, help_test_setting_attribute_with_template, help_test_setting_blocked_attribute_via_mqtt_json_message, help_test_setup_manual_entity_from_yaml, help_test_unique_id, help_test_update_with_json_attrs_bad_JSON, help_test_update_with_json_attrs_not_dict, ) from tests.common import assert_setup_component, async_fire_mqtt_message from tests.components.light import common DEFAULT_CONFIG = { light.DOMAIN: {"platform": "mqtt", "name": "test", "command_topic": "test-topic"} } async def test_fail_setup_if_no_command_topic(hass, mqtt_mock_entry_no_yaml_config): """Test if command fails with command topic.""" assert await async_setup_component( hass, light.DOMAIN, {light.DOMAIN: {"platform": "mqtt", "name": "test"}} ) await hass.async_block_till_done() await mqtt_mock_entry_no_yaml_config() assert hass.states.get("light.test") is None async def test_legacy_rgb_white_light(hass, mqtt_mock_entry_with_yaml_config): """Test legacy RGB + white light flags brightness support.""" assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_rgb/set", "rgb_command_topic": "test_light_rgb/rgb/set", "white_value_command_topic": "test_light_rgb/white/set", } }, ) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") expected_features = ( light.SUPPORT_COLOR | light.SUPPORT_BRIGHTNESS | light.SUPPORT_WHITE_VALUE ) assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == expected_features assert state.attributes.get(light.ATTR_COLOR_MODE) is None assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == ["hs", "rgbw"] async def test_no_color_brightness_color_temp_hs_white_xy_if_no_topics( hass, mqtt_mock_entry_with_yaml_config ): """Test if there is no color and brightness if no topic.""" assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", } }, ) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("rgb_color") is None assert state.attributes.get("rgbw_color") is None assert state.attributes.get("rgbww_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) is None assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == ["onoff"] async_fire_mqtt_message(hass, "test_light_rgb/status", "ON") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("rgb_color") is None assert state.attributes.get("rgbw_color") is None assert state.attributes.get("rgbww_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) == "onoff" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == ["onoff"] async_fire_mqtt_message(hass, "test_light_rgb/status", "OFF") state = hass.states.get("light.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "test_light_rgb/status", "None") state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN async def test_legacy_controlling_state_via_topic( hass, mqtt_mock_entry_with_yaml_config ): """Test the controlling of the state via topic for legacy light (white_value).""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", "brightness_state_topic": "test_light_rgb/brightness/status", "brightness_command_topic": "test_light_rgb/brightness/set", "rgb_state_topic": "test_light_rgb/rgb/status", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_state_topic": "test_light_rgb/color_temp/status", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_state_topic": "test_light_rgb/effect/status", "effect_command_topic": "test_light_rgb/effect/set", "hs_state_topic": "test_light_rgb/hs/status", "hs_command_topic": "test_light_rgb/hs/set", "white_value_state_topic": "test_light_rgb/white_value/status", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_state_topic": "test_light_rgb/xy/status", "xy_command_topic": "test_light_rgb/xy/set", "qos": "0", "payload_on": 1, "payload_off": 0, } } color_modes = ["color_temp", "hs", "rgbw"] assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("rgb_color") is None assert state.attributes.get("rgbw_color") is None assert state.attributes.get("rgbww_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) is None assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_light_rgb/status", "1") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("rgb_color") is None assert state.attributes.get("rgbw_color") is None assert state.attributes.get("rgbww_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/status", "0") state = hass.states.get("light.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "test_light_rgb/status", "1") async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", "100") light_state = hass.states.get("light.test") assert light_state.attributes["brightness"] == 100 assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/color_temp/status", "300") light_state = hass.states.get("light.test") assert light_state.attributes.get("color_temp") is None assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/white_value/status", "100") light_state = hass.states.get("light.test") assert light_state.attributes["white_value"] == 100 assert light_state.attributes["color_temp"] == 300 assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "color_temp" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/effect/status", "rainbow") light_state = hass.states.get("light.test") assert light_state.attributes["effect"] == "rainbow" assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "color_temp" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/status", "1") async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", "125,125,125") light_state = hass.states.get("light.test") assert light_state.attributes.get("rgb_color") == (255, 187, 131) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "color_temp" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/white_value/status", "0") light_state = hass.states.get("light.test") assert light_state.attributes.get("rgb_color") == (255, 255, 255) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/hs/status", "200,50") light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (200, 50) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/xy/status", "0.675,0.322") light_state = hass.states.get("light.test") assert light_state.attributes.get("xy_color") == (0.672, 0.324) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async def test_controlling_state_via_topic(hass, mqtt_mock_entry_with_yaml_config): """Test the controlling of the state via topic.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", "brightness_state_topic": "test_light_rgb/brightness/status", "brightness_command_topic": "test_light_rgb/brightness/set", "rgb_state_topic": "test_light_rgb/rgb/status", "rgb_command_topic": "test_light_rgb/rgb/set", "rgbw_state_topic": "test_light_rgb/rgbw/status", "rgbw_command_topic": "test_light_rgb/rgbw/set", "rgbww_state_topic": "test_light_rgb/rgbww/status", "rgbww_command_topic": "test_light_rgb/rgbww/set", "color_temp_state_topic": "test_light_rgb/color_temp/status", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_state_topic": "test_light_rgb/effect/status", "effect_command_topic": "test_light_rgb/effect/set", "hs_state_topic": "test_light_rgb/hs/status", "hs_command_topic": "test_light_rgb/hs/set", "xy_state_topic": "test_light_rgb/xy/status", "xy_command_topic": "test_light_rgb/xy/set", "qos": "0", "payload_on": 1, "payload_off": 0, } } color_modes = ["color_temp", "hs", "rgb", "rgbw", "rgbww", "xy"] assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("rgb_color") is None assert state.attributes.get("rgbw_color") is None assert state.attributes.get("rgbww_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) is None assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_light_rgb/status", "1") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("rgb_color") is None assert state.attributes.get("rgbw_color") is None assert state.attributes.get("rgbww_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/status", "0") state = hass.states.get("light.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "test_light_rgb/status", "1") async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", "100") light_state = hass.states.get("light.test") assert light_state.attributes.get("brightness") is None assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/color_temp/status", "300") light_state = hass.states.get("light.test") assert light_state.attributes.get("brightness") == 100 assert light_state.attributes["color_temp"] == 300 assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "color_temp" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/effect/status", "rainbow") light_state = hass.states.get("light.test") assert light_state.attributes["effect"] == "rainbow" assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "color_temp" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", "125,125,125") light_state = hass.states.get("light.test") assert light_state.attributes.get("rgb_color") == (125, 125, 125) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "rgb" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/rgbw/status", "80,40,20,10") light_state = hass.states.get("light.test") assert light_state.attributes.get("rgbw_color") == (80, 40, 20, 10) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "rgbw" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/rgbww/status", "80,40,20,10,8") light_state = hass.states.get("light.test") assert light_state.attributes.get("rgbww_color") == (80, 40, 20, 10, 8) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "rgbww" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/hs/status", "200,50") light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (200, 50) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/xy/status", "0.675,0.322") light_state = hass.states.get("light.test") assert light_state.attributes.get("xy_color") == (0.675, 0.322) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "xy" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async def test_legacy_invalid_state_via_topic( hass, mqtt_mock_entry_with_yaml_config, caplog ): """Test handling of empty data via topic.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", "brightness_state_topic": "test_light_rgb/brightness/status", "brightness_command_topic": "test_light_rgb/brightness/set", "rgb_state_topic": "test_light_rgb/rgb/status", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_state_topic": "test_light_rgb/color_temp/status", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_state_topic": "test_light_rgb/effect/status", "effect_command_topic": "test_light_rgb/effect/set", "hs_state_topic": "test_light_rgb/hs/status", "hs_command_topic": "test_light_rgb/hs/set", "white_value_state_topic": "test_light_rgb/white_value/status", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_state_topic": "test_light_rgb/xy/status", "xy_command_topic": "test_light_rgb/xy/set", "qos": "0", "payload_on": 1, "payload_off": 0, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_light_rgb/status", "1") async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", "255,255,255") async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", "255") async_fire_mqtt_message(hass, "test_light_rgb/effect/status", "none") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (255, 255, 255) assert state.attributes.get("brightness") == 255 assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") == "none" assert state.attributes.get("hs_color") == (0, 0) assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") == (0.323, 0.329) async_fire_mqtt_message(hass, "test_light_rgb/status", "") assert "Ignoring empty state message" in caplog.text light_state = hass.states.get("light.test") assert state.state == STATE_ON async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", "") assert "Ignoring empty brightness message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes["brightness"] == 255 async_fire_mqtt_message(hass, "test_light_rgb/effect/status", "") assert "Ignoring empty effect message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes["effect"] == "none" async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", "") assert "Ignoring empty rgb message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("rgb_color") == (255, 255, 255) async_fire_mqtt_message(hass, "test_light_rgb/hs/status", "") assert "Ignoring empty hs message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (0, 0) async_fire_mqtt_message(hass, "test_light_rgb/hs/status", "bad,bad") assert "Failed to parse hs state update" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (0, 0) async_fire_mqtt_message(hass, "test_light_rgb/xy/status", "") assert "Ignoring empty xy-color message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("xy_color") == (0.323, 0.329) async_fire_mqtt_message(hass, "test_light_rgb/color_temp/status", "153") async_fire_mqtt_message(hass, "test_light_rgb/white_value/status", "255") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (255, 254, 250) assert state.attributes.get("brightness") == 255 assert state.attributes.get("color_temp") == 153 assert state.attributes.get("effect") == "none" assert state.attributes.get("hs_color") == (54.768, 1.6) assert state.attributes.get("white_value") == 255 assert state.attributes.get("xy_color") == (0.326, 0.333) async_fire_mqtt_message(hass, "test_light_rgb/color_temp/status", "") assert "Ignoring empty color temp message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes["color_temp"] == 153 async_fire_mqtt_message(hass, "test_light_rgb/white_value/status", "") assert "Ignoring empty white value message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes["white_value"] == 255 async def test_invalid_state_via_topic(hass, mqtt_mock_entry_with_yaml_config, caplog): """Test handling of empty data via topic.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", "brightness_state_topic": "test_light_rgb/brightness/status", "brightness_command_topic": "test_light_rgb/brightness/set", "color_mode_state_topic": "test_light_rgb/color_mode/status", "rgb_state_topic": "test_light_rgb/rgb/status", "rgb_command_topic": "test_light_rgb/rgb/set", "rgbw_state_topic": "test_light_rgb/rgbw/status", "rgbw_command_topic": "test_light_rgb/rgbw/set", "rgbww_state_topic": "test_light_rgb/rgbww/status", "rgbww_command_topic": "test_light_rgb/rgbww/set", "color_temp_state_topic": "test_light_rgb/color_temp/status", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_state_topic": "test_light_rgb/effect/status", "effect_command_topic": "test_light_rgb/effect/set", "hs_state_topic": "test_light_rgb/hs/status", "hs_command_topic": "test_light_rgb/hs/set", "xy_state_topic": "test_light_rgb/xy/status", "xy_command_topic": "test_light_rgb/xy/set", "qos": "0", "payload_on": 1, "payload_off": 0, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("rgb_color") is None assert state.attributes.get("rgbw_color") is None assert state.attributes.get("rgbww_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("xy_color") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_light_rgb/status", "1") async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "rgb") async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", "255,255,255") async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", "255") async_fire_mqtt_message(hass, "test_light_rgb/effect/status", "none") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (255, 255, 255) assert state.attributes.get("brightness") == 255 assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") == "none" assert state.attributes.get("hs_color") == (0, 0) assert state.attributes.get("xy_color") == (0.323, 0.329) assert state.attributes.get("color_mode") == "rgb" async_fire_mqtt_message(hass, "test_light_rgb/status", "") assert "Ignoring empty state message" in caplog.text light_state = hass.states.get("light.test") assert state.state == STATE_ON async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", "") assert "Ignoring empty brightness message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes["brightness"] == 255 async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "") assert "Ignoring empty color mode message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes["effect"] == "none" async_fire_mqtt_message(hass, "test_light_rgb/effect/status", "") assert "Ignoring empty effect message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes["effect"] == "none" async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", "") assert "Ignoring empty rgb message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("rgb_color") == (255, 255, 255) async_fire_mqtt_message(hass, "test_light_rgb/hs/status", "") assert "Ignoring empty hs message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (0, 0) async_fire_mqtt_message(hass, "test_light_rgb/hs/status", "bad,bad") assert "Failed to parse hs state update" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (0, 0) async_fire_mqtt_message(hass, "test_light_rgb/xy/status", "") assert "Ignoring empty xy-color message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("xy_color") == (0.323, 0.329) async_fire_mqtt_message(hass, "test_light_rgb/rgbw/status", "255,255,255,1") async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "rgbw") async_fire_mqtt_message(hass, "test_light_rgb/rgbw/status", "") assert "Ignoring empty rgbw message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("rgbw_color") == (255, 255, 255, 1) async_fire_mqtt_message(hass, "test_light_rgb/rgbww/status", "255,255,255,1,2") async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "rgbww") async_fire_mqtt_message(hass, "test_light_rgb/rgbww/status", "") assert "Ignoring empty rgbww message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes.get("rgbww_color") == (255, 255, 255, 1, 2) async_fire_mqtt_message(hass, "test_light_rgb/color_temp/status", "153") async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "color_temp") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (255, 254, 250) assert state.attributes.get("brightness") == 255 assert state.attributes.get("color_temp") == 153 assert state.attributes.get("effect") == "none" assert state.attributes.get("hs_color") == (54.768, 1.6) assert state.attributes.get("xy_color") == (0.326, 0.333) async_fire_mqtt_message(hass, "test_light_rgb/color_temp/status", "") assert "Ignoring empty color temp message" in caplog.text light_state = hass.states.get("light.test") assert light_state.attributes["color_temp"] == 153 async def test_brightness_controlling_scale(hass, mqtt_mock_entry_with_yaml_config): """Test the brightness controlling scale.""" with assert_setup_component(1, light.DOMAIN): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_scale/status", "command_topic": "test_scale/set", "brightness_state_topic": "test_scale/brightness/status", "brightness_command_topic": "test_scale/brightness/set", "brightness_scale": "99", "qos": 0, "payload_on": "on", "payload_off": "off", } }, ) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("brightness") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_scale/status", "on") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") is None async_fire_mqtt_message(hass, "test_scale/status", "off") state = hass.states.get("light.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "test_scale/status", "on") async_fire_mqtt_message(hass, "test_scale/brightness/status", "99") light_state = hass.states.get("light.test") assert light_state.attributes["brightness"] == 255 async def test_brightness_from_rgb_controlling_scale( hass, mqtt_mock_entry_with_yaml_config ): """Test the brightness controlling scale.""" with assert_setup_component(1, light.DOMAIN): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_scale_rgb/status", "command_topic": "test_scale_rgb/set", "rgb_state_topic": "test_scale_rgb/rgb/status", "rgb_command_topic": "test_scale_rgb/rgb/set", "qos": 0, "payload_on": "on", "payload_off": "off", } }, ) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("brightness") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_scale_rgb/status", "on") async_fire_mqtt_message(hass, "test_scale_rgb/rgb/status", "255,0,0") state = hass.states.get("light.test") assert state.attributes.get("brightness") == 255 async_fire_mqtt_message(hass, "test_scale_rgb/rgb/status", "127,0,0") state = hass.states.get("light.test") assert state.attributes.get("brightness") == 127 async def test_legacy_white_value_controlling_scale( hass, mqtt_mock_entry_with_yaml_config ): """Test the white_value controlling scale.""" with assert_setup_component(1, light.DOMAIN): assert await async_setup_component( hass, light.DOMAIN, { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_scale/status", "command_topic": "test_scale/set", "white_value_state_topic": "test_scale/white_value/status", "white_value_command_topic": "test_scale/white_value/set", "white_value_scale": "99", "qos": 0, "payload_on": "on", "payload_off": "off", } }, ) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("white_value") is None assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_scale/status", "on") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("white_value") is None async_fire_mqtt_message(hass, "test_scale/status", "off") state = hass.states.get("light.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "test_scale/status", "on") async_fire_mqtt_message(hass, "test_scale/white_value/status", "99") light_state = hass.states.get("light.test") assert light_state.attributes["white_value"] == 255 async def test_legacy_controlling_state_via_topic_with_templates( hass, mqtt_mock_entry_with_yaml_config ): """Test the setting of the state with a template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/brightness/set", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_command_topic": "test_light_rgb/xy/set", "brightness_state_topic": "test_light_rgb/brightness/status", "color_temp_state_topic": "test_light_rgb/color_temp/status", "effect_state_topic": "test_light_rgb/effect/status", "hs_state_topic": "test_light_rgb/hs/status", "rgb_state_topic": "test_light_rgb/rgb/status", "white_value_state_topic": "test_light_rgb/white_value/status", "xy_state_topic": "test_light_rgb/xy/status", "state_value_template": "{{ value_json.hello }}", "brightness_value_template": "{{ value_json.hello }}", "color_temp_value_template": "{{ value_json.hello }}", "effect_value_template": "{{ value_json.hello }}", "hs_value_template": '{{ value_json.hello | join(",") }}', "rgb_value_template": '{{ value_json.hello | join(",") }}', "white_value_template": "{{ value_json.hello }}", "xy_value_template": '{{ value_json.hello | join(",") }}', } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("brightness") is None assert state.attributes.get("rgb_color") is None async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", '{"hello": [1, 2, 3]}') async_fire_mqtt_message(hass, "test_light_rgb/status", '{"hello": "ON"}') async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", '{"hello": "50"}') async_fire_mqtt_message( hass, "test_light_rgb/color_temp/status", '{"hello": "300"}' ) async_fire_mqtt_message( hass, "test_light_rgb/effect/status", '{"hello": "rainbow"}' ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 50 assert state.attributes.get("rgb_color") == (84, 169, 255) assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") == "rainbow" assert state.attributes.get("white_value") is None async_fire_mqtt_message( hass, "test_light_rgb/white_value/status", '{"hello": "75"}' ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 50 assert state.attributes.get("rgb_color") == (255, 187, 131) assert state.attributes.get("color_temp") == 300 assert state.attributes.get("effect") == "rainbow" assert state.attributes.get("white_value") == 75 async_fire_mqtt_message(hass, "test_light_rgb/hs/status", '{"hello": [100,50]}') async_fire_mqtt_message(hass, "test_light_rgb/white_value/status", '{"hello": "0"}') state = hass.states.get("light.test") assert state.attributes.get("hs_color") == (100, 50) async_fire_mqtt_message( hass, "test_light_rgb/xy/status", '{"hello": [0.123,0.123]}' ) state = hass.states.get("light.test") assert state.attributes.get("xy_color") == (0.14, 0.131) async_fire_mqtt_message(hass, "test_light_rgb/status", '{"hello": null}') state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN async def test_controlling_state_via_topic_with_templates( hass, mqtt_mock_entry_with_yaml_config ): """Test the setting of the state with a template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/brightness/set", "rgb_command_topic": "test_light_rgb/rgb/set", "rgbw_command_topic": "test_light_rgb/rgbw/set", "rgbww_command_topic": "test_light_rgb/rgbw/set", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "xy_command_topic": "test_light_rgb/xy/set", "brightness_state_topic": "test_light_rgb/brightness/status", "color_temp_state_topic": "test_light_rgb/color_temp/status", "effect_state_topic": "test_light_rgb/effect/status", "hs_state_topic": "test_light_rgb/hs/status", "rgb_state_topic": "test_light_rgb/rgb/status", "rgbw_state_topic": "test_light_rgb/rgbw/status", "rgbww_state_topic": "test_light_rgb/rgbww/status", "xy_state_topic": "test_light_rgb/xy/status", "state_value_template": "{{ value_json.hello }}", "brightness_value_template": "{{ value_json.hello }}", "color_temp_value_template": "{{ value_json.hello }}", "effect_value_template": "{{ value_json.hello }}", "hs_value_template": '{{ value_json.hello | join(",") }}', "rgb_value_template": '{{ value_json.hello | join(",") }}', "rgbw_value_template": '{{ value_json.hello | join(",") }}', "rgbww_value_template": '{{ value_json.hello | join(",") }}', "xy_value_template": '{{ value_json.hello | join(",") }}', } } color_modes = ["color_temp", "hs", "rgb", "rgbw", "rgbww", "xy"] assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("brightness") is None assert state.attributes.get("rgb_color") is None async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", '{"hello": [1, 2, 3]}') async_fire_mqtt_message(hass, "test_light_rgb/status", '{"hello": "ON"}') async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", '{"hello": "50"}') async_fire_mqtt_message( hass, "test_light_rgb/effect/status", '{"hello": "rainbow"}' ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 50 assert state.attributes.get("rgb_color") == (1, 2, 3) assert state.attributes.get("effect") == "rainbow" assert state.attributes.get(light.ATTR_COLOR_MODE) == "rgb" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message( hass, "test_light_rgb/rgbw/status", '{"hello": [1, 2, 3, 4]}' ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgbw_color") == (1, 2, 3, 4) assert state.attributes.get(light.ATTR_COLOR_MODE) == "rgbw" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message( hass, "test_light_rgb/rgbww/status", '{"hello": [1, 2, 3, 4, 5]}' ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgbww_color") == (1, 2, 3, 4, 5) assert state.attributes.get(light.ATTR_COLOR_MODE) == "rgbww" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message( hass, "test_light_rgb/color_temp/status", '{"hello": "300"}' ) state = hass.states.get("light.test") assert state.attributes.get("color_temp") == 300 assert state.attributes.get(light.ATTR_COLOR_MODE) == "color_temp" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/hs/status", '{"hello": [100,50]}') state = hass.states.get("light.test") assert state.attributes.get("hs_color") == (100, 50) assert state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message( hass, "test_light_rgb/xy/status", '{"hello": [0.123,0.123]}' ) state = hass.states.get("light.test") assert state.attributes.get("xy_color") == (0.123, 0.123) assert state.attributes.get(light.ATTR_COLOR_MODE) == "xy" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async def test_legacy_sending_mqtt_commands_and_optimistic( hass, mqtt_mock_entry_with_yaml_config ): """Test the sending of command in optimistic mode.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/brightness/set", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_command_topic": "test_light_rgb/xy/set", "effect_list": ["colorloop", "random"], "qos": 2, "payload_on": "on", "payload_off": "off", } } color_modes = ["color_temp", "hs", "rgbw"] fake_state = ha.State( "light.test", "on", { "brightness": 95, "hs_color": [100, 100], "effect": "random", "color_temp": 100, # TODO: Test restoring state with white_value "white_value": 0, }, ) with patch( "homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state", return_value=fake_state, ), assert_setup_component(1, light.DOMAIN): assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 95 assert state.attributes.get("hs_color") == (100, 100) assert state.attributes.get("effect") == "random" assert state.attributes.get("color_temp") is None assert state.attributes.get("white_value") is None assert state.attributes.get(ATTR_ASSUMED_STATE) assert state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_on(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", "on", 2, False ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", "off", 2, False ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_OFF mqtt_mock.reset_mock() await common.async_turn_on( hass, "light.test", brightness=50, xy_color=[0.123, 0.123] ) state = hass.states.get("light.test") assert state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_on(hass, "light.test", brightness=50, hs_color=[359, 78]) state = hass.states.get("light.test") assert state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_on(hass, "light.test", rgb_color=[255, 128, 0]) state = hass.states.get("light.test") assert state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 2, False), call("test_light_rgb/rgb/set", "255,128,0", 2, False), call("test_light_rgb/brightness/set", "50", 2, False), call("test_light_rgb/hs/set", "359.0,78.0", 2, False), call("test_light_rgb/xy/set", "0.14,0.131", 2, False), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes["rgb_color"] == (255, 128, 0) assert state.attributes["brightness"] == 50 assert state.attributes["hs_color"] == (30.118, 100) assert state.attributes.get("white_value") is None assert state.attributes["xy_color"] == (0.611, 0.375) assert state.attributes.get("color_temp") is None await common.async_turn_on(hass, "light.test", white_value=80, color_temp=125) state = hass.states.get("light.test") assert state.attributes.get(light.ATTR_COLOR_MODE) == "color_temp" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/white_value/set", "80", 2, False), call("test_light_rgb/color_temp/set", "125", 2, False), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") == (221, 229, 255) assert state.attributes["brightness"] == 50 assert state.attributes.get("hs_color") == (224.772, 13.249) assert state.attributes["white_value"] == 80 assert state.attributes.get("xy_color") == (0.296, 0.301) assert state.attributes["color_temp"] == 125 async def test_sending_mqtt_commands_and_optimistic( hass, mqtt_mock_entry_with_yaml_config ): """Test the sending of command in optimistic mode.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/brightness/set", "rgb_command_topic": "test_light_rgb/rgb/set", "rgbw_command_topic": "test_light_rgb/rgbw/set", "rgbww_command_topic": "test_light_rgb/rgbww/set", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "xy_command_topic": "test_light_rgb/xy/set", "effect_list": ["colorloop", "random"], "qos": 2, "payload_on": "on", "payload_off": "off", } } color_modes = ["color_temp", "hs", "rgb", "rgbw", "rgbww", "xy"] fake_state = ha.State( "light.test", "on", { "brightness": 95, "hs_color": [100, 100], "effect": "random", "color_temp": 100, "color_mode": "hs", }, ) with patch( "homeassistant.helpers.restore_state.RestoreEntity.async_get_last_state", return_value=fake_state, ), assert_setup_component(1, light.DOMAIN): assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 95 assert state.attributes.get("hs_color") == (100, 100) assert state.attributes.get("effect") == "random" assert state.attributes.get("color_temp") is None assert state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes assert state.attributes.get(ATTR_ASSUMED_STATE) await common.async_turn_on(hass, "light.test", effect="colorloop") mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 2, False), call("test_light_rgb/effect/set", "colorloop", 2, False), ], any_order=True, ) assert mqtt_mock.async_publish.call_count == 2 mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("effect") == "colorloop" assert state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with( "test_light_rgb/set", "off", 2, False ) mqtt_mock.async_publish.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_OFF assert state.attributes.get(light.ATTR_COLOR_MODE) is None assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_on( hass, "light.test", brightness=10, rgb_color=[80, 40, 20] ) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 2, False), call("test_light_rgb/brightness/set", "10", 2, False), call("test_light_rgb/rgb/set", "80,40,20", 2, False), ], any_order=True, ) assert mqtt_mock.async_publish.call_count == 3 mqtt_mock.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 10 assert state.attributes.get("rgb_color") == (80, 40, 20) assert state.attributes.get(light.ATTR_COLOR_MODE) == "rgb" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_on( hass, "light.test", brightness=20, rgbw_color=[80, 40, 20, 10] ) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 2, False), call("test_light_rgb/brightness/set", "20", 2, False), call("test_light_rgb/rgbw/set", "80,40,20,10", 2, False), ], any_order=True, ) assert mqtt_mock.async_publish.call_count == 3 mqtt_mock.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 20 assert state.attributes.get("rgbw_color") == (80, 40, 20, 10) assert state.attributes.get(light.ATTR_COLOR_MODE) == "rgbw" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_on( hass, "light.test", brightness=40, rgbww_color=[80, 40, 20, 10, 8] ) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 2, False), call("test_light_rgb/brightness/set", "40", 2, False), call("test_light_rgb/rgbww/set", "80,40,20,10,8", 2, False), ], any_order=True, ) assert mqtt_mock.async_publish.call_count == 3 mqtt_mock.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 40 assert state.attributes.get("rgbww_color") == (80, 40, 20, 10, 8) assert state.attributes.get(light.ATTR_COLOR_MODE) == "rgbww" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_on(hass, "light.test", brightness=50, hs_color=[359, 78]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 2, False), call("test_light_rgb/brightness/set", "50", 2, False), call("test_light_rgb/hs/set", "359.0,78.0", 2, False), ], any_order=True, ) assert mqtt_mock.async_publish.call_count == 3 mqtt_mock.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 50 assert state.attributes.get("hs_color") == (359.0, 78.0) assert state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_on(hass, "light.test", brightness=60, xy_color=[0.2, 0.3]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 2, False), call("test_light_rgb/brightness/set", "60", 2, False), call("test_light_rgb/xy/set", "0.2,0.3", 2, False), ], any_order=True, ) assert mqtt_mock.async_publish.call_count == 3 mqtt_mock.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 60 assert state.attributes.get("xy_color") == (0.2, 0.3) assert state.attributes.get(light.ATTR_COLOR_MODE) == "xy" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes await common.async_turn_on(hass, "light.test", color_temp=125) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/color_temp/set", "125", 2, False), ], any_order=True, ) assert mqtt_mock.async_publish.call_count == 2 mqtt_mock.reset_mock() state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 60 assert state.attributes.get("color_temp") == 125 assert state.attributes.get(light.ATTR_COLOR_MODE) == "color_temp" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async def test_sending_mqtt_rgb_command_with_template( hass, mqtt_mock_entry_with_yaml_config ): """Test the sending of RGB command with template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_rgb/set", "rgb_command_topic": "test_light_rgb/rgb/set", "rgb_command_template": '{{ "#%02x%02x%02x" | ' "format(red, green, blue)}}", "payload_on": "on", "payload_off": "off", "qos": 0, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", rgb_color=[255, 128, 64]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 0, False), call("test_light_rgb/rgb/set", "#ff8040", 0, False), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes["rgb_color"] == (255, 128, 64) async def test_sending_mqtt_rgbw_command_with_template( hass, mqtt_mock_entry_with_yaml_config ): """Test the sending of RGBW command with template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_rgb/set", "rgbw_command_topic": "test_light_rgb/rgbw/set", "rgbw_command_template": '{{ "#%02x%02x%02x%02x" | ' "format(red, green, blue, white)}}", "payload_on": "on", "payload_off": "off", "qos": 0, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", rgbw_color=[255, 128, 64, 32]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 0, False), call("test_light_rgb/rgbw/set", "#ff804020", 0, False), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes["rgbw_color"] == (255, 128, 64, 32) async def test_sending_mqtt_rgbww_command_with_template( hass, mqtt_mock_entry_with_yaml_config ): """Test the sending of RGBWW command with template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_rgb/set", "rgbww_command_topic": "test_light_rgb/rgbww/set", "rgbww_command_template": '{{ "#%02x%02x%02x%02x%02x" | ' "format(red, green, blue, cold_white, warm_white)}}", "payload_on": "on", "payload_off": "off", "qos": 0, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", rgbww_color=[255, 128, 64, 32, 16]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_rgb/set", "on", 0, False), call("test_light_rgb/rgbww/set", "#ff80402010", 0, False), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes["rgbww_color"] == (255, 128, 64, 32, 16) async def test_sending_mqtt_color_temp_command_with_template( hass, mqtt_mock_entry_with_yaml_config ): """Test the sending of Color Temp command with template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_color_temp/set", "color_temp_command_topic": "test_light_color_temp/color_temp/set", "color_temp_command_template": "{{ (1000 / value) | round(0) }}", "payload_on": "on", "payload_off": "off", "qos": 0, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", color_temp=100) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_color_temp/set", "on", 0, False), call("test_light_color_temp/color_temp/set", "10", 0, False), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes["color_temp"] == 100 async def test_on_command_first(hass, mqtt_mock_entry_with_yaml_config): """Test on command being sent before brightness.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "brightness_command_topic": "test_light/bright", "on_command_type": "first", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", brightness=50) # Should get the following MQTT messages. # test_light/set: 'ON' # test_light/bright: 50 mqtt_mock.async_publish.assert_has_calls( [ call("test_light/set", "ON", 0, False), call("test_light/bright", "50", 0, False), ], ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) async def test_on_command_last(hass, mqtt_mock_entry_with_yaml_config): """Test on command being sent after brightness.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "brightness_command_topic": "test_light/bright", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", brightness=50) # Should get the following MQTT messages. # test_light/bright: 50 # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/bright", "50", 0, False), call("test_light/set", "ON", 0, False), ], ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) async def test_on_command_brightness(hass, mqtt_mock_entry_with_yaml_config): """Test on command being sent as only brightness.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "brightness_command_topic": "test_light/bright", "rgb_command_topic": "test_light/rgb", "on_command_type": "brightness", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN # Turn on w/ no brightness - should set to max await common.async_turn_on(hass, "light.test") # Should get the following MQTT messages. # test_light/bright: 255 mqtt_mock.async_publish.assert_called_once_with( "test_light/bright", "255", 0, False ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) mqtt_mock.async_publish.reset_mock() # Turn on w/ brightness await common.async_turn_on(hass, "light.test", brightness=50) mqtt_mock.async_publish.assert_called_once_with("test_light/bright", "50", 0, False) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") # Turn on w/ just a color to ensure brightness gets # added and sent. await common.async_turn_on(hass, "light.test", rgb_color=[255, 128, 0]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "255,128,0", 0, False), call("test_light/bright", "50", 0, False), ], any_order=True, ) async def test_on_command_brightness_scaled(hass, mqtt_mock_entry_with_yaml_config): """Test brightness scale.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "brightness_command_topic": "test_light/bright", "brightness_scale": 100, "rgb_command_topic": "test_light/rgb", "on_command_type": "brightness", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN # Turn on w/ no brightness - should set to max await common.async_turn_on(hass, "light.test") # Should get the following MQTT messages. # test_light/bright: 100 mqtt_mock.async_publish.assert_called_once_with( "test_light/bright", "100", 0, False ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) mqtt_mock.async_publish.reset_mock() # Turn on w/ brightness await common.async_turn_on(hass, "light.test", brightness=50) mqtt_mock.async_publish.assert_called_once_with("test_light/bright", "20", 0, False) mqtt_mock.async_publish.reset_mock() # Turn on w/ max brightness await common.async_turn_on(hass, "light.test", brightness=255) mqtt_mock.async_publish.assert_called_once_with( "test_light/bright", "100", 0, False ) mqtt_mock.async_publish.reset_mock() # Turn on w/ min brightness await common.async_turn_on(hass, "light.test", brightness=1) mqtt_mock.async_publish.assert_called_once_with("test_light/bright", "1", 0, False) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") # Turn on w/ just a color to ensure brightness gets # added and sent. await common.async_turn_on(hass, "light.test", rgb_color=[255, 128, 0]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "255,128,0", 0, False), call("test_light/bright", "1", 0, False), ], any_order=True, ) async def test_legacy_on_command_rgb(hass, mqtt_mock_entry_with_yaml_config): """Test on command in RGB brightness mode.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "rgb_command_topic": "test_light/rgb", "white_value_command_topic": "test_light/white_value", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", brightness=127) # Should get the following MQTT messages. # test_light/rgb: '127,127,127' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "127,127,127", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=255) # Should get the following MQTT messages. # test_light/rgb: '255,255,255' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "255,255,255", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=1) # Should get the following MQTT messages. # test_light/rgb: '1,1,1' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "1,1,1", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) # Ensure color gets scaled with brightness. await common.async_turn_on(hass, "light.test", rgb_color=[255, 128, 0]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "1,0,0", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=255) # Should get the following MQTT messages. # test_light/rgb: '255,128,0' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "255,128,0", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() async def test_on_command_rgb(hass, mqtt_mock_entry_with_yaml_config): """Test on command in RGB brightness mode.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "rgb_command_topic": "test_light/rgb", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", brightness=127) # Should get the following MQTT messages. # test_light/rgb: '127,127,127' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "127,127,127", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=255) # Should get the following MQTT messages. # test_light/rgb: '255,255,255' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "255,255,255", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=1) # Should get the following MQTT messages. # test_light/rgb: '1,1,1' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "1,1,1", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) # Ensure color gets scaled with brightness. await common.async_turn_on(hass, "light.test", rgb_color=[255, 128, 0]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "1,0,0", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=255) # Should get the following MQTT messages. # test_light/rgb: '255,128,0' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "255,128,0", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() async def test_on_command_rgbw(hass, mqtt_mock_entry_with_yaml_config): """Test on command in RGBW brightness mode.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "rgbw_command_topic": "test_light/rgbw", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", brightness=127) # Should get the following MQTT messages. # test_light/rgbw: '127,127,127,127' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbw", "127,127,127,127", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=255) # Should get the following MQTT messages. # test_light/rgbw: '255,255,255,255' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbw", "255,255,255,255", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=1) # Should get the following MQTT messages. # test_light/rgbw: '1,1,1,1' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbw", "1,1,1,1", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) # Ensure color gets scaled with brightness. await common.async_turn_on(hass, "light.test", rgbw_color=[255, 128, 0, 16]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbw", "1,0,0,0", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=255) # Should get the following MQTT messages. # test_light/rgbw: '255,128,0' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbw", "255,128,0,16", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() async def test_on_command_rgbww(hass, mqtt_mock_entry_with_yaml_config): """Test on command in RGBWW brightness mode.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "rgbww_command_topic": "test_light/rgbww", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", brightness=127) # Should get the following MQTT messages. # test_light/rgbww: '127,127,127,127,127' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbww", "127,127,127,127,127", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=255) # Should get the following MQTT messages. # test_light/rgbww: '255,255,255,255,255' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbww", "255,255,255,255,255", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=1) # Should get the following MQTT messages. # test_light/rgbww: '1,1,1,1,1' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbww", "1,1,1,1,1", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) # Ensure color gets scaled with brightness. await common.async_turn_on(hass, "light.test", rgbww_color=[255, 128, 0, 16, 32]) mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbww", "1,0,0,0,0", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", brightness=255) # Should get the following MQTT messages. # test_light/rgbww: '255,128,0,16,32' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbww", "255,128,0,16,32", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() async def test_on_command_rgb_template(hass, mqtt_mock_entry_with_yaml_config): """Test on command in RGB brightness mode with RGB template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "rgb_command_topic": "test_light/rgb", "rgb_command_template": "{{ red }}/{{ green }}/{{ blue }}", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", brightness=127) # Should get the following MQTT messages. # test_light/rgb: '127/127/127' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgb", "127/127/127", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) async def test_on_command_rgbw_template(hass, mqtt_mock_entry_with_yaml_config): """Test on command in RGBW brightness mode with RGBW template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "rgbw_command_topic": "test_light/rgbw", "rgbw_command_template": "{{ red }}/{{ green }}/{{ blue }}/{{ white }}", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", brightness=127) # Should get the following MQTT messages. # test_light/rgb: '127/127/127/127' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbw", "127/127/127/127", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) async def test_on_command_rgbww_template(hass, mqtt_mock_entry_with_yaml_config): """Test on command in RGBWW brightness mode with RGBWW template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "rgbww_command_topic": "test_light/rgbww", "rgbww_command_template": "{{ red }}/{{ green }}/{{ blue }}/{{ cold_white }}/{{ warm_white }}", } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", brightness=127) # Should get the following MQTT messages. # test_light/rgb: '127/127/127/127/127' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/rgbww", "127/127/127/127/127", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) async def test_on_command_white(hass, mqtt_mock_entry_with_yaml_config): """Test sending commands for RGB + white light.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "tasmota_B94927/cmnd/POWER", "state_value_template": "{{ value_json.POWER }}", "payload_off": "OFF", "payload_on": "ON", "brightness_command_topic": "tasmota_B94927/cmnd/Dimmer", "brightness_scale": 100, "on_command_type": "brightness", "brightness_value_template": "{{ value_json.Dimmer }}", "rgb_command_topic": "tasmota_B94927/cmnd/Color2", "rgb_value_template": "{{value_json.Color.split(',')[0:3]|join(',')}}", "white_command_topic": "tasmota_B94927/cmnd/White", "white_scale": 100, "color_mode_value_template": "{% if value_json.White %} white {% else %} rgb {% endif %}", "qos": "0", } } color_modes = ["rgb", "white"] assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("brightness") is None assert state.attributes.get("rgb_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) is None assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes assert state.attributes.get(ATTR_ASSUMED_STATE) await common.async_turn_on(hass, "light.test", brightness=192) mqtt_mock.async_publish.assert_has_calls( [ call("tasmota_B94927/cmnd/Dimmer", "75", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", white=255) mqtt_mock.async_publish.assert_has_calls( [ call("tasmota_B94927/cmnd/White", "100", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test", white=64) mqtt_mock.async_publish.assert_has_calls( [ call("tasmota_B94927/cmnd/White", "25", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_on(hass, "light.test") mqtt_mock.async_publish.assert_has_calls( [ call("tasmota_B94927/cmnd/Dimmer", "25", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with( "tasmota_B94927/cmnd/POWER", "OFF", 0, False ) async def test_explicit_color_mode(hass, mqtt_mock_entry_with_yaml_config): """Test explicit color mode over mqtt.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", "color_mode_state_topic": "test_light_rgb/color_mode/status", "brightness_state_topic": "test_light_rgb/brightness/status", "brightness_command_topic": "test_light_rgb/brightness/set", "rgb_state_topic": "test_light_rgb/rgb/status", "rgb_command_topic": "test_light_rgb/rgb/set", "rgbw_state_topic": "test_light_rgb/rgbw/status", "rgbw_command_topic": "test_light_rgb/rgbw/set", "rgbww_state_topic": "test_light_rgb/rgbww/status", "rgbww_command_topic": "test_light_rgb/rgbww/set", "color_temp_state_topic": "test_light_rgb/color_temp/status", "color_temp_command_topic": "test_light_rgb/color_temp/set", "effect_state_topic": "test_light_rgb/effect/status", "effect_command_topic": "test_light_rgb/effect/set", "hs_state_topic": "test_light_rgb/hs/status", "hs_command_topic": "test_light_rgb/hs/set", "xy_state_topic": "test_light_rgb/xy/status", "xy_command_topic": "test_light_rgb/xy/set", "qos": "0", "payload_on": 1, "payload_off": 0, } } color_modes = ["color_temp", "hs", "rgb", "rgbw", "rgbww", "xy"] assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("rgb_color") is None assert state.attributes.get("rgbw_color") is None assert state.attributes.get("rgbww_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) is None assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_light_rgb/status", "1") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("effect") is None assert state.attributes.get("hs_color") is None assert state.attributes.get("rgb_color") is None assert state.attributes.get("rgbw_color") is None assert state.attributes.get("rgbww_color") is None assert state.attributes.get("white_value") is None assert state.attributes.get("xy_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/status", "0") state = hass.states.get("light.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "test_light_rgb/status", "1") async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", "100") light_state = hass.states.get("light.test") assert light_state.attributes.get("brightness") is None assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/color_temp/status", "300") light_state = hass.states.get("light.test") assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/effect/status", "rainbow") light_state = hass.states.get("light.test") assert light_state.attributes["effect"] == "rainbow" assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/rgb/status", "125,125,125") light_state = hass.states.get("light.test") assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/rgbw/status", "80,40,20,10") light_state = hass.states.get("light.test") assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/rgbww/status", "80,40,20,10,8") light_state = hass.states.get("light.test") assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/hs/status", "200,50") light_state = hass.states.get("light.test") assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/xy/status", "0.675,0.322") light_state = hass.states.get("light.test") assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "color_temp") light_state = hass.states.get("light.test") assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "color_temp" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "rgb") light_state = hass.states.get("light.test") assert light_state.attributes.get("rgb_color") == (125, 125, 125) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "rgb" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "rgbw") light_state = hass.states.get("light.test") assert light_state.attributes.get("rgbw_color") == (80, 40, 20, 10) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "rgbw" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "rgbww") light_state = hass.states.get("light.test") assert light_state.attributes.get("rgbww_color") == (80, 40, 20, 10, 8) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "rgbww" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "hs") light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (200, 50) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/color_mode/status", "xy") light_state = hass.states.get("light.test") assert light_state.attributes.get("xy_color") == (0.675, 0.322) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "xy" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async def test_explicit_color_mode_templated(hass, mqtt_mock_entry_with_yaml_config): """Test templated explicit color mode over mqtt.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "test_light_rgb/status", "command_topic": "test_light_rgb/set", "color_mode_state_topic": "test_light_rgb/color_mode/status", "color_mode_value_template": "{{ value_json.color_mode }}", "brightness_state_topic": "test_light_rgb/brightness/status", "brightness_command_topic": "test_light_rgb/brightness/set", "color_temp_state_topic": "test_light_rgb/color_temp/status", "color_temp_command_topic": "test_light_rgb/color_temp/set", "hs_state_topic": "test_light_rgb/hs/status", "hs_command_topic": "test_light_rgb/hs/set", "qos": "0", "payload_on": 1, "payload_off": 0, } } color_modes = ["color_temp", "hs"] assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("hs_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) is None assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "test_light_rgb/status", "1") state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp") is None assert state.attributes.get("hs_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/status", "0") state = hass.states.get("light.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "test_light_rgb/status", "1") async_fire_mqtt_message(hass, "test_light_rgb/brightness/status", "100") light_state = hass.states.get("light.test") assert light_state.attributes.get("brightness") is None assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/color_temp/status", "300") light_state = hass.states.get("light.test") assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message(hass, "test_light_rgb/hs/status", "200,50") light_state = hass.states.get("light.test") assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "unknown" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message( hass, "test_light_rgb/color_mode/status", '{"color_mode":"color_temp"}' ) light_state = hass.states.get("light.test") assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "color_temp" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message( hass, "test_light_rgb/color_mode/status", '{"color_mode":"hs"}' ) light_state = hass.states.get("light.test") assert light_state.attributes.get("hs_color") == (200, 50) assert light_state.attributes.get(light.ATTR_COLOR_MODE) == "hs" assert light_state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async def test_white_state_update(hass, mqtt_mock_entry_with_yaml_config): """Test state updates for RGB + white light.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "state_topic": "tasmota_B94927/tele/STATE", "command_topic": "tasmota_B94927/cmnd/POWER", "state_value_template": "{{ value_json.POWER }}", "payload_off": "OFF", "payload_on": "ON", "brightness_command_topic": "tasmota_B94927/cmnd/Dimmer", "brightness_state_topic": "tasmota_B94927/tele/STATE", "brightness_scale": 100, "on_command_type": "brightness", "brightness_value_template": "{{ value_json.Dimmer }}", "rgb_command_topic": "tasmota_B94927/cmnd/Color2", "rgb_state_topic": "tasmota_B94927/tele/STATE", "rgb_value_template": "{{value_json.Color.split(',')[0:3]|join(',')}}", "white_command_topic": "tasmota_B94927/cmnd/White", "white_scale": 100, "color_mode_state_topic": "tasmota_B94927/tele/STATE", "color_mode_value_template": "{% if value_json.White %} white {% else %} rgb {% endif %}", "qos": "0", } } color_modes = ["rgb", "white"] assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN assert state.attributes.get("brightness") is None assert state.attributes.get("rgb_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) is None assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message( hass, "tasmota_B94927/tele/STATE", '{"POWER":"ON","Dimmer":50,"Color":"0,0,0,128","White":50}', ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 128 assert state.attributes.get("rgb_color") is None assert state.attributes.get(light.ATTR_COLOR_MODE) == "white" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async_fire_mqtt_message( hass, "tasmota_B94927/tele/STATE", '{"POWER":"ON","Dimmer":50,"Color":"128,64,32,0","White":0}', ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("brightness") == 128 assert state.attributes.get("rgb_color") == (128, 64, 32) assert state.attributes.get(light.ATTR_COLOR_MODE) == "rgb" assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes async def test_effect(hass, mqtt_mock_entry_with_yaml_config): """Test effect.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light/set", "effect_command_topic": "test_light/effect/set", "effect_list": ["rainbow", "colorloop"], } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", effect="rainbow") # Should get the following MQTT messages. # test_light/effect/set: 'rainbow' # test_light/set: 'ON' mqtt_mock.async_publish.assert_has_calls( [ call("test_light/effect/set", "rainbow", 0, False), call("test_light/set", "ON", 0, False), ], any_order=True, ) mqtt_mock.async_publish.reset_mock() await common.async_turn_off(hass, "light.test") mqtt_mock.async_publish.assert_called_once_with("test_light/set", "OFF", 0, False) async def test_availability_when_connection_lost( hass, mqtt_mock_entry_with_yaml_config ): """Test availability after MQTT disconnection.""" await help_test_availability_when_connection_lost( hass, mqtt_mock_entry_with_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_availability_without_topic(hass, mqtt_mock_entry_with_yaml_config): """Test availability without defined availability topic.""" await help_test_availability_without_topic( hass, mqtt_mock_entry_with_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_default_availability_payload(hass, mqtt_mock_entry_with_yaml_config): """Test availability by default payload with defined topic.""" await help_test_default_availability_payload( hass, mqtt_mock_entry_with_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_custom_availability_payload(hass, mqtt_mock_entry_with_yaml_config): """Test availability by custom payload with defined topic.""" await help_test_custom_availability_payload( hass, mqtt_mock_entry_with_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_setting_attribute_via_mqtt_json_message( hass, mqtt_mock_entry_with_yaml_config ): """Test the setting of attribute via MQTT with JSON payload.""" await help_test_setting_attribute_via_mqtt_json_message( hass, mqtt_mock_entry_with_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_setting_blocked_attribute_via_mqtt_json_message( hass, mqtt_mock_entry_no_yaml_config ): """Test the setting of attribute via MQTT with JSON payload.""" await help_test_setting_blocked_attribute_via_mqtt_json_message( hass, mqtt_mock_entry_no_yaml_config, light.DOMAIN, DEFAULT_CONFIG, MQTT_LIGHT_ATTRIBUTES_BLOCKED, ) async def test_setting_attribute_with_template(hass, mqtt_mock_entry_with_yaml_config): """Test the setting of attribute via MQTT with JSON payload.""" await help_test_setting_attribute_with_template( hass, mqtt_mock_entry_with_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_update_with_json_attrs_not_dict( hass, mqtt_mock_entry_with_yaml_config, caplog ): """Test attributes get extracted from a JSON result.""" await help_test_update_with_json_attrs_not_dict( hass, mqtt_mock_entry_with_yaml_config, caplog, light.DOMAIN, DEFAULT_CONFIG ) async def test_update_with_json_attrs_bad_JSON( hass, mqtt_mock_entry_with_yaml_config, caplog ): """Test attributes get extracted from a JSON result.""" await help_test_update_with_json_attrs_bad_JSON( hass, mqtt_mock_entry_with_yaml_config, caplog, light.DOMAIN, DEFAULT_CONFIG ) async def test_discovery_update_attr(hass, mqtt_mock_entry_no_yaml_config, caplog): """Test update of discovered MQTTAttributes.""" await help_test_discovery_update_attr( hass, mqtt_mock_entry_no_yaml_config, caplog, light.DOMAIN, DEFAULT_CONFIG ) async def test_unique_id(hass, mqtt_mock_entry_with_yaml_config): """Test unique id option only creates one light per unique_id.""" config = { light.DOMAIN: [ { "platform": "mqtt", "name": "Test 1", "state_topic": "test-topic", "command_topic": "test_topic", "unique_id": "TOTALLY_UNIQUE", }, { "platform": "mqtt", "name": "<NAME>", "state_topic": "test-topic", "command_topic": "test_topic", "unique_id": "TOTALLY_UNIQUE", }, ] } await help_test_unique_id( hass, mqtt_mock_entry_with_yaml_config, light.DOMAIN, config ) async def test_discovery_removal_light(hass, mqtt_mock_entry_no_yaml_config, caplog): """Test removal of discovered light.""" data = ( '{ "name": "test",' ' "state_topic": "test_topic",' ' "command_topic": "test_topic" }' ) await help_test_discovery_removal( hass, mqtt_mock_entry_no_yaml_config, caplog, light.DOMAIN, data ) async def test_discovery_deprecated(hass, mqtt_mock_entry_no_yaml_config, caplog): """Test discovery of mqtt light with deprecated platform option.""" await mqtt_mock_entry_no_yaml_config() data = ( '{ "name": "Beer",' ' "platform": "mqtt",' ' "command_topic": "test_topic"}' ) async_fire_mqtt_message(hass, "homeassistant/light/bla/config", data) await hass.async_block_till_done() state = hass.states.get("light.beer") assert state is not None assert state.name == "Beer" async def test_discovery_update_light_topic_and_template( hass, mqtt_mock_entry_no_yaml_config, caplog ): """Test update of discovered light.""" config1 = { "name": "Beer", "state_topic": "test_light_rgb/state1", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/state1", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_command_topic": "test_light_rgb/state1", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_command_topic": "test_light_rgb/xy/set", "brightness_state_topic": "test_light_rgb/state1", "color_temp_state_topic": "test_light_rgb/state1", "effect_state_topic": "test_light_rgb/state1", "hs_state_topic": "test_light_rgb/state1", "rgb_state_topic": "test_light_rgb/state1", "white_value_state_topic": "test_light_rgb/state1", "xy_state_topic": "test_light_rgb/state1", "state_value_template": "{{ value_json.state1.state }}", "brightness_value_template": "{{ value_json.state1.brightness }}", "color_temp_value_template": "{{ value_json.state1.ct }}", "effect_value_template": "{{ value_json.state1.fx }}", "hs_value_template": "{{ value_json.state1.hs }}", "rgb_value_template": "{{ value_json.state1.rgb }}", "white_value_template": "{{ value_json.state1.white }}", "xy_value_template": "{{ value_json.state1.xy }}", } config2 = { "name": "Milk", "state_topic": "test_light_rgb/state2", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/state2", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_command_topic": "test_light_rgb/state2", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_command_topic": "test_light_rgb/xy/set", "brightness_state_topic": "test_light_rgb/state2", "color_temp_state_topic": "test_light_rgb/state2", "effect_state_topic": "test_light_rgb/state2", "hs_state_topic": "test_light_rgb/state2", "rgb_state_topic": "test_light_rgb/state2", "white_value_state_topic": "test_light_rgb/state2", "xy_state_topic": "test_light_rgb/state2", "state_value_template": "{{ value_json.state2.state }}", "brightness_value_template": "{{ value_json.state2.brightness }}", "color_temp_value_template": "{{ value_json.state2.ct }}", "effect_value_template": "{{ value_json.state2.fx }}", "hs_value_template": "{{ value_json.state2.hs }}", "rgb_value_template": "{{ value_json.state2.rgb }}", "white_value_template": "{{ value_json.state2.white }}", "xy_value_template": "{{ value_json.state2.xy }}", } state_data1 = [ ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "brightness":100, "ct":123, "white":100, "fx":"cycle"}}', ) ], "on", [ ("brightness", 100), ("color_temp", 123), ("white_value", 100), ("effect", "cycle"), ], ), ( [("test_light_rgb/state1", '{"state1":{"state":"OFF"}}')], "off", None, ), ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "hs":"1,2", "white":0}}', ) ], "on", [("hs_color", (1, 2)), ("white_value", None)], ), ( [ ( "test_light_rgb/state1", '{"state1":{"rgb":"255,127,63"}}', ) ], "on", [("rgb_color", (255, 127, 63))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"xy":"0.3, 0.4"}}', ) ], "on", [("xy_color", (0.3, 0.401))], ), ] state_data2 = [ ( [ ( "test_light_rgb/state2", '{"state2":{"state":"ON", "brightness":50, "ct":200, "white":50, "fx":"loop"}}', ) ], "on", [ ("brightness", 50), ("color_temp", 200), ("white_value", 50), ("effect", "loop"), ], ), ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "brightness":100, "ct":123, "fx":"cycle"}}', ), ( "test_light_rgb/state1", '{"state2":{"state":"ON", "brightness":100, "ct":123, "fx":"cycle"}}', ), ( "test_light_rgb/state2", '{"state1":{"state":"ON", "brightness":100, "ct":123, "fx":"cycle"}}', ), ], "on", [("brightness", 50), ("color_temp", 200), ("effect", "loop")], ), ( [("test_light_rgb/state1", '{"state1":{"state":"OFF"}}')], "on", None, ), ( [("test_light_rgb/state1", '{"state2":{"state":"OFF"}}')], "on", None, ), ( [("test_light_rgb/state2", '{"state1":{"state":"OFF"}}')], "on", None, ), ( [("test_light_rgb/state2", '{"state2":{"state":"OFF"}}')], "off", None, ), ( [ ( "test_light_rgb/state2", '{"state2":{"state":"ON", "hs":"1.2,2.2", "white":0}}', ) ], "on", [("hs_color", (1.2, 2.2)), ("white_value", None)], ), ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "hs":"1,2"}}', ), ( "test_light_rgb/state1", '{"state2":{"state":"ON", "hs":"1,2"}}', ), ( "test_light_rgb/state2", '{"state1":{"state":"ON", "hs":"1,2"}}', ), ], "on", [("hs_color", (1.2, 2.2))], ), ( [ ( "test_light_rgb/state2", '{"state2":{"rgb":"63,127,255"}}', ) ], "on", [("rgb_color", (63, 127, 255))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"rgb":"255,127,63"}}', ), ( "test_light_rgb/state1", '{"state2":{"rgb":"255,127,63"}}', ), ( "test_light_rgb/state2", '{"state1":{"rgb":"255,127,63"}}', ), ], "on", [("rgb_color", (63, 127, 255))], ), ( [ ( "test_light_rgb/state2", '{"state2":{"xy":"0.4, 0.3"}}', ) ], "on", [("xy_color", (0.4, 0.3))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"white":50, "xy":"0.3, 0.4"}}', ), ( "test_light_rgb/state1", '{"state2":{"white":50, "xy":"0.3, 0.4"}}', ), ( "test_light_rgb/state2", '{"state1":{"white":50, "xy":"0.3, 0.4"}}', ), ], "on", [("xy_color", (0.4, 0.3))], ), ] await help_test_discovery_update( hass, mqtt_mock_entry_no_yaml_config, caplog, light.DOMAIN, config1, config2, state_data1=state_data1, state_data2=state_data2, ) async def test_discovery_update_light_template( hass, mqtt_mock_entry_no_yaml_config, caplog ): """Test update of discovered light.""" config1 = { "name": "Beer", "state_topic": "test_light_rgb/state1", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/state1", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_command_topic": "test_light_rgb/state1", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_command_topic": "test_light_rgb/xy/set", "brightness_state_topic": "test_light_rgb/state1", "color_temp_state_topic": "test_light_rgb/state1", "effect_state_topic": "test_light_rgb/state1", "hs_state_topic": "test_light_rgb/state1", "rgb_state_topic": "test_light_rgb/state1", "white_value_state_topic": "test_light_rgb/state1", "xy_state_topic": "test_light_rgb/state1", "state_value_template": "{{ value_json.state1.state }}", "brightness_value_template": "{{ value_json.state1.brightness }}", "color_temp_value_template": "{{ value_json.state1.ct }}", "effect_value_template": "{{ value_json.state1.fx }}", "hs_value_template": "{{ value_json.state1.hs }}", "rgb_value_template": "{{ value_json.state1.rgb }}", "white_value_template": "{{ value_json.state1.white }}", "xy_value_template": "{{ value_json.state1.xy }}", } config2 = { "name": "Milk", "state_topic": "test_light_rgb/state1", "command_topic": "test_light_rgb/set", "brightness_command_topic": "test_light_rgb/state1", "rgb_command_topic": "test_light_rgb/rgb/set", "color_temp_command_topic": "test_light_rgb/state1", "effect_command_topic": "test_light_rgb/effect/set", "hs_command_topic": "test_light_rgb/hs/set", "white_value_command_topic": "test_light_rgb/white_value/set", "xy_command_topic": "test_light_rgb/xy/set", "brightness_state_topic": "test_light_rgb/state1", "color_temp_state_topic": "test_light_rgb/state1", "effect_state_topic": "test_light_rgb/state1", "hs_state_topic": "test_light_rgb/state1", "rgb_state_topic": "test_light_rgb/state1", "white_value_state_topic": "test_light_rgb/state1", "xy_state_topic": "test_light_rgb/state1", "state_value_template": "{{ value_json.state2.state }}", "brightness_value_template": "{{ value_json.state2.brightness }}", "color_temp_value_template": "{{ value_json.state2.ct }}", "effect_value_template": "{{ value_json.state2.fx }}", "hs_value_template": "{{ value_json.state2.hs }}", "rgb_value_template": "{{ value_json.state2.rgb }}", "white_value_template": "{{ value_json.state2.white }}", "xy_value_template": "{{ value_json.state2.xy }}", } state_data1 = [ ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "brightness":100, "ct":123, "white":100, "fx":"cycle"}}', ) ], "on", [ ("brightness", 100), ("color_temp", 123), ("white_value", 100), ("effect", "cycle"), ], ), ( [("test_light_rgb/state1", '{"state1":{"state":"OFF"}}')], "off", None, ), ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "hs":"1,2", "white":0}}', ) ], "on", [("hs_color", (1, 2))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"rgb":"255,127,63"}}', ) ], "on", [("rgb_color", (255, 127, 63))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"white":0, "xy":"0.3, 0.4"}}', ) ], "on", [("white_value", None), ("xy_color", (0.3, 0.401))], ), ] state_data2 = [ ( [ ( "test_light_rgb/state1", '{"state2":{"state":"ON", "brightness":50, "ct":200, "white":50, "fx":"loop"}}', ) ], "on", [ ("brightness", 50), ("color_temp", 200), ("white_value", 50), ("effect", "loop"), ], ), ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "brightness":100, "ct":123, "fx":"cycle"}}', ), ], "on", [("brightness", 50), ("color_temp", 200), ("effect", "loop")], ), ( [("test_light_rgb/state1", '{"state1":{"state":"OFF"}}')], "on", None, ), ( [("test_light_rgb/state1", '{"state2":{"state":"OFF"}}')], "off", None, ), ( [ ( "test_light_rgb/state1", '{"state2":{"state":"ON", "hs":"1.2,2.2", "white":0}}', ) ], "on", [("hs_color", (1.2, 2.2))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"state":"ON", "hs":"1,2"}}', ) ], "on", [("hs_color", (1.2, 2.2))], ), ( [ ( "test_light_rgb/state1", '{"state2":{"rgb":"63,127,255"}}', ) ], "on", [("rgb_color", (63, 127, 255))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"rgb":"255,127,63"}}', ) ], "on", [("rgb_color", (63, 127, 255))], ), ( [ ( "test_light_rgb/state1", '{"state2":{"xy":"0.4, 0.3"}}', ) ], "on", [("white_value", None), ("xy_color", (0.4, 0.3))], ), ( [ ( "test_light_rgb/state1", '{"state1":{"white":50, "xy":"0.3, 0.4"}}', ) ], "on", [("white_value", None), ("xy_color", (0.4, 0.3))], ), ] await help_test_discovery_update( hass, mqtt_mock_entry_no_yaml_config, caplog, light.DOMAIN, config1, config2, state_data1=state_data1, state_data2=state_data2, ) async def test_discovery_update_unchanged_light( hass, mqtt_mock_entry_no_yaml_config, caplog ): """Test update of discovered light.""" data1 = ( '{ "name": "Beer",' ' "state_topic": "test_topic",' ' "command_topic": "test_topic" }' ) with patch( "homeassistant.components.mqtt.light.schema_basic.MqttLight.discovery_update" ) as discovery_update: await help_test_discovery_update_unchanged( hass, mqtt_mock_entry_no_yaml_config, caplog, light.DOMAIN, data1, discovery_update, ) @pytest.mark.no_fail_on_log_exception async def test_discovery_broken(hass, mqtt_mock_entry_no_yaml_config, caplog): """Test handling of bad discovery message.""" data1 = '{ "name": "Beer" }' data2 = ( '{ "name": "Milk",' ' "state_topic": "test_topic",' ' "command_topic": "test_topic" }' ) await help_test_discovery_broken( hass, mqtt_mock_entry_no_yaml_config, caplog, light.DOMAIN, data1, data2 ) async def test_entity_device_info_with_connection(hass, mqtt_mock_entry_no_yaml_config): """Test MQTT light device registry integration.""" await help_test_entity_device_info_with_connection( hass, mqtt_mock_entry_no_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_device_info_with_identifier(hass, mqtt_mock_entry_no_yaml_config): """Test MQTT light device registry integration.""" await help_test_entity_device_info_with_identifier( hass, mqtt_mock_entry_no_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_device_info_update(hass, mqtt_mock_entry_no_yaml_config): """Test device registry update.""" await help_test_entity_device_info_update( hass, mqtt_mock_entry_no_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_device_info_remove(hass, mqtt_mock_entry_no_yaml_config): """Test device registry remove.""" await help_test_entity_device_info_remove( hass, mqtt_mock_entry_no_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_id_update_subscriptions(hass, mqtt_mock_entry_with_yaml_config): """Test MQTT subscriptions are managed when entity_id is updated.""" await help_test_entity_id_update_subscriptions( hass, mqtt_mock_entry_with_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_id_update_discovery_update(hass, mqtt_mock_entry_no_yaml_config): """Test MQTT discovery update when entity_id is updated.""" await help_test_entity_id_update_discovery_update( hass, mqtt_mock_entry_no_yaml_config, light.DOMAIN, DEFAULT_CONFIG ) async def test_entity_debug_info_message(hass, mqtt_mock_entry_no_yaml_config): """Test MQTT debug info.""" await help_test_entity_debug_info_message( hass, mqtt_mock_entry_no_yaml_config, light.DOMAIN, DEFAULT_CONFIG, light.SERVICE_TURN_ON, ) async def test_max_mireds(hass, mqtt_mock_entry_with_yaml_config): """Test setting min_mireds and max_mireds.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_max_mireds/set", "color_temp_command_topic": "test_max_mireds/color_temp/set", "max_mireds": 370, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.attributes.get("min_mireds") == 153 assert state.attributes.get("max_mireds") == 370 @pytest.mark.parametrize( "service,topic,parameters,payload,template,tpl_par,tpl_output", [ ( light.SERVICE_TURN_ON, "command_topic", None, "ON", None, None, None, ), ( light.SERVICE_TURN_ON, "white_command_topic", {"white": "255"}, 255, None, None, None, ), ( light.SERVICE_TURN_ON, "brightness_command_topic", {"color_temp": "200", "brightness": "50"}, 50, "brightness_command_template", "value", b"5", ), ( light.SERVICE_TURN_ON, "effect_command_topic", {"rgb_color": [255, 128, 0], "effect": "color_loop"}, "color_loop", "effect_command_template", "value", b"c", ), ( light.SERVICE_TURN_ON, "color_temp_command_topic", {"color_temp": "200"}, 200, "color_temp_command_template", "value", b"2", ), ( light.SERVICE_TURN_ON, "rgb_command_topic", {"rgb_color": [255, 128, 0]}, "255,128,0", "rgb_command_template", "red", b"2", ), ( light.SERVICE_TURN_ON, "hs_command_topic", {"rgb_color": [255, 128, 0]}, "30.118,100.0", None, None, None, ), ( light.SERVICE_TURN_ON, "xy_command_topic", {"hs_color": [30.118, 100.0]}, "0.611,0.375", None, None, None, ), ( light.SERVICE_TURN_OFF, "command_topic", None, "OFF", None, None, None, ), ], ) async def test_publishing_with_custom_encoding( hass, mqtt_mock_entry_with_yaml_config, caplog, service, topic, parameters, payload, template, tpl_par, tpl_output, ): """Test publishing MQTT payload with different encoding.""" domain = light.DOMAIN config = copy.deepcopy(DEFAULT_CONFIG[domain]) if topic == "effect_command_topic": config["effect_list"] = ["random", "color_loop"] elif topic == "white_command_topic": config["rgb_command_topic"] = "some-cmd-topic" await help_test_publishing_with_custom_encoding( hass, mqtt_mock_entry_with_yaml_config, caplog, domain, config, service, topic, parameters, payload, template, tpl_par=tpl_par, tpl_output=tpl_output, ) async def test_reloadable(hass, mqtt_mock_entry_with_yaml_config, caplog, tmp_path): """Test reloading the MQTT platform.""" domain = light.DOMAIN config = DEFAULT_CONFIG[domain] await help_test_reloadable( hass, mqtt_mock_entry_with_yaml_config, caplog, tmp_path, domain, config ) async def test_reloadable_late(hass, mqtt_client_mock, caplog, tmp_path): """Test reloading the MQTT platform with late entry setup.""" domain = light.DOMAIN config = DEFAULT_CONFIG[domain] await help_test_reloadable_late(hass, caplog, tmp_path, domain, config) @pytest.mark.parametrize( "topic,value,attribute,attribute_value,init_payload", [ ("state_topic", "ON", None, "on", None), ("brightness_state_topic", "60", "brightness", 60, ("state_topic", "ON")), ( "color_mode_state_topic", "200", "color_mode", "200", ("state_topic", "ON"), ), ("color_temp_state_topic", "200", "color_temp", 200, ("state_topic", "ON")), ("effect_state_topic", "random", "effect", "random", ("state_topic", "ON")), ("hs_state_topic", "200,50", "hs_color", (200, 50), ("state_topic", "ON")), ( "xy_state_topic", "128,128", "xy_color", (128, 128), ("state_topic", "ON"), ), ( "rgb_state_topic", "255,0,240", "rgb_color", (255, 0, 240), ("state_topic", "ON"), ), ], ) async def test_encoding_subscribable_topics( hass, mqtt_mock_entry_with_yaml_config, caplog, topic, value, attribute, attribute_value, init_payload, ): """Test handling of incoming encoded payload.""" config = copy.deepcopy(DEFAULT_CONFIG[light.DOMAIN]) config[CONF_EFFECT_COMMAND_TOPIC] = "light/CONF_EFFECT_COMMAND_TOPIC" config[CONF_RGB_COMMAND_TOPIC] = "light/CONF_RGB_COMMAND_TOPIC" config[CONF_BRIGHTNESS_COMMAND_TOPIC] = "light/CONF_BRIGHTNESS_COMMAND_TOPIC" config[CONF_COLOR_TEMP_COMMAND_TOPIC] = "light/CONF_COLOR_TEMP_COMMAND_TOPIC" config[CONF_HS_COMMAND_TOPIC] = "light/CONF_HS_COMMAND_TOPIC" config[CONF_RGB_COMMAND_TOPIC] = "light/CONF_RGB_COMMAND_TOPIC" config[CONF_RGBW_COMMAND_TOPIC] = "light/CONF_RGBW_COMMAND_TOPIC" config[CONF_RGBWW_COMMAND_TOPIC] = "light/CONF_RGBWW_COMMAND_TOPIC" config[CONF_XY_COMMAND_TOPIC] = "light/CONF_XY_COMMAND_TOPIC" config[CONF_EFFECT_LIST] = ["colorloop", "random"] if attribute and attribute == "brightness": config[CONF_WHITE_VALUE_COMMAND_TOPIC] = "light/CONF_WHITE_VALUE_COMMAND_TOPIC" await help_test_encoding_subscribable_topics( hass, mqtt_mock_entry_with_yaml_config, caplog, light.DOMAIN, config, topic, value, attribute, attribute_value, init_payload, ) async def test_sending_mqtt_brightness_command_with_template( hass, mqtt_mock_entry_with_yaml_config ): """Test the sending of Brightness command with template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_brightness/set", "brightness_command_topic": "test_light_brightness/brightness/set", "brightness_command_template": "{{ (1000 / value) | round(0) }}", "payload_on": "on", "payload_off": "off", "qos": 0, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", brightness=100) mqtt_mock.async_publish.assert_has_calls( [ call("test_light_brightness/set", "on", 0, False), call("test_light_brightness/brightness/set", "10", 0, False), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes["brightness"] == 100 async def test_sending_mqtt_effect_command_with_template( hass, mqtt_mock_entry_with_yaml_config ): """Test the sending of Effect command with template.""" config = { light.DOMAIN: { "platform": "mqtt", "name": "test", "command_topic": "test_light_brightness/set", "brightness_command_topic": "test_light_brightness/brightness/set", "effect_command_topic": "test_light_brightness/effect/set", "effect_command_template": '{ "effect": "{{ value }}" }', "effect_list": ["colorloop", "random"], "payload_on": "on", "payload_off": "off", "qos": 0, } } assert await async_setup_component(hass, light.DOMAIN, config) await hass.async_block_till_done() mqtt_mock = await mqtt_mock_entry_with_yaml_config() state = hass.states.get("light.test") assert state.state == STATE_UNKNOWN await common.async_turn_on(hass, "light.test", effect="colorloop") mqtt_mock.async_publish.assert_has_calls( [ call("test_light_brightness/set", "on", 0, False), call( "test_light_brightness/effect/set", '{ "effect": "colorloop" }', 0, False, ), ], any_order=True, ) state = hass.states.get("light.test") assert state.state == STATE_ON assert state.attributes.get("effect") == "colorloop" async def test_setup_manual_entity_from_yaml(hass): """Test setup manual configured MQTT entity.""" platform = light.DOMAIN config = copy.deepcopy(DEFAULT_CONFIG[platform]) config["name"] = "test" del config["platform"] await help_test_setup_manual_entity_from_yaml(hass, platform, config) assert hass.states.get(f"{platform}.test") is not None
en
0.76188
The tests for the MQTT light platform. Configuration for RGB Version with brightness: light: platform: mqtt name: "Office Light RGB" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" rgb_state_topic: "office/rgb1/rgb/status" rgb_command_topic: "office/rgb1/rgb/set" qos: 0 payload_on: "on" payload_off: "off" Configuration for XY Version with brightness: light: platform: mqtt name: "Office Light XY" state_topic: "office/xy1/light/status" command_topic: "office/xy1/light/switch" brightness_state_topic: "office/xy1/brightness/status" brightness_command_topic: "office/xy1/brightness/set" xy_state_topic: "office/xy1/xy/status" xy_command_topic: "office/xy1/xy/set" qos: 0 payload_on: "on" payload_off: "off" config without RGB: light: platform: mqtt name: "Office Light" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" qos: 0 payload_on: "on" payload_off: "off" config without RGB and brightness: light: platform: mqtt name: "Office Light" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" qos: 0 payload_on: "on" payload_off: "off" config for RGB Version with brightness and scale: light: platform: mqtt name: "Office Light RGB" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" brightness_scale: 99 rgb_state_topic: "office/rgb1/rgb/status" rgb_command_topic: "office/rgb1/rgb/set" rgb_scale: 99 qos: 0 payload_on: "on" payload_off: "off" config with brightness and color temp light: platform: mqtt name: "Office Light Color Temp" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" brightness_scale: 99 color_temp_state_topic: "office/rgb1/color_temp/status" color_temp_command_topic: "office/rgb1/color_temp/set" qos: 0 payload_on: "on" payload_off: "off" config with brightness and effect light: platform: mqtt name: "Office Light Color Temp" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" brightness_scale: 99 effect_state_topic: "office/rgb1/effect/status" effect_command_topic: "office/rgb1/effect/set" effect_list: - rainbow - colorloop qos: 0 payload_on: "on" payload_off: "off" config for RGB Version with white value and scale: light: platform: mqtt name: "Office Light RGB" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" white_value_state_topic: "office/rgb1/white_value/status" white_value_command_topic: "office/rgb1/white_value/set" white_value_scale: 99 rgb_state_topic: "office/rgb1/rgb/status" rgb_command_topic: "office/rgb1/rgb/set" rgb_scale: 99 qos: 0 payload_on: "on" payload_off: "off" config for RGB Version with RGB command template: light: platform: mqtt name: "Office Light RGB" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" rgb_state_topic: "office/rgb1/rgb/status" rgb_command_topic: "office/rgb1/rgb/set" rgb_command_template: "{{ '#%02x%02x%02x' | format(red, green, blue)}}" qos: 0 payload_on: "on" payload_off: "off" Configuration for HS Version with brightness: light: platform: mqtt name: "Office Light HS" state_topic: "office/hs1/light/status" command_topic: "office/hs1/light/switch" brightness_state_topic: "office/hs1/brightness/status" brightness_command_topic: "office/hs1/brightness/set" hs_state_topic: "office/hs1/hs/status" hs_command_topic: "office/hs1/hs/set" qos: 0 payload_on: "on" payload_off: "off" Configuration with brightness command template: light: platform: mqtt name: "Office Light" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" brightness_state_topic: "office/rgb1/brightness/status" brightness_command_topic: "office/rgb1/brightness/set" brightness_command_template: '{ "brightness": "{{ value }}" }' qos: 0 payload_on: "on" payload_off: "off" Configuration with effect command template: light: platform: mqtt name: "Office Light Color Temp" state_topic: "office/rgb1/light/status" command_topic: "office/rgb1/light/switch" effect_state_topic: "office/rgb1/effect/status" effect_command_topic: "office/rgb1/effect/set" effect_command_template: '{ "effect": "{{ value }}" }' effect_list: - rainbow - colorloop qos: 0 payload_on: "on" payload_off: "off" Test if command fails with command topic. Test legacy RGB + white light flags brightness support. Test if there is no color and brightness if no topic. Test the controlling of the state via topic for legacy light (white_value). Test the controlling of the state via topic. Test handling of empty data via topic. Test handling of empty data via topic. Test the brightness controlling scale. Test the brightness controlling scale. Test the white_value controlling scale. Test the setting of the state with a template. Test the setting of the state with a template. Test the sending of command in optimistic mode. # TODO: Test restoring state with white_value Test the sending of command in optimistic mode. Test the sending of RGB command with template. Test the sending of RGBW command with template. Test the sending of RGBWW command with template. Test the sending of Color Temp command with template. Test on command being sent before brightness. # Should get the following MQTT messages. # test_light/set: 'ON' # test_light/bright: 50 Test on command being sent after brightness. # Should get the following MQTT messages. # test_light/bright: 50 # test_light/set: 'ON' Test on command being sent as only brightness. # Turn on w/ no brightness - should set to max # Should get the following MQTT messages. # test_light/bright: 255 # Turn on w/ brightness # Turn on w/ just a color to ensure brightness gets # added and sent. Test brightness scale. # Turn on w/ no brightness - should set to max # Should get the following MQTT messages. # test_light/bright: 100 # Turn on w/ brightness # Turn on w/ max brightness # Turn on w/ min brightness # Turn on w/ just a color to ensure brightness gets # added and sent. Test on command in RGB brightness mode. # Should get the following MQTT messages. # test_light/rgb: '127,127,127' # test_light/set: 'ON' # Should get the following MQTT messages. # test_light/rgb: '255,255,255' # test_light/set: 'ON' # Should get the following MQTT messages. # test_light/rgb: '1,1,1' # test_light/set: 'ON' # Ensure color gets scaled with brightness. # Should get the following MQTT messages. # test_light/rgb: '255,128,0' # test_light/set: 'ON' Test on command in RGB brightness mode. # Should get the following MQTT messages. # test_light/rgb: '127,127,127' # test_light/set: 'ON' # Should get the following MQTT messages. # test_light/rgb: '255,255,255' # test_light/set: 'ON' # Should get the following MQTT messages. # test_light/rgb: '1,1,1' # test_light/set: 'ON' # Ensure color gets scaled with brightness. # Should get the following MQTT messages. # test_light/rgb: '255,128,0' # test_light/set: 'ON' Test on command in RGBW brightness mode. # Should get the following MQTT messages. # test_light/rgbw: '127,127,127,127' # test_light/set: 'ON' # Should get the following MQTT messages. # test_light/rgbw: '255,255,255,255' # test_light/set: 'ON' # Should get the following MQTT messages. # test_light/rgbw: '1,1,1,1' # test_light/set: 'ON' # Ensure color gets scaled with brightness. # Should get the following MQTT messages. # test_light/rgbw: '255,128,0' # test_light/set: 'ON' Test on command in RGBWW brightness mode. # Should get the following MQTT messages. # test_light/rgbww: '127,127,127,127,127' # test_light/set: 'ON' # Should get the following MQTT messages. # test_light/rgbww: '255,255,255,255,255' # test_light/set: 'ON' # Should get the following MQTT messages. # test_light/rgbww: '1,1,1,1,1' # test_light/set: 'ON' # Ensure color gets scaled with brightness. # Should get the following MQTT messages. # test_light/rgbww: '255,128,0,16,32' # test_light/set: 'ON' Test on command in RGB brightness mode with RGB template. # Should get the following MQTT messages. # test_light/rgb: '127/127/127' # test_light/set: 'ON' Test on command in RGBW brightness mode with RGBW template. # Should get the following MQTT messages. # test_light/rgb: '127/127/127/127' # test_light/set: 'ON' Test on command in RGBWW brightness mode with RGBWW template. # Should get the following MQTT messages. # test_light/rgb: '127/127/127/127/127' # test_light/set: 'ON' Test sending commands for RGB + white light. Test explicit color mode over mqtt. Test templated explicit color mode over mqtt. Test state updates for RGB + white light. Test effect. # Should get the following MQTT messages. # test_light/effect/set: 'rainbow' # test_light/set: 'ON' Test availability after MQTT disconnection. Test availability without defined availability topic. Test availability by default payload with defined topic. Test availability by custom payload with defined topic. Test the setting of attribute via MQTT with JSON payload. Test the setting of attribute via MQTT with JSON payload. Test the setting of attribute via MQTT with JSON payload. Test attributes get extracted from a JSON result. Test attributes get extracted from a JSON result. Test update of discovered MQTTAttributes. Test unique id option only creates one light per unique_id. Test removal of discovered light. Test discovery of mqtt light with deprecated platform option. Test update of discovered light. Test update of discovered light. Test update of discovered light. Test handling of bad discovery message. Test MQTT light device registry integration. Test MQTT light device registry integration. Test device registry update. Test device registry remove. Test MQTT subscriptions are managed when entity_id is updated. Test MQTT discovery update when entity_id is updated. Test MQTT debug info. Test setting min_mireds and max_mireds. Test publishing MQTT payload with different encoding. Test reloading the MQTT platform. Test reloading the MQTT platform with late entry setup. Test handling of incoming encoded payload. Test the sending of Brightness command with template. Test the sending of Effect command with template. Test setup manual configured MQTT entity.
1.755629
2
tools/telemetry/telemetry/core/platform/profiler/android_profiling_helper_unittest.py
tmpsantos/chromium
0
6625831
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import glob import os import pickle import re import shutil import tempfile import unittest from telemetry import benchmark from telemetry.core import util from telemetry.core.platform.profiler import android_profiling_helper from telemetry.unittest import simple_mock from telemetry.unittest import tab_test_case def _GetLibrariesMappedIntoProcesses(device, pids): libs = set() for pid in pids: maps_file = '/proc/%d/maps' % pid maps = device.ReadFile(maps_file, as_root=True) for map_line in maps: lib = re.match(r'.*\s(/.*[.]so)$', map_line) if lib: libs.add(lib.group(1)) return libs class TestAndroidProfilingHelper(unittest.TestCase): def testGetRequiredLibrariesForPerfProfile(self): perf_output = os.path.join( util.GetUnittestDataDir(), 'sample_perf_report_output.txt') with open(perf_output) as f: perf_output = f.read() mock_popen = simple_mock.MockObject() mock_popen.ExpectCall('communicate').WillReturn([None, perf_output]) mock_subprocess = simple_mock.MockObject() mock_subprocess.ExpectCall( 'Popen').WithArgs(simple_mock.DONT_CARE).WillReturn(mock_popen) mock_subprocess.SetAttribute('PIPE', simple_mock.MockObject()) real_subprocess = android_profiling_helper.subprocess android_profiling_helper.subprocess = mock_subprocess try: libs = android_profiling_helper.GetRequiredLibrariesForPerfProfile('foo') self.assertEqual(libs, set([ '/data/app-lib/com.google.android.apps.chrome-2/libchrome.2016.0.so', '/system/lib/libart.so', '/system/lib/libc.so', '/system/lib/libm.so'])) finally: android_profiling_helper.subprocess = real_subprocess @benchmark.Enabled('android') def testGetRequiredLibrariesForVTuneProfile(self): vtune_db_output = os.path.join( util.GetUnittestDataDir(), 'sample_vtune_db_output') with open(vtune_db_output, 'rb') as f: vtune_db_output = pickle.load(f) mock_cursor = simple_mock.MockObject() mock_cursor.ExpectCall( 'execute').WithArgs(simple_mock.DONT_CARE).WillReturn(vtune_db_output) mock_conn = simple_mock.MockObject() mock_conn.ExpectCall('cursor').WillReturn(mock_cursor) mock_conn.ExpectCall('close') mock_sqlite3 = simple_mock.MockObject() mock_sqlite3.ExpectCall( 'connect').WithArgs(simple_mock.DONT_CARE).WillReturn(mock_conn) real_sqlite3 = android_profiling_helper.sqlite3 android_profiling_helper.sqlite3 = mock_sqlite3 try: libs = android_profiling_helper.GetRequiredLibrariesForVTuneProfile('foo') self.assertEqual(libs, set([ '/data/app-lib/com.google.android.apps.chrome-1/libchrome.2019.0.so', '/system/lib/libdvm.so', '/system/lib/libc.so', '/system/lib/libm.so'])) finally: android_profiling_helper.sqlite3 = real_sqlite3 class TestAndroidProfilingHelperTabTestCase(tab_test_case.TabTestCase): def setUp(self): super(TestAndroidProfilingHelperTabTestCase, self).setUp() # pylint: disable=W0212 browser_backend = self._browser._browser_backend try: self._device = browser_backend.adb.device() except AttributeError: pass @benchmark.Enabled('android') def testCreateSymFs(self): # pylint: disable=W0212 browser_pid = self._browser._browser_backend.pid pids = ([browser_pid] + self._browser._platform_backend.GetChildPids(browser_pid)) libs = _GetLibrariesMappedIntoProcesses(self._device, pids) assert libs symfs_dir = tempfile.mkdtemp() try: kallsyms = android_profiling_helper.CreateSymFs(self._device, symfs_dir, libs) # Make sure we found at least one unstripped library. unstripped_libs = glob.glob(os.path.join(symfs_dir, 'data', 'app-lib', '*', '*.so')) assert unstripped_libs # Check that we have kernel symbols. assert os.path.exists(kallsyms) # Check that all requested libraries are present. for lib in libs: assert os.path.exists(os.path.join(symfs_dir, lib[1:])), \ '%s not found in symfs' % lib finally: shutil.rmtree(symfs_dir) @benchmark.Enabled('android') def testGetToolchainBinaryPath(self): with tempfile.NamedTemporaryFile() as libc: self._device.PullFile('/system/lib/libc.so', libc.name) path = android_profiling_helper.GetToolchainBinaryPath(libc.name, 'objdump') assert os.path.exists(path)
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import glob import os import pickle import re import shutil import tempfile import unittest from telemetry import benchmark from telemetry.core import util from telemetry.core.platform.profiler import android_profiling_helper from telemetry.unittest import simple_mock from telemetry.unittest import tab_test_case def _GetLibrariesMappedIntoProcesses(device, pids): libs = set() for pid in pids: maps_file = '/proc/%d/maps' % pid maps = device.ReadFile(maps_file, as_root=True) for map_line in maps: lib = re.match(r'.*\s(/.*[.]so)$', map_line) if lib: libs.add(lib.group(1)) return libs class TestAndroidProfilingHelper(unittest.TestCase): def testGetRequiredLibrariesForPerfProfile(self): perf_output = os.path.join( util.GetUnittestDataDir(), 'sample_perf_report_output.txt') with open(perf_output) as f: perf_output = f.read() mock_popen = simple_mock.MockObject() mock_popen.ExpectCall('communicate').WillReturn([None, perf_output]) mock_subprocess = simple_mock.MockObject() mock_subprocess.ExpectCall( 'Popen').WithArgs(simple_mock.DONT_CARE).WillReturn(mock_popen) mock_subprocess.SetAttribute('PIPE', simple_mock.MockObject()) real_subprocess = android_profiling_helper.subprocess android_profiling_helper.subprocess = mock_subprocess try: libs = android_profiling_helper.GetRequiredLibrariesForPerfProfile('foo') self.assertEqual(libs, set([ '/data/app-lib/com.google.android.apps.chrome-2/libchrome.2016.0.so', '/system/lib/libart.so', '/system/lib/libc.so', '/system/lib/libm.so'])) finally: android_profiling_helper.subprocess = real_subprocess @benchmark.Enabled('android') def testGetRequiredLibrariesForVTuneProfile(self): vtune_db_output = os.path.join( util.GetUnittestDataDir(), 'sample_vtune_db_output') with open(vtune_db_output, 'rb') as f: vtune_db_output = pickle.load(f) mock_cursor = simple_mock.MockObject() mock_cursor.ExpectCall( 'execute').WithArgs(simple_mock.DONT_CARE).WillReturn(vtune_db_output) mock_conn = simple_mock.MockObject() mock_conn.ExpectCall('cursor').WillReturn(mock_cursor) mock_conn.ExpectCall('close') mock_sqlite3 = simple_mock.MockObject() mock_sqlite3.ExpectCall( 'connect').WithArgs(simple_mock.DONT_CARE).WillReturn(mock_conn) real_sqlite3 = android_profiling_helper.sqlite3 android_profiling_helper.sqlite3 = mock_sqlite3 try: libs = android_profiling_helper.GetRequiredLibrariesForVTuneProfile('foo') self.assertEqual(libs, set([ '/data/app-lib/com.google.android.apps.chrome-1/libchrome.2019.0.so', '/system/lib/libdvm.so', '/system/lib/libc.so', '/system/lib/libm.so'])) finally: android_profiling_helper.sqlite3 = real_sqlite3 class TestAndroidProfilingHelperTabTestCase(tab_test_case.TabTestCase): def setUp(self): super(TestAndroidProfilingHelperTabTestCase, self).setUp() # pylint: disable=W0212 browser_backend = self._browser._browser_backend try: self._device = browser_backend.adb.device() except AttributeError: pass @benchmark.Enabled('android') def testCreateSymFs(self): # pylint: disable=W0212 browser_pid = self._browser._browser_backend.pid pids = ([browser_pid] + self._browser._platform_backend.GetChildPids(browser_pid)) libs = _GetLibrariesMappedIntoProcesses(self._device, pids) assert libs symfs_dir = tempfile.mkdtemp() try: kallsyms = android_profiling_helper.CreateSymFs(self._device, symfs_dir, libs) # Make sure we found at least one unstripped library. unstripped_libs = glob.glob(os.path.join(symfs_dir, 'data', 'app-lib', '*', '*.so')) assert unstripped_libs # Check that we have kernel symbols. assert os.path.exists(kallsyms) # Check that all requested libraries are present. for lib in libs: assert os.path.exists(os.path.join(symfs_dir, lib[1:])), \ '%s not found in symfs' % lib finally: shutil.rmtree(symfs_dir) @benchmark.Enabled('android') def testGetToolchainBinaryPath(self): with tempfile.NamedTemporaryFile() as libc: self._device.PullFile('/system/lib/libc.so', libc.name) path = android_profiling_helper.GetToolchainBinaryPath(libc.name, 'objdump') assert os.path.exists(path)
en
0.902095
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # pylint: disable=W0212 # pylint: disable=W0212 # Make sure we found at least one unstripped library. # Check that we have kernel symbols. # Check that all requested libraries are present.
1.95963
2
ansible/modules/utilities/helper/meta.py
EnjoyLifeFund/macHighSierra-py36-pkgs
1
6625832
<reponame>EnjoyLifeFund/macHighSierra-py36-pkgs #!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Ansible, a Red Hat company # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'core'} DOCUMENTATION = ''' module: meta short_description: Execute Ansible 'actions' version_added: "1.2" description: - Meta tasks are a special kind of task which can influence Ansible internal execution or state. Prior to Ansible 2.0, the only meta option available was `flush_handlers`. As of 2.2, there are five meta tasks which can be used. Meta tasks can be used anywhere within your playbook. - This module is also supported for Windows targets. options: free_form: description: - This module takes a free form command, as a string. There's not an actual option named "free form". See the examples! - > C(flush_handlers) makes Ansible run any handler tasks which have thus far been notified. Ansible inserts these tasks internally at certain points to implicitly trigger handler runs (after pre/post tasks, the final role execution, and the main tasks section of your plays). - > C(refresh_inventory) (added in 2.0) forces the reload of the inventory, which in the case of dynamic inventory scripts means they will be re-executed. This is mainly useful when additional hosts are created and users wish to use them instead of using the `add_host` module." - "C(noop) (added in 2.0) This literally does 'nothing'. It is mainly used internally and not recommended for general use." - "C(clear_facts) (added in 2.1) causes the gathered facts for the hosts specified in the play's list of hosts to be cleared, including the fact cache." - "C(clear_host_errors) (added in 2.1) clears the failed state (if any) from hosts specified in the play's list of hosts." - "C(end_play) (added in 2.2) causes the play to end without failing the host." - "C(reset_connection) (added in 2.3) interrupts a persistent connection (i.e. ssh + control persist)" choices: ['noop', 'flush_handlers', 'refresh_inventory', 'clear_facts', 'clear_host_errors', 'end_play', 'reset_connection'] required: true notes: - C(meta) is not really a module nor action_plugin as such it cannot be overwritten. - This module is also supported for Windows targets. author: - "Ansible Core Team" ''' EXAMPLES = ''' - template: src: new.j2 dest: /etc/config.txt notify: myhandler - name: force all notified handlers to run at this point, not waiting for normal sync points meta: flush_handlers - name: reload inventory, useful with dynamic inventories when play makes changes to the existing hosts cloud_guest: # this is fake module name: newhost state: present - name: Refresh inventory to ensure new instaces exist in inventory meta: refresh_inventory - name: Clear gathered facts from all currently targeted hosts meta: clear_facts - name: bring host back to play after failure copy: src: file dest: /etc/file remote_user: imightnothavepermission - meta: clear_host_errors - user: name={{ansible_user}} groups=input - name: reset ssh connection to allow user changes to affect 'current login user' meta: reset_connection '''
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Ansible, a Red Hat company # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'core'} DOCUMENTATION = ''' module: meta short_description: Execute Ansible 'actions' version_added: "1.2" description: - Meta tasks are a special kind of task which can influence Ansible internal execution or state. Prior to Ansible 2.0, the only meta option available was `flush_handlers`. As of 2.2, there are five meta tasks which can be used. Meta tasks can be used anywhere within your playbook. - This module is also supported for Windows targets. options: free_form: description: - This module takes a free form command, as a string. There's not an actual option named "free form". See the examples! - > C(flush_handlers) makes Ansible run any handler tasks which have thus far been notified. Ansible inserts these tasks internally at certain points to implicitly trigger handler runs (after pre/post tasks, the final role execution, and the main tasks section of your plays). - > C(refresh_inventory) (added in 2.0) forces the reload of the inventory, which in the case of dynamic inventory scripts means they will be re-executed. This is mainly useful when additional hosts are created and users wish to use them instead of using the `add_host` module." - "C(noop) (added in 2.0) This literally does 'nothing'. It is mainly used internally and not recommended for general use." - "C(clear_facts) (added in 2.1) causes the gathered facts for the hosts specified in the play's list of hosts to be cleared, including the fact cache." - "C(clear_host_errors) (added in 2.1) clears the failed state (if any) from hosts specified in the play's list of hosts." - "C(end_play) (added in 2.2) causes the play to end without failing the host." - "C(reset_connection) (added in 2.3) interrupts a persistent connection (i.e. ssh + control persist)" choices: ['noop', 'flush_handlers', 'refresh_inventory', 'clear_facts', 'clear_host_errors', 'end_play', 'reset_connection'] required: true notes: - C(meta) is not really a module nor action_plugin as such it cannot be overwritten. - This module is also supported for Windows targets. author: - "Ansible Core Team" ''' EXAMPLES = ''' - template: src: new.j2 dest: /etc/config.txt notify: myhandler - name: force all notified handlers to run at this point, not waiting for normal sync points meta: flush_handlers - name: reload inventory, useful with dynamic inventories when play makes changes to the existing hosts cloud_guest: # this is fake module name: newhost state: present - name: Refresh inventory to ensure new instaces exist in inventory meta: refresh_inventory - name: Clear gathered facts from all currently targeted hosts meta: clear_facts - name: bring host back to play after failure copy: src: file dest: /etc/file remote_user: imightnothavepermission - meta: clear_host_errors - user: name={{ansible_user}} groups=input - name: reset ssh connection to allow user changes to affect 'current login user' meta: reset_connection '''
en
0.828389
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Ansible, a Red Hat company # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) module: meta short_description: Execute Ansible 'actions' version_added: "1.2" description: - Meta tasks are a special kind of task which can influence Ansible internal execution or state. Prior to Ansible 2.0, the only meta option available was `flush_handlers`. As of 2.2, there are five meta tasks which can be used. Meta tasks can be used anywhere within your playbook. - This module is also supported for Windows targets. options: free_form: description: - This module takes a free form command, as a string. There's not an actual option named "free form". See the examples! - > C(flush_handlers) makes Ansible run any handler tasks which have thus far been notified. Ansible inserts these tasks internally at certain points to implicitly trigger handler runs (after pre/post tasks, the final role execution, and the main tasks section of your plays). - > C(refresh_inventory) (added in 2.0) forces the reload of the inventory, which in the case of dynamic inventory scripts means they will be re-executed. This is mainly useful when additional hosts are created and users wish to use them instead of using the `add_host` module." - "C(noop) (added in 2.0) This literally does 'nothing'. It is mainly used internally and not recommended for general use." - "C(clear_facts) (added in 2.1) causes the gathered facts for the hosts specified in the play's list of hosts to be cleared, including the fact cache." - "C(clear_host_errors) (added in 2.1) clears the failed state (if any) from hosts specified in the play's list of hosts." - "C(end_play) (added in 2.2) causes the play to end without failing the host." - "C(reset_connection) (added in 2.3) interrupts a persistent connection (i.e. ssh + control persist)" choices: ['noop', 'flush_handlers', 'refresh_inventory', 'clear_facts', 'clear_host_errors', 'end_play', 'reset_connection'] required: true notes: - C(meta) is not really a module nor action_plugin as such it cannot be overwritten. - This module is also supported for Windows targets. author: - "Ansible Core Team" - template: src: new.j2 dest: /etc/config.txt notify: myhandler - name: force all notified handlers to run at this point, not waiting for normal sync points meta: flush_handlers - name: reload inventory, useful with dynamic inventories when play makes changes to the existing hosts cloud_guest: # this is fake module name: newhost state: present - name: Refresh inventory to ensure new instaces exist in inventory meta: refresh_inventory - name: Clear gathered facts from all currently targeted hosts meta: clear_facts - name: bring host back to play after failure copy: src: file dest: /etc/file remote_user: imightnothavepermission - meta: clear_host_errors - user: name={{ansible_user}} groups=input - name: reset ssh connection to allow user changes to affect 'current login user' meta: reset_connection
1.769556
2
utils/helper.py
avalanchesiqi/twitter-sampling
1
6625833
<gh_stars>1-10 import time from datetime import datetime, timedelta class Timer: def __init__(self): self.start_time = None def start(self): self.start_time = time.time() def stop(self): print('>>> Elapsed time: {0}\n'.format(str(timedelta(seconds=time.time() - self.start_time))[:-3])) def strify(iterable_obj, delimiter=','): return delimiter.join(iterable_obj) date_format = {'tweet': '%a %b %d %H:%M:%S %z %Y', 'youtube': '%Y-%m-%d'} def str2obj(str, fmt='youtube'): if fmt == 'tweet' or fmt == 'youtube': return datetime.strptime(str, date_format[fmt]) else: return datetime.strptime(str, fmt) def obj2str(obj, fmt='youtube'): if fmt == 'tweet' or fmt == 'youtube': return obj.strftime(date_format[fmt]) else: return obj.strftime(fmt) # twitter's snowflake parameters twepoch = 1288834974657 datacenter_id_bits = 5 worker_id_bits = 5 sequence_id_bits = 12 max_datacenter_id = 1 << datacenter_id_bits max_worker_id = 1 << worker_id_bits max_sequence_id = 1 << sequence_id_bits max_timestamp = 1 << (64 - datacenter_id_bits - worker_id_bits - sequence_id_bits) def make_snowflake(timestamp_ms, datacenter_id, worker_id, sequence_id, twepoch=twepoch): """generate a twitter-snowflake id, based on https://github.com/twitter/snowflake/blob/master/src/main/scala/com/twitter/service/snowflake/IdWorker.scala :param: timestamp_ms time since UNIX epoch in milliseconds""" timestamp_ms = int(timestamp_ms) sid = ((timestamp_ms - twepoch) % max_timestamp) << datacenter_id_bits << worker_id_bits << sequence_id_bits sid += (datacenter_id % max_datacenter_id) << worker_id_bits << sequence_id_bits sid += (worker_id % max_worker_id) << sequence_id_bits sid += sequence_id % max_sequence_id return sid def melt_snowflake(snowflake_id, twepoch=twepoch): """inversely transform a snowflake id back to its components.""" snowflake_id = int(snowflake_id) sequence_id = snowflake_id & (max_sequence_id - 1) worker_id = (snowflake_id >> sequence_id_bits) & (max_worker_id - 1) datacenter_id = (snowflake_id >> sequence_id_bits >> worker_id_bits) & (max_datacenter_id - 1) timestamp_ms = snowflake_id >> sequence_id_bits >> worker_id_bits >> datacenter_id_bits timestamp_ms += twepoch return timestamp_ms, datacenter_id, worker_id, sequence_id def count_track(track_list, start_with_rate=False, subcrawler=False): if subcrawler: total_track_cnt = 0 for i in range(len(track_list)): total_track_cnt += count_track(track_list[i], start_with_rate=start_with_rate, subcrawler=False) return total_track_cnt else: if len(track_list) == 0: return 0 if start_with_rate: track_cnt = -track_list[0] else: track_cnt = 0 if len(track_list) == 1: return track_cnt + track_list[0] for i in range(len(track_list) - 1): if track_list[i + 1] <= track_list[i]: track_cnt += track_list[i] track_cnt += track_list[-1] return track_cnt
import time from datetime import datetime, timedelta class Timer: def __init__(self): self.start_time = None def start(self): self.start_time = time.time() def stop(self): print('>>> Elapsed time: {0}\n'.format(str(timedelta(seconds=time.time() - self.start_time))[:-3])) def strify(iterable_obj, delimiter=','): return delimiter.join(iterable_obj) date_format = {'tweet': '%a %b %d %H:%M:%S %z %Y', 'youtube': '%Y-%m-%d'} def str2obj(str, fmt='youtube'): if fmt == 'tweet' or fmt == 'youtube': return datetime.strptime(str, date_format[fmt]) else: return datetime.strptime(str, fmt) def obj2str(obj, fmt='youtube'): if fmt == 'tweet' or fmt == 'youtube': return obj.strftime(date_format[fmt]) else: return obj.strftime(fmt) # twitter's snowflake parameters twepoch = 1288834974657 datacenter_id_bits = 5 worker_id_bits = 5 sequence_id_bits = 12 max_datacenter_id = 1 << datacenter_id_bits max_worker_id = 1 << worker_id_bits max_sequence_id = 1 << sequence_id_bits max_timestamp = 1 << (64 - datacenter_id_bits - worker_id_bits - sequence_id_bits) def make_snowflake(timestamp_ms, datacenter_id, worker_id, sequence_id, twepoch=twepoch): """generate a twitter-snowflake id, based on https://github.com/twitter/snowflake/blob/master/src/main/scala/com/twitter/service/snowflake/IdWorker.scala :param: timestamp_ms time since UNIX epoch in milliseconds""" timestamp_ms = int(timestamp_ms) sid = ((timestamp_ms - twepoch) % max_timestamp) << datacenter_id_bits << worker_id_bits << sequence_id_bits sid += (datacenter_id % max_datacenter_id) << worker_id_bits << sequence_id_bits sid += (worker_id % max_worker_id) << sequence_id_bits sid += sequence_id % max_sequence_id return sid def melt_snowflake(snowflake_id, twepoch=twepoch): """inversely transform a snowflake id back to its components.""" snowflake_id = int(snowflake_id) sequence_id = snowflake_id & (max_sequence_id - 1) worker_id = (snowflake_id >> sequence_id_bits) & (max_worker_id - 1) datacenter_id = (snowflake_id >> sequence_id_bits >> worker_id_bits) & (max_datacenter_id - 1) timestamp_ms = snowflake_id >> sequence_id_bits >> worker_id_bits >> datacenter_id_bits timestamp_ms += twepoch return timestamp_ms, datacenter_id, worker_id, sequence_id def count_track(track_list, start_with_rate=False, subcrawler=False): if subcrawler: total_track_cnt = 0 for i in range(len(track_list)): total_track_cnt += count_track(track_list[i], start_with_rate=start_with_rate, subcrawler=False) return total_track_cnt else: if len(track_list) == 0: return 0 if start_with_rate: track_cnt = -track_list[0] else: track_cnt = 0 if len(track_list) == 1: return track_cnt + track_list[0] for i in range(len(track_list) - 1): if track_list[i + 1] <= track_list[i]: track_cnt += track_list[i] track_cnt += track_list[-1] return track_cnt
en
0.624142
# twitter's snowflake parameters generate a twitter-snowflake id, based on https://github.com/twitter/snowflake/blob/master/src/main/scala/com/twitter/service/snowflake/IdWorker.scala :param: timestamp_ms time since UNIX epoch in milliseconds inversely transform a snowflake id back to its components.
3.197995
3
app/gui.py
jakubsolecki/Team-Locator
0
6625834
from time import sleep from kivy.app import App from kivy.properties import ObjectProperty, StringProperty from kivy.uix.gridlayout import GridLayout from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.treeview import TreeViewLabel from kivy.uix.popup import Popup from kivy.uix.floatlayout import FloatLayout from kivy.uix.widget import Widget from kivy.utils import get_color_from_hex from kivy.metrics import * from client import Client # from app.client import Client from colordict import color_dictionary from gpsblinker import GpsBlinker from kivy.storage.jsonstore import JsonStore import atexit import os import glob from returnbinder import ReturnBinder class WindowManager(ScreenManager): pass class MapWindow(Screen): pass class TokenWindow(Screen): nick = ObjectProperty(None) code = ObjectProperty(None) ip_address = ObjectProperty(None) client = Client.get_instance() colornum = 10 # Expected to change. If players stay black something is wrong current_blinker = None stored_data = JsonStore('data.json') def __disconnect(self): files = glob.glob('cache/*.png') for f in files: if not f.endswith(".png"): # Additional safety, should never happen print("ERROR WHILE CLEARING CACHE, FOUND NON-PNG FILE, ABORTING") break os.remove(f) self.client.send_message(self.client.DISCONNECT_MESSAGE, self.code.text) sleep(1) def __connect(self): if 'host-' in self.nick.text or ':' in self.nick.text or\ len(self.nick.text) >= 16 or\ len(self.code.text) > 10 or\ len(self.ip_address.text) > 16: return self.client.connect(server_ip=self.ip_address.text) # after pressing "Host Game" button: def host_connect(self): self.__connect() if not self.client.is_connected(): return atexit.register(self.__disconnect) screen = App.get_running_app().root screen.current = "host" ReturnBinder.get_instance().current_screen = "host" self.stored_data.clear() self.stored_data.put('credentials', ip_address=self.ip_address.text, nick=self.nick.text) # after pressing "Connect Game" button: def player_connect(self): self.__connect() if not self.client.is_connected(): return atexit.register(self.__disconnect) message = self.code.text + ":" + self.nick.text print("Message being sent to server: " + message) self.client.send_message(self.client.INIT_MESSAGE, message) sleep(1) if self.client.get_token() is None: return # Takes first letter as number from 0 to 9: || #1ABCD means color 1 || if len(self.code.text) >= 1 and self.code.text[0].isdigit(): self.colornum = int(self.code.text[0]) # GPS always starts in AGH WIEiT faculty building self.current_blinker = blinker = GpsBlinker(lon=19.9125399, lat=50.0680966, nick=self.nick.text, color_number=self.colornum) team_map = App.get_running_app().root.ids.mw.ids.map team_map.add_widget(blinker) team_map.start_checking = True blinker.blink() App.get_running_app().gps_mod.start_updating(blinker) self.stored_data.clear() self.stored_data.put('credentials', ip_address=self.ip_address.text, nick=self.nick.text) screen = App.get_running_app().root screen.current = "viewer" ReturnBinder.get_instance().current_screen = "viewer" class HostWindow(Screen): # Window for setting game rules switch = ObjectProperty(None) # Set to None because it is created before actual switch from .kv file slider = ObjectProperty(None) tv = ObjectProperty(None) hostVisible = False teamNumber = 0 def create_nodes(self): if int(self.slider.value) == self.teamNumber: return self.teamNumber = int(self.slider.value) for node in [i for i in self.tv.iterate_all_nodes()]: self.tv.remove_node(node) for i in range(int(self.slider.value)): self.teamNumber = i + 1 name = 'Druzyna ' + str(i + 1) color = get_color_from_hex(color_dictionary[i]) self.tv.add_node(TreeViewLabel(text=name, color=color)) def host_to_server(self): self.hostVisible = self.switch.active nickname = App.get_running_app().root.ids.tw.nick.text password = App.get_running_app().root.ids.tw.code.text message = password + ":" + nickname + ":" + str(int(self.hostVisible)) + ":" + str(self.teamNumber) print("Message sent to server: " + message) client = Client.get_instance() client.send_message(client.INIT_MESSAGE, message) sleep(1) if client.get_token is None: return tw = App.get_running_app().root.ids.tw tw.current_blinker = blinker = GpsBlinker(lon=19.9125399, lat=50.0680966, nick=nickname, color_number=10) team_map = App.get_running_app().root.ids.mw.ids.map team_map.add_widget(blinker) team_map.add_host_buttons() blinker.blink() App.get_running_app().gps_mod.start_updating(blinker) screen = App.get_running_app().root screen.current = "viewer" ReturnBinder.get_instance().current_screen = "viewer" # -----------------------------These classes made for pop window of team tokens----------------------------------------- def show_popup(text): show = Pop(text) popupWindow = Popup(title="Password for teams:", content=show, size_hint=(None, None), size=(sp(200), sp(250))) popupWindow.open() class Pop(FloatLayout): text = "placeholder" def __init__(self, text, **kwargs): self.text = text super(FloatLayout, self).__init__(**kwargs) class BtnPopup(Widget): text = '' def __init__(self, text="PLACEHOLDER", *args, **kwargs): super().__init__(**kwargs) self.text = text def click(self): show_popup(text=self.text) def terminate_game_remove_host_privileges(self): content = ConfirmPopup(text='Are you sure?') content.bind(on_answer=self._on_answer) self.popup = Popup(title="Terminating game", content=content, size_hint=(None, None), size=(sp(200), sp(200))) self.popup.open() def _on_answer(self, instance, answer): if answer is 'yes': client = Client.get_instance() client.send_message(client.CLOSE_GAME, None) team_map = App.get_running_app().root.ids.mw.ids.map team_map.remove_host_buttons() tw = App.get_running_app().root.ids.tw team_map.remove_widget(tw.current_blinker) team_map.host_buttons = None App.get_running_app().root.current = "menu" ReturnBinder.get_instance().current_screen = "menu" self.popup.dismiss() class ConfirmPopup(GridLayout): text = StringProperty() def __init__(self, **kwargs): self.register_event_type('on_answer') super(ConfirmPopup, self).__init__(**kwargs) def on_answer(self, *args): pass
from time import sleep from kivy.app import App from kivy.properties import ObjectProperty, StringProperty from kivy.uix.gridlayout import GridLayout from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.treeview import TreeViewLabel from kivy.uix.popup import Popup from kivy.uix.floatlayout import FloatLayout from kivy.uix.widget import Widget from kivy.utils import get_color_from_hex from kivy.metrics import * from client import Client # from app.client import Client from colordict import color_dictionary from gpsblinker import GpsBlinker from kivy.storage.jsonstore import JsonStore import atexit import os import glob from returnbinder import ReturnBinder class WindowManager(ScreenManager): pass class MapWindow(Screen): pass class TokenWindow(Screen): nick = ObjectProperty(None) code = ObjectProperty(None) ip_address = ObjectProperty(None) client = Client.get_instance() colornum = 10 # Expected to change. If players stay black something is wrong current_blinker = None stored_data = JsonStore('data.json') def __disconnect(self): files = glob.glob('cache/*.png') for f in files: if not f.endswith(".png"): # Additional safety, should never happen print("ERROR WHILE CLEARING CACHE, FOUND NON-PNG FILE, ABORTING") break os.remove(f) self.client.send_message(self.client.DISCONNECT_MESSAGE, self.code.text) sleep(1) def __connect(self): if 'host-' in self.nick.text or ':' in self.nick.text or\ len(self.nick.text) >= 16 or\ len(self.code.text) > 10 or\ len(self.ip_address.text) > 16: return self.client.connect(server_ip=self.ip_address.text) # after pressing "Host Game" button: def host_connect(self): self.__connect() if not self.client.is_connected(): return atexit.register(self.__disconnect) screen = App.get_running_app().root screen.current = "host" ReturnBinder.get_instance().current_screen = "host" self.stored_data.clear() self.stored_data.put('credentials', ip_address=self.ip_address.text, nick=self.nick.text) # after pressing "Connect Game" button: def player_connect(self): self.__connect() if not self.client.is_connected(): return atexit.register(self.__disconnect) message = self.code.text + ":" + self.nick.text print("Message being sent to server: " + message) self.client.send_message(self.client.INIT_MESSAGE, message) sleep(1) if self.client.get_token() is None: return # Takes first letter as number from 0 to 9: || #1ABCD means color 1 || if len(self.code.text) >= 1 and self.code.text[0].isdigit(): self.colornum = int(self.code.text[0]) # GPS always starts in AGH WIEiT faculty building self.current_blinker = blinker = GpsBlinker(lon=19.9125399, lat=50.0680966, nick=self.nick.text, color_number=self.colornum) team_map = App.get_running_app().root.ids.mw.ids.map team_map.add_widget(blinker) team_map.start_checking = True blinker.blink() App.get_running_app().gps_mod.start_updating(blinker) self.stored_data.clear() self.stored_data.put('credentials', ip_address=self.ip_address.text, nick=self.nick.text) screen = App.get_running_app().root screen.current = "viewer" ReturnBinder.get_instance().current_screen = "viewer" class HostWindow(Screen): # Window for setting game rules switch = ObjectProperty(None) # Set to None because it is created before actual switch from .kv file slider = ObjectProperty(None) tv = ObjectProperty(None) hostVisible = False teamNumber = 0 def create_nodes(self): if int(self.slider.value) == self.teamNumber: return self.teamNumber = int(self.slider.value) for node in [i for i in self.tv.iterate_all_nodes()]: self.tv.remove_node(node) for i in range(int(self.slider.value)): self.teamNumber = i + 1 name = 'Druzyna ' + str(i + 1) color = get_color_from_hex(color_dictionary[i]) self.tv.add_node(TreeViewLabel(text=name, color=color)) def host_to_server(self): self.hostVisible = self.switch.active nickname = App.get_running_app().root.ids.tw.nick.text password = App.get_running_app().root.ids.tw.code.text message = password + ":" + nickname + ":" + str(int(self.hostVisible)) + ":" + str(self.teamNumber) print("Message sent to server: " + message) client = Client.get_instance() client.send_message(client.INIT_MESSAGE, message) sleep(1) if client.get_token is None: return tw = App.get_running_app().root.ids.tw tw.current_blinker = blinker = GpsBlinker(lon=19.9125399, lat=50.0680966, nick=nickname, color_number=10) team_map = App.get_running_app().root.ids.mw.ids.map team_map.add_widget(blinker) team_map.add_host_buttons() blinker.blink() App.get_running_app().gps_mod.start_updating(blinker) screen = App.get_running_app().root screen.current = "viewer" ReturnBinder.get_instance().current_screen = "viewer" # -----------------------------These classes made for pop window of team tokens----------------------------------------- def show_popup(text): show = Pop(text) popupWindow = Popup(title="Password for teams:", content=show, size_hint=(None, None), size=(sp(200), sp(250))) popupWindow.open() class Pop(FloatLayout): text = "placeholder" def __init__(self, text, **kwargs): self.text = text super(FloatLayout, self).__init__(**kwargs) class BtnPopup(Widget): text = '' def __init__(self, text="PLACEHOLDER", *args, **kwargs): super().__init__(**kwargs) self.text = text def click(self): show_popup(text=self.text) def terminate_game_remove_host_privileges(self): content = ConfirmPopup(text='Are you sure?') content.bind(on_answer=self._on_answer) self.popup = Popup(title="Terminating game", content=content, size_hint=(None, None), size=(sp(200), sp(200))) self.popup.open() def _on_answer(self, instance, answer): if answer is 'yes': client = Client.get_instance() client.send_message(client.CLOSE_GAME, None) team_map = App.get_running_app().root.ids.mw.ids.map team_map.remove_host_buttons() tw = App.get_running_app().root.ids.tw team_map.remove_widget(tw.current_blinker) team_map.host_buttons = None App.get_running_app().root.current = "menu" ReturnBinder.get_instance().current_screen = "menu" self.popup.dismiss() class ConfirmPopup(GridLayout): text = StringProperty() def __init__(self, **kwargs): self.register_event_type('on_answer') super(ConfirmPopup, self).__init__(**kwargs) def on_answer(self, *args): pass
en
0.872304
# from app.client import Client # Expected to change. If players stay black something is wrong # Additional safety, should never happen # after pressing "Host Game" button: # after pressing "Connect Game" button: # Takes first letter as number from 0 to 9: || #1ABCD means color 1 || # GPS always starts in AGH WIEiT faculty building # Window for setting game rules # Set to None because it is created before actual switch from .kv file # -----------------------------These classes made for pop window of team tokens-----------------------------------------
2.28657
2
k2/python/tests/shortest_path_test.py
Jarvan-Wang/k2
0
6625835
<gh_stars>0 #!/usr/bin/env python3 # # Copyright (c) 2020 Mobvoi Inc. (authors: <NAME>) # # See ../../../LICENSE for clarification regarding multiple authors # To run this single test, use # # ctest --verbose -R shortest_path_test_py import unittest import k2 import torch class TestShortestPath(unittest.TestCase): @classmethod def setUpClass(cls): cls.devices = [torch.device('cpu')] if torch.cuda.is_available() and k2.with_cuda: cls.devices.append(torch.device('cuda', 0)) if torch.cuda.device_count() > 1: torch.cuda.set_device(1) cls.devices.append(torch.device('cuda', 1)) def test_single_fsa(self): s = ''' 0 4 1 1 0 1 1 1 1 2 1 2 1 3 1 3 2 7 1 4 3 7 1 5 4 6 1 2 4 8 1 3 5 9 -1 4 6 9 -1 3 7 9 -1 5 8 9 -1 6 9 ''' for device in self.devices: fsa = k2.Fsa.from_str(s).to(device) fsa = k2.create_fsa_vec([fsa]) fsa.requires_grad_(True) best_path = k2.shortest_path(fsa, use_double_scores=False) # we recompute the total_scores for backprop total_scores = best_path.scores.sum() assert total_scores == 14 expected = torch.zeros(12) expected[torch.tensor([1, 3, 5, 10])] = 1 total_scores.backward() assert torch.allclose(fsa.scores.grad, expected.to(device)) def test_fsa_vec(self): # best path: # states: 0 -> 1 -> 3 -> 7 -> 9 # arcs: 1 -> 3 -> 5 -> 10 s1 = ''' 0 4 1 1 0 1 1 1 1 2 1 2 1 3 1 3 2 7 1 4 3 7 1 5 4 6 1 2 4 8 1 3 5 9 -1 4 6 9 -1 3 7 9 -1 5 8 9 -1 6 9 ''' # best path: # states: 0 -> 2 -> 3 -> 4 -> 5 # arcs: 1 -> 4 -> 5 -> 7 s2 = ''' 0 1 1 1 0 2 2 6 1 2 3 3 1 3 4 2 2 3 5 4 3 4 6 3 3 5 -1 2 4 5 -1 0 5 ''' # best path: # states: 0 -> 2 -> 3 # arcs: 1 -> 3 s3 = ''' 0 1 1 10 0 2 2 100 1 3 -1 3.5 2 3 -1 5.5 3 ''' for device in self.devices: fsa1 = k2.Fsa.from_str(s1).to(device) fsa2 = k2.Fsa.from_str(s2).to(device) fsa3 = k2.Fsa.from_str(s3).to(device) fsa1.requires_grad_(True) fsa2.requires_grad_(True) fsa3.requires_grad_(True) fsa_vec = k2.create_fsa_vec([fsa1, fsa2, fsa3]) assert fsa_vec.shape == (3, None, None) best_path = k2.shortest_path(fsa_vec, use_double_scores=False) # we recompute the total_scores for backprop total_scores = best_path.scores.sum() total_scores.backward() fsa1_best_arc_indexes = torch.tensor([1, 3, 5, 10], device=device) assert torch.all( torch.eq(fsa1.scores.grad[fsa1_best_arc_indexes], torch.ones(4, device=device))) assert fsa1.scores.grad.sum() == 4 fsa2_best_arc_indexes = torch.tensor([1, 4, 5, 7], device=device) assert torch.all( torch.eq(fsa2.scores.grad[fsa2_best_arc_indexes], torch.ones(4, device=device))) assert fsa2.scores.grad.sum() == 4 fsa3_best_arc_indexes = torch.tensor([1, 3], device=device) assert torch.all( torch.eq(fsa3.scores.grad[fsa3_best_arc_indexes], torch.ones(2, device=device))) assert fsa3.scores.grad.sum() == 2 if __name__ == '__main__': unittest.main()
#!/usr/bin/env python3 # # Copyright (c) 2020 Mobvoi Inc. (authors: <NAME>) # # See ../../../LICENSE for clarification regarding multiple authors # To run this single test, use # # ctest --verbose -R shortest_path_test_py import unittest import k2 import torch class TestShortestPath(unittest.TestCase): @classmethod def setUpClass(cls): cls.devices = [torch.device('cpu')] if torch.cuda.is_available() and k2.with_cuda: cls.devices.append(torch.device('cuda', 0)) if torch.cuda.device_count() > 1: torch.cuda.set_device(1) cls.devices.append(torch.device('cuda', 1)) def test_single_fsa(self): s = ''' 0 4 1 1 0 1 1 1 1 2 1 2 1 3 1 3 2 7 1 4 3 7 1 5 4 6 1 2 4 8 1 3 5 9 -1 4 6 9 -1 3 7 9 -1 5 8 9 -1 6 9 ''' for device in self.devices: fsa = k2.Fsa.from_str(s).to(device) fsa = k2.create_fsa_vec([fsa]) fsa.requires_grad_(True) best_path = k2.shortest_path(fsa, use_double_scores=False) # we recompute the total_scores for backprop total_scores = best_path.scores.sum() assert total_scores == 14 expected = torch.zeros(12) expected[torch.tensor([1, 3, 5, 10])] = 1 total_scores.backward() assert torch.allclose(fsa.scores.grad, expected.to(device)) def test_fsa_vec(self): # best path: # states: 0 -> 1 -> 3 -> 7 -> 9 # arcs: 1 -> 3 -> 5 -> 10 s1 = ''' 0 4 1 1 0 1 1 1 1 2 1 2 1 3 1 3 2 7 1 4 3 7 1 5 4 6 1 2 4 8 1 3 5 9 -1 4 6 9 -1 3 7 9 -1 5 8 9 -1 6 9 ''' # best path: # states: 0 -> 2 -> 3 -> 4 -> 5 # arcs: 1 -> 4 -> 5 -> 7 s2 = ''' 0 1 1 1 0 2 2 6 1 2 3 3 1 3 4 2 2 3 5 4 3 4 6 3 3 5 -1 2 4 5 -1 0 5 ''' # best path: # states: 0 -> 2 -> 3 # arcs: 1 -> 3 s3 = ''' 0 1 1 10 0 2 2 100 1 3 -1 3.5 2 3 -1 5.5 3 ''' for device in self.devices: fsa1 = k2.Fsa.from_str(s1).to(device) fsa2 = k2.Fsa.from_str(s2).to(device) fsa3 = k2.Fsa.from_str(s3).to(device) fsa1.requires_grad_(True) fsa2.requires_grad_(True) fsa3.requires_grad_(True) fsa_vec = k2.create_fsa_vec([fsa1, fsa2, fsa3]) assert fsa_vec.shape == (3, None, None) best_path = k2.shortest_path(fsa_vec, use_double_scores=False) # we recompute the total_scores for backprop total_scores = best_path.scores.sum() total_scores.backward() fsa1_best_arc_indexes = torch.tensor([1, 3, 5, 10], device=device) assert torch.all( torch.eq(fsa1.scores.grad[fsa1_best_arc_indexes], torch.ones(4, device=device))) assert fsa1.scores.grad.sum() == 4 fsa2_best_arc_indexes = torch.tensor([1, 4, 5, 7], device=device) assert torch.all( torch.eq(fsa2.scores.grad[fsa2_best_arc_indexes], torch.ones(4, device=device))) assert fsa2.scores.grad.sum() == 4 fsa3_best_arc_indexes = torch.tensor([1, 3], device=device) assert torch.all( torch.eq(fsa3.scores.grad[fsa3_best_arc_indexes], torch.ones(2, device=device))) assert fsa3.scores.grad.sum() == 2 if __name__ == '__main__': unittest.main()
en
0.467052
#!/usr/bin/env python3 # # Copyright (c) 2020 Mobvoi Inc. (authors: <NAME>) # # See ../../../LICENSE for clarification regarding multiple authors # To run this single test, use # # ctest --verbose -R shortest_path_test_py 0 4 1 1 0 1 1 1 1 2 1 2 1 3 1 3 2 7 1 4 3 7 1 5 4 6 1 2 4 8 1 3 5 9 -1 4 6 9 -1 3 7 9 -1 5 8 9 -1 6 9 # we recompute the total_scores for backprop # best path: # states: 0 -> 1 -> 3 -> 7 -> 9 # arcs: 1 -> 3 -> 5 -> 10 0 4 1 1 0 1 1 1 1 2 1 2 1 3 1 3 2 7 1 4 3 7 1 5 4 6 1 2 4 8 1 3 5 9 -1 4 6 9 -1 3 7 9 -1 5 8 9 -1 6 9 # best path: # states: 0 -> 2 -> 3 -> 4 -> 5 # arcs: 1 -> 4 -> 5 -> 7 0 1 1 1 0 2 2 6 1 2 3 3 1 3 4 2 2 3 5 4 3 4 6 3 3 5 -1 2 4 5 -1 0 5 # best path: # states: 0 -> 2 -> 3 # arcs: 1 -> 3 0 1 1 10 0 2 2 100 1 3 -1 3.5 2 3 -1 5.5 3 # we recompute the total_scores for backprop
2.815456
3
train_quant.py
Roxbili/kws-demo
0
6625836
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # # Modifications Copyright 2017 Arm Inc. All Rights Reserved. # Added model dimensions as command line argument and changed to Adam optimizer # # """Simple speech recognition to spot a limited number of keywords. This is a self-contained example script that will train a very basic audio recognition model in TensorFlow. It downloads the necessary training data and runs with reasonable defaults to train within a few hours even only using a CPU. For more information, please see https://www.tensorflow.org/tutorials/audio_recognition. It is intended as an introduction to using neural networks for audio recognition, and is not a full speech recognition system. For more advanced speech systems, I recommend looking into Kaldi. This network uses a keyword detection style to spot discrete words from a small vocabulary, consisting of "yes", "no", "up", "down", "left", "right", "on", "off", "stop", and "go". To run the training process, use: bazel run tensorflow/examples/speech_commands:train This will write out checkpoints to /tmp/speech_commands_train/, and will download over 1GB of open source training data, so you'll need enough free space and a good internet connection. The default data is a collection of thousands of one-second .wav files, each containing one spoken word. This data set is collected from https://aiyprojects.withgoogle.com/open_speech_recording, please consider contributing to help improve this and other models! As training progresses, it will print out its accuracy metrics, which should rise above 90% by the end. Once it's complete, you can run the freeze script to get a binary GraphDef that you can easily deploy on mobile applications. If you want to train on your own data, you'll need to create .wavs with your recordings, all at a consistent length, and then arrange them into subfolders organized by label. For example, here's a possible file structure: my_wavs > up > audio_0.wav audio_1.wav down > audio_2.wav audio_3.wav other> audio_4.wav audio_5.wav You'll also need to tell the script what labels to look for, using the `--wanted_words` argument. In this case, 'up,down' might be what you want, and the audio in the 'other' folder would be used to train an 'unknown' category. To pull this all together, you'd run: bazel run tensorflow/examples/speech_commands:train -- \ --data_dir=my_wavs --wanted_words=up,down """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import os.path import sys import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf import input_data import models from tensorflow.python.platform import gfile from tensorflow.contrib import slim as slim def main(_): # We want to see all the logging messages for this tutorial. tf.logging.set_verbosity(tf.logging.INFO) # Start a new TensorFlow session. sess = tf.InteractiveSession() # Begin by making sure we have the training data we need. If you already have # training data of your own, use `--data_url= ` on the command line to avoid # downloading. model_settings = models.prepare_model_settings( len(input_data.prepare_words_list(FLAGS.wanted_words.split(','))), FLAGS.sample_rate, FLAGS.clip_duration_ms, FLAGS.window_size_ms, FLAGS.window_stride_ms, FLAGS.dct_coefficient_count) # print(model_settings['label_count']) # sys.exit(0) audio_processor = input_data.AudioProcessor( FLAGS.data_url, FLAGS.data_dir, FLAGS.silence_percentage, FLAGS.unknown_percentage, FLAGS.wanted_words.split(','), FLAGS.validation_percentage, FLAGS.testing_percentage, model_settings) fingerprint_size = model_settings['fingerprint_size'] label_count = model_settings['label_count'] time_shift_samples = int((FLAGS.time_shift_ms * FLAGS.sample_rate) / 1000) # Figure out the learning rates for each training phase. Since it's often # effective to have high learning rates at the start of training, followed by # lower levels towards the end, the number of steps and learning rates can be # specified as comma-separated lists to define the rate at each stage. For # example --how_many_training_steps=10000,3000 --learning_rate=0.001,0.0001 # will run 13,000 training loops in total, with a rate of 0.001 for the first # 10,000, and 0.0001 for the final 3,000. training_steps_list = list(map(int, FLAGS.how_many_training_steps.split(','))) learning_rates_list = list(map(float, FLAGS.learning_rate.split(','))) if len(training_steps_list) != len(learning_rates_list): raise Exception( '--how_many_training_steps and --learning_rate must be equal length ' 'lists, but are %d and %d long instead' % (len(training_steps_list), len(learning_rates_list))) fingerprint_input = tf.placeholder( tf.float32, [None, fingerprint_size], name='fingerprint_input') # is_training = tf.placeholder(shape=(), dtype=tf.bool) is_training = True logits = models.create_model( fingerprint_input, model_settings, FLAGS.model_architecture, FLAGS.model_size_info, is_training=is_training) # Trainable vars has to be collected before adding quant ops. trainable_vars = tf.trainable_variables() # Define loss and optimizer ground_truth_input = tf.placeholder( tf.float32, [None, label_count], name='groundtruth_input') # Optionally we can add runtime checks to spot when NaNs or other symptoms of # numerical errors start occurring during training. control_dependencies = [] if FLAGS.check_nans: checks = tf.add_check_numerics_ops() control_dependencies = [checks] if FLAGS.quant: tf.logging.info("Adding quantization ops...") tf.contrib.quantize.experimental_create_training_graph(sess.graph, weight_bits=FLAGS.bits, activation_bits=FLAGS.bits, quant_delay=2400, symmetric=True) print("Done") # Now, create dependencies for quantizing weights with tf.name_scope('cross_entropy'): cross_entropy_mean = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits( labels=ground_truth_input, logits=logits)) tf.summary.scalar('cross_entropy', cross_entropy_mean) update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) global_step = tf.train.get_or_create_global_step() increment_global_step = tf.assign(global_step, global_step + 1) start_step = 1 tf.logging.info('Training from step: %d ', start_step) with tf.name_scope('train'), tf.control_dependencies(update_ops), tf.control_dependencies(control_dependencies): learning_rate_input = tf.placeholder( tf.float32, [], name='learning_rate_input') train_op = tf.train.AdamOptimizer( learning_rate_input) train_step = slim.learning.create_train_op(cross_entropy_mean, train_op) # train_step = tf.train.GradientDescentOptimizer( # learning_rate_input).minimize(cross_entropy_mean) predicted_indices = tf.argmax(logits, 1) expected_indices = tf.argmax(ground_truth_input, 1) correct_prediction = tf.equal(predicted_indices, expected_indices) confusion_matrix = tf.confusion_matrix( expected_indices, predicted_indices, num_classes=label_count) evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) tf.summary.scalar('accuracy', evaluation_step) saver = tf.train.Saver(tf.global_variables()) # Merge all the summaries and write them out to /tmp/retrain_logs (by default) merged_summaries = tf.summary.merge_all() train_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/train', sess.graph) validation_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/validation') tf.global_variables_initializer().run() if FLAGS.start_checkpoint: try: models.load_variables_from_checkpoint(sess, FLAGS.start_checkpoint, trainable_vars) except Exception: pass start_step = global_step.eval(session=sess) # Parameter counts params = tf.trainable_variables() num_params = sum(map(lambda t: np.prod(tf.shape(t.value()).eval()), params)) print('Total number of Parameters: ', num_params) # Save graph.pbtxt. tf.train.write_graph(sess.graph_def, FLAGS.train_dir, FLAGS.model_architecture + '.pbtxt') # Save list of words. with gfile.GFile( os.path.join(FLAGS.train_dir, FLAGS.model_architecture + '_labels.txt'), 'w') as f: f.write('\n'.join(audio_processor.words_list)) # Training loop. best_accuracy = 0 training_steps_max = np.sum(training_steps_list) for training_step in xrange(start_step, training_steps_max + 1): # Figure out what the current learning rate is. training_steps_sum = 0 for i in range(len(training_steps_list)): training_steps_sum += training_steps_list[i] if training_step <= training_steps_sum: learning_rate_value = learning_rates_list[i] break # Pull the audio samples we'll use for training. train_fingerprints, train_ground_truth = audio_processor.get_data( FLAGS.batch_size, 0, model_settings, FLAGS.background_frequency, FLAGS.background_volume, time_shift_samples, 'training', sess) # Run the graph with this batch of training data. train_summary, train_accuracy, cross_entropy_value, _, _ = sess.run( [ merged_summaries, evaluation_step, cross_entropy_mean, train_step, increment_global_step ], feed_dict={ fingerprint_input: train_fingerprints, ground_truth_input: train_ground_truth, learning_rate_input: learning_rate_value, }) train_writer.add_summary(train_summary, training_step) tf.logging.info('Step #%d: rate %f, accuracy %.2f%%, cross entropy %f' % (training_step, learning_rate_value, train_accuracy * 100, cross_entropy_value)) is_last_step = (training_step == training_steps_max) """ if (training_step % FLAGS.eval_step_interval) == 0 or is_last_step: set_size = audio_processor.set_size('validation') total_accuracy = 0 total_conf_matrix = None for i in xrange(0, set_size, FLAGS.batch_size): validation_fingerprints, validation_ground_truth = ( audio_processor.get_data(FLAGS.batch_size, i, model_settings, 0.0, 0.0, 0, 'validation', sess)) # Run a validation step and capture training summaries for TensorBoard # with the `merged` op. validation_summary, validation_accuracy, conf_matrix = sess.run( [merged_summaries, evaluation_step, confusion_matrix], feed_dict={ fingerprint_input: validation_fingerprints, ground_truth_input: validation_ground_truth, }) validation_writer.add_summary(validation_summary, training_step) batch_size = min(FLAGS.batch_size, set_size - i) total_accuracy += (validation_accuracy * batch_size) / set_size if total_conf_matrix is None: total_conf_matrix = conf_matrix else: total_conf_matrix += conf_matrix tf.logging.info('Confusion Matrix:\n %s' % (total_conf_matrix)) tf.logging.info('Step %d: Validation accuracy = %.2f%% (N=%d)' % (training_step, total_accuracy * 100, set_size)) """ # Save the model checkpoint when validation accuracy improves """ if total_accuracy > best_accuracy: best_accuracy = total_accuracy checkpoint_path = os.path.join(FLAGS.train_dir, 'best', FLAGS.model_architecture + '_' + str(int(best_accuracy * 10000)) + '.ckpt') tf.logging.info('Saving best model to "%s-%d"', checkpoint_path, training_step) saver.save(sess, checkpoint_path, global_step=training_step) tf.logging.info('So far the best validation accuracy is %.2f%%' % (best_accuracy * 100)) """ if (training_step % FLAGS.eval_step_interval) == 0 or is_last_step: checkpoint_path = os.path.join(FLAGS.train_dir, 'best', FLAGS.model_architecture + ".ckpt") tf.logging.info('Saving best model to "%s-%d"', checkpoint_path, training_step) saver.save(sess, checkpoint_path, global_step=training_step) set_size = audio_processor.set_size('testing') tf.logging.info('set_size=%d', set_size) total_accuracy = 0 total_conf_matrix = None for i in xrange(0, set_size, FLAGS.batch_size): test_fingerprints, test_ground_truth = audio_processor.get_data( FLAGS.batch_size, i, model_settings, 0.0, 0.0, 0, 'testing', sess) test_accuracy, conf_matrix = sess.run( [evaluation_step, confusion_matrix], feed_dict={ fingerprint_input: test_fingerprints, ground_truth_input: test_ground_truth, }) batch_size = min(FLAGS.batch_size, set_size - i) total_accuracy += (test_accuracy * batch_size) / set_size if total_conf_matrix is None: total_conf_matrix = conf_matrix else: total_conf_matrix += conf_matrix tf.logging.info('Confusion Matrix:\n %s' % (total_conf_matrix)) tf.logging.info('Final test accuracy = %.2f%% (N=%d)' % (total_accuracy * 100, set_size)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--data_url', type=str, # pylint: disable=line-too-long default='http://download.tensorflow.org/data/speech_commands_v0.02.tar.gz', # pylint: enable=line-too-long help='Location of speech training data archive on the web.') parser.add_argument( '--data_dir', type=str, default='/tmp/speech_dataset/', help="""\ Where to download the speech training data to. """) parser.add_argument( '--background_volume', type=float, default=0.1, help="""\ How loud the background noise should be, between 0 and 1. """) parser.add_argument( '--background_frequency', type=float, default=0.8, help="""\ How many of the training samples have background noise mixed in. """) parser.add_argument( '--silence_percentage', type=float, default=10.0, help="""\ How much of the training data should be silence. """) parser.add_argument( '--unknown_percentage', type=float, default=10.0, help="""\ How much of the training data should be unknown words. """) parser.add_argument( '--time_shift_ms', type=float, default=100.0, help="""\ Range to randomly shift the training audio by in time. """) parser.add_argument( '--testing_percentage', type=int, default=10, help='What percentage of wavs to use as a test set.') parser.add_argument( '--validation_percentage', type=int, default=10, help='What percentage of wavs to use as a validation set.') parser.add_argument( '--sample_rate', type=int, default=16000, help='Expected sample rate of the wavs',) parser.add_argument( '--clip_duration_ms', type=int, default=1000, help='Expected duration in milliseconds of the wavs',) parser.add_argument( '--window_size_ms', type=float, default=30.0, help='How long each spectrogram timeslice is',) parser.add_argument( '--window_stride_ms', type=float, default=10.0, help='How long each spectrogram timeslice is',) parser.add_argument( '--dct_coefficient_count', type=int, default=40, help='How many bins to use for the MFCC fingerprint',) parser.add_argument( '--how_many_training_steps', type=str, default='15000,3000', help='How many training loops to run',) parser.add_argument( '--eval_step_interval', type=int, default=400, help='How often to evaluate the training results.') parser.add_argument( '--learning_rate', type=str, default='0.001,0.0001', help='How large a learning rate to use when training.') parser.add_argument( '--batch_size', type=int, default=100, help='How many items to train with at once',) parser.add_argument( '--summaries_dir', type=str, default='/tmp/retrain_logs', help='Where to save summary logs for TensorBoard.') parser.add_argument( '--wanted_words', type=str, default='yes,no,up,down,left,right,on,off,stop,go', help='Words to use (others will be added to an unknown label)',) parser.add_argument( '--train_dir', type=str, default='/tmp/speech_commands_train', help='Directory to write event logs and checkpoint.') parser.add_argument( '--save_step_interval', type=int, default=100, help='Save model checkpoint every save_steps.') parser.add_argument( '--start_checkpoint', type=str, default='', help='If specified, restore this pretrained model before any training.') parser.add_argument( '--model_architecture', type=str, default='dnn', help='What model architecture to use') parser.add_argument( '--model_size_info', type=int, nargs="+", default=[128,128,128], help='Model dimensions - different for various models') parser.add_argument( '--check_nans', type=bool, default=False, help='Whether to check for invalid numbers during processing') parser.add_argument("--quant", action='store_true', default=False) parser.add_argument("--bits", type=int, # 只有当quant参数有效的时候这个参数才能生效 default=8) FLAGS, unparsed = parser.parse_known_args() tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # # Modifications Copyright 2017 Arm Inc. All Rights Reserved. # Added model dimensions as command line argument and changed to Adam optimizer # # """Simple speech recognition to spot a limited number of keywords. This is a self-contained example script that will train a very basic audio recognition model in TensorFlow. It downloads the necessary training data and runs with reasonable defaults to train within a few hours even only using a CPU. For more information, please see https://www.tensorflow.org/tutorials/audio_recognition. It is intended as an introduction to using neural networks for audio recognition, and is not a full speech recognition system. For more advanced speech systems, I recommend looking into Kaldi. This network uses a keyword detection style to spot discrete words from a small vocabulary, consisting of "yes", "no", "up", "down", "left", "right", "on", "off", "stop", and "go". To run the training process, use: bazel run tensorflow/examples/speech_commands:train This will write out checkpoints to /tmp/speech_commands_train/, and will download over 1GB of open source training data, so you'll need enough free space and a good internet connection. The default data is a collection of thousands of one-second .wav files, each containing one spoken word. This data set is collected from https://aiyprojects.withgoogle.com/open_speech_recording, please consider contributing to help improve this and other models! As training progresses, it will print out its accuracy metrics, which should rise above 90% by the end. Once it's complete, you can run the freeze script to get a binary GraphDef that you can easily deploy on mobile applications. If you want to train on your own data, you'll need to create .wavs with your recordings, all at a consistent length, and then arrange them into subfolders organized by label. For example, here's a possible file structure: my_wavs > up > audio_0.wav audio_1.wav down > audio_2.wav audio_3.wav other> audio_4.wav audio_5.wav You'll also need to tell the script what labels to look for, using the `--wanted_words` argument. In this case, 'up,down' might be what you want, and the audio in the 'other' folder would be used to train an 'unknown' category. To pull this all together, you'd run: bazel run tensorflow/examples/speech_commands:train -- \ --data_dir=my_wavs --wanted_words=up,down """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import os.path import sys import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf import input_data import models from tensorflow.python.platform import gfile from tensorflow.contrib import slim as slim def main(_): # We want to see all the logging messages for this tutorial. tf.logging.set_verbosity(tf.logging.INFO) # Start a new TensorFlow session. sess = tf.InteractiveSession() # Begin by making sure we have the training data we need. If you already have # training data of your own, use `--data_url= ` on the command line to avoid # downloading. model_settings = models.prepare_model_settings( len(input_data.prepare_words_list(FLAGS.wanted_words.split(','))), FLAGS.sample_rate, FLAGS.clip_duration_ms, FLAGS.window_size_ms, FLAGS.window_stride_ms, FLAGS.dct_coefficient_count) # print(model_settings['label_count']) # sys.exit(0) audio_processor = input_data.AudioProcessor( FLAGS.data_url, FLAGS.data_dir, FLAGS.silence_percentage, FLAGS.unknown_percentage, FLAGS.wanted_words.split(','), FLAGS.validation_percentage, FLAGS.testing_percentage, model_settings) fingerprint_size = model_settings['fingerprint_size'] label_count = model_settings['label_count'] time_shift_samples = int((FLAGS.time_shift_ms * FLAGS.sample_rate) / 1000) # Figure out the learning rates for each training phase. Since it's often # effective to have high learning rates at the start of training, followed by # lower levels towards the end, the number of steps and learning rates can be # specified as comma-separated lists to define the rate at each stage. For # example --how_many_training_steps=10000,3000 --learning_rate=0.001,0.0001 # will run 13,000 training loops in total, with a rate of 0.001 for the first # 10,000, and 0.0001 for the final 3,000. training_steps_list = list(map(int, FLAGS.how_many_training_steps.split(','))) learning_rates_list = list(map(float, FLAGS.learning_rate.split(','))) if len(training_steps_list) != len(learning_rates_list): raise Exception( '--how_many_training_steps and --learning_rate must be equal length ' 'lists, but are %d and %d long instead' % (len(training_steps_list), len(learning_rates_list))) fingerprint_input = tf.placeholder( tf.float32, [None, fingerprint_size], name='fingerprint_input') # is_training = tf.placeholder(shape=(), dtype=tf.bool) is_training = True logits = models.create_model( fingerprint_input, model_settings, FLAGS.model_architecture, FLAGS.model_size_info, is_training=is_training) # Trainable vars has to be collected before adding quant ops. trainable_vars = tf.trainable_variables() # Define loss and optimizer ground_truth_input = tf.placeholder( tf.float32, [None, label_count], name='groundtruth_input') # Optionally we can add runtime checks to spot when NaNs or other symptoms of # numerical errors start occurring during training. control_dependencies = [] if FLAGS.check_nans: checks = tf.add_check_numerics_ops() control_dependencies = [checks] if FLAGS.quant: tf.logging.info("Adding quantization ops...") tf.contrib.quantize.experimental_create_training_graph(sess.graph, weight_bits=FLAGS.bits, activation_bits=FLAGS.bits, quant_delay=2400, symmetric=True) print("Done") # Now, create dependencies for quantizing weights with tf.name_scope('cross_entropy'): cross_entropy_mean = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits( labels=ground_truth_input, logits=logits)) tf.summary.scalar('cross_entropy', cross_entropy_mean) update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) global_step = tf.train.get_or_create_global_step() increment_global_step = tf.assign(global_step, global_step + 1) start_step = 1 tf.logging.info('Training from step: %d ', start_step) with tf.name_scope('train'), tf.control_dependencies(update_ops), tf.control_dependencies(control_dependencies): learning_rate_input = tf.placeholder( tf.float32, [], name='learning_rate_input') train_op = tf.train.AdamOptimizer( learning_rate_input) train_step = slim.learning.create_train_op(cross_entropy_mean, train_op) # train_step = tf.train.GradientDescentOptimizer( # learning_rate_input).minimize(cross_entropy_mean) predicted_indices = tf.argmax(logits, 1) expected_indices = tf.argmax(ground_truth_input, 1) correct_prediction = tf.equal(predicted_indices, expected_indices) confusion_matrix = tf.confusion_matrix( expected_indices, predicted_indices, num_classes=label_count) evaluation_step = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) tf.summary.scalar('accuracy', evaluation_step) saver = tf.train.Saver(tf.global_variables()) # Merge all the summaries and write them out to /tmp/retrain_logs (by default) merged_summaries = tf.summary.merge_all() train_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/train', sess.graph) validation_writer = tf.summary.FileWriter(FLAGS.summaries_dir + '/validation') tf.global_variables_initializer().run() if FLAGS.start_checkpoint: try: models.load_variables_from_checkpoint(sess, FLAGS.start_checkpoint, trainable_vars) except Exception: pass start_step = global_step.eval(session=sess) # Parameter counts params = tf.trainable_variables() num_params = sum(map(lambda t: np.prod(tf.shape(t.value()).eval()), params)) print('Total number of Parameters: ', num_params) # Save graph.pbtxt. tf.train.write_graph(sess.graph_def, FLAGS.train_dir, FLAGS.model_architecture + '.pbtxt') # Save list of words. with gfile.GFile( os.path.join(FLAGS.train_dir, FLAGS.model_architecture + '_labels.txt'), 'w') as f: f.write('\n'.join(audio_processor.words_list)) # Training loop. best_accuracy = 0 training_steps_max = np.sum(training_steps_list) for training_step in xrange(start_step, training_steps_max + 1): # Figure out what the current learning rate is. training_steps_sum = 0 for i in range(len(training_steps_list)): training_steps_sum += training_steps_list[i] if training_step <= training_steps_sum: learning_rate_value = learning_rates_list[i] break # Pull the audio samples we'll use for training. train_fingerprints, train_ground_truth = audio_processor.get_data( FLAGS.batch_size, 0, model_settings, FLAGS.background_frequency, FLAGS.background_volume, time_shift_samples, 'training', sess) # Run the graph with this batch of training data. train_summary, train_accuracy, cross_entropy_value, _, _ = sess.run( [ merged_summaries, evaluation_step, cross_entropy_mean, train_step, increment_global_step ], feed_dict={ fingerprint_input: train_fingerprints, ground_truth_input: train_ground_truth, learning_rate_input: learning_rate_value, }) train_writer.add_summary(train_summary, training_step) tf.logging.info('Step #%d: rate %f, accuracy %.2f%%, cross entropy %f' % (training_step, learning_rate_value, train_accuracy * 100, cross_entropy_value)) is_last_step = (training_step == training_steps_max) """ if (training_step % FLAGS.eval_step_interval) == 0 or is_last_step: set_size = audio_processor.set_size('validation') total_accuracy = 0 total_conf_matrix = None for i in xrange(0, set_size, FLAGS.batch_size): validation_fingerprints, validation_ground_truth = ( audio_processor.get_data(FLAGS.batch_size, i, model_settings, 0.0, 0.0, 0, 'validation', sess)) # Run a validation step and capture training summaries for TensorBoard # with the `merged` op. validation_summary, validation_accuracy, conf_matrix = sess.run( [merged_summaries, evaluation_step, confusion_matrix], feed_dict={ fingerprint_input: validation_fingerprints, ground_truth_input: validation_ground_truth, }) validation_writer.add_summary(validation_summary, training_step) batch_size = min(FLAGS.batch_size, set_size - i) total_accuracy += (validation_accuracy * batch_size) / set_size if total_conf_matrix is None: total_conf_matrix = conf_matrix else: total_conf_matrix += conf_matrix tf.logging.info('Confusion Matrix:\n %s' % (total_conf_matrix)) tf.logging.info('Step %d: Validation accuracy = %.2f%% (N=%d)' % (training_step, total_accuracy * 100, set_size)) """ # Save the model checkpoint when validation accuracy improves """ if total_accuracy > best_accuracy: best_accuracy = total_accuracy checkpoint_path = os.path.join(FLAGS.train_dir, 'best', FLAGS.model_architecture + '_' + str(int(best_accuracy * 10000)) + '.ckpt') tf.logging.info('Saving best model to "%s-%d"', checkpoint_path, training_step) saver.save(sess, checkpoint_path, global_step=training_step) tf.logging.info('So far the best validation accuracy is %.2f%%' % (best_accuracy * 100)) """ if (training_step % FLAGS.eval_step_interval) == 0 or is_last_step: checkpoint_path = os.path.join(FLAGS.train_dir, 'best', FLAGS.model_architecture + ".ckpt") tf.logging.info('Saving best model to "%s-%d"', checkpoint_path, training_step) saver.save(sess, checkpoint_path, global_step=training_step) set_size = audio_processor.set_size('testing') tf.logging.info('set_size=%d', set_size) total_accuracy = 0 total_conf_matrix = None for i in xrange(0, set_size, FLAGS.batch_size): test_fingerprints, test_ground_truth = audio_processor.get_data( FLAGS.batch_size, i, model_settings, 0.0, 0.0, 0, 'testing', sess) test_accuracy, conf_matrix = sess.run( [evaluation_step, confusion_matrix], feed_dict={ fingerprint_input: test_fingerprints, ground_truth_input: test_ground_truth, }) batch_size = min(FLAGS.batch_size, set_size - i) total_accuracy += (test_accuracy * batch_size) / set_size if total_conf_matrix is None: total_conf_matrix = conf_matrix else: total_conf_matrix += conf_matrix tf.logging.info('Confusion Matrix:\n %s' % (total_conf_matrix)) tf.logging.info('Final test accuracy = %.2f%% (N=%d)' % (total_accuracy * 100, set_size)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--data_url', type=str, # pylint: disable=line-too-long default='http://download.tensorflow.org/data/speech_commands_v0.02.tar.gz', # pylint: enable=line-too-long help='Location of speech training data archive on the web.') parser.add_argument( '--data_dir', type=str, default='/tmp/speech_dataset/', help="""\ Where to download the speech training data to. """) parser.add_argument( '--background_volume', type=float, default=0.1, help="""\ How loud the background noise should be, between 0 and 1. """) parser.add_argument( '--background_frequency', type=float, default=0.8, help="""\ How many of the training samples have background noise mixed in. """) parser.add_argument( '--silence_percentage', type=float, default=10.0, help="""\ How much of the training data should be silence. """) parser.add_argument( '--unknown_percentage', type=float, default=10.0, help="""\ How much of the training data should be unknown words. """) parser.add_argument( '--time_shift_ms', type=float, default=100.0, help="""\ Range to randomly shift the training audio by in time. """) parser.add_argument( '--testing_percentage', type=int, default=10, help='What percentage of wavs to use as a test set.') parser.add_argument( '--validation_percentage', type=int, default=10, help='What percentage of wavs to use as a validation set.') parser.add_argument( '--sample_rate', type=int, default=16000, help='Expected sample rate of the wavs',) parser.add_argument( '--clip_duration_ms', type=int, default=1000, help='Expected duration in milliseconds of the wavs',) parser.add_argument( '--window_size_ms', type=float, default=30.0, help='How long each spectrogram timeslice is',) parser.add_argument( '--window_stride_ms', type=float, default=10.0, help='How long each spectrogram timeslice is',) parser.add_argument( '--dct_coefficient_count', type=int, default=40, help='How many bins to use for the MFCC fingerprint',) parser.add_argument( '--how_many_training_steps', type=str, default='15000,3000', help='How many training loops to run',) parser.add_argument( '--eval_step_interval', type=int, default=400, help='How often to evaluate the training results.') parser.add_argument( '--learning_rate', type=str, default='0.001,0.0001', help='How large a learning rate to use when training.') parser.add_argument( '--batch_size', type=int, default=100, help='How many items to train with at once',) parser.add_argument( '--summaries_dir', type=str, default='/tmp/retrain_logs', help='Where to save summary logs for TensorBoard.') parser.add_argument( '--wanted_words', type=str, default='yes,no,up,down,left,right,on,off,stop,go', help='Words to use (others will be added to an unknown label)',) parser.add_argument( '--train_dir', type=str, default='/tmp/speech_commands_train', help='Directory to write event logs and checkpoint.') parser.add_argument( '--save_step_interval', type=int, default=100, help='Save model checkpoint every save_steps.') parser.add_argument( '--start_checkpoint', type=str, default='', help='If specified, restore this pretrained model before any training.') parser.add_argument( '--model_architecture', type=str, default='dnn', help='What model architecture to use') parser.add_argument( '--model_size_info', type=int, nargs="+", default=[128,128,128], help='Model dimensions - different for various models') parser.add_argument( '--check_nans', type=bool, default=False, help='Whether to check for invalid numbers during processing') parser.add_argument("--quant", action='store_true', default=False) parser.add_argument("--bits", type=int, # 只有当quant参数有效的时候这个参数才能生效 default=8) FLAGS, unparsed = parser.parse_known_args() tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
en
0.822123
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # # Modifications Copyright 2017 Arm Inc. All Rights Reserved. # Added model dimensions as command line argument and changed to Adam optimizer # # Simple speech recognition to spot a limited number of keywords. This is a self-contained example script that will train a very basic audio recognition model in TensorFlow. It downloads the necessary training data and runs with reasonable defaults to train within a few hours even only using a CPU. For more information, please see https://www.tensorflow.org/tutorials/audio_recognition. It is intended as an introduction to using neural networks for audio recognition, and is not a full speech recognition system. For more advanced speech systems, I recommend looking into Kaldi. This network uses a keyword detection style to spot discrete words from a small vocabulary, consisting of "yes", "no", "up", "down", "left", "right", "on", "off", "stop", and "go". To run the training process, use: bazel run tensorflow/examples/speech_commands:train This will write out checkpoints to /tmp/speech_commands_train/, and will download over 1GB of open source training data, so you'll need enough free space and a good internet connection. The default data is a collection of thousands of one-second .wav files, each containing one spoken word. This data set is collected from https://aiyprojects.withgoogle.com/open_speech_recording, please consider contributing to help improve this and other models! As training progresses, it will print out its accuracy metrics, which should rise above 90% by the end. Once it's complete, you can run the freeze script to get a binary GraphDef that you can easily deploy on mobile applications. If you want to train on your own data, you'll need to create .wavs with your recordings, all at a consistent length, and then arrange them into subfolders organized by label. For example, here's a possible file structure: my_wavs > up > audio_0.wav audio_1.wav down > audio_2.wav audio_3.wav other> audio_4.wav audio_5.wav You'll also need to tell the script what labels to look for, using the `--wanted_words` argument. In this case, 'up,down' might be what you want, and the audio in the 'other' folder would be used to train an 'unknown' category. To pull this all together, you'd run: bazel run tensorflow/examples/speech_commands:train -- \ --data_dir=my_wavs --wanted_words=up,down # pylint: disable=redefined-builtin # We want to see all the logging messages for this tutorial. # Start a new TensorFlow session. # Begin by making sure we have the training data we need. If you already have # training data of your own, use `--data_url= ` on the command line to avoid # downloading. # print(model_settings['label_count']) # sys.exit(0) # Figure out the learning rates for each training phase. Since it's often # effective to have high learning rates at the start of training, followed by # lower levels towards the end, the number of steps and learning rates can be # specified as comma-separated lists to define the rate at each stage. For # example --how_many_training_steps=10000,3000 --learning_rate=0.001,0.0001 # will run 13,000 training loops in total, with a rate of 0.001 for the first # 10,000, and 0.0001 for the final 3,000. # is_training = tf.placeholder(shape=(), dtype=tf.bool) # Trainable vars has to be collected before adding quant ops. # Define loss and optimizer # Optionally we can add runtime checks to spot when NaNs or other symptoms of # numerical errors start occurring during training. # Now, create dependencies for quantizing weights # train_step = tf.train.GradientDescentOptimizer( # learning_rate_input).minimize(cross_entropy_mean) # Merge all the summaries and write them out to /tmp/retrain_logs (by default) # Parameter counts # Save graph.pbtxt. # Save list of words. # Training loop. # Figure out what the current learning rate is. # Pull the audio samples we'll use for training. # Run the graph with this batch of training data. #%d: rate %f, accuracy %.2f%%, cross entropy %f' % if (training_step % FLAGS.eval_step_interval) == 0 or is_last_step: set_size = audio_processor.set_size('validation') total_accuracy = 0 total_conf_matrix = None for i in xrange(0, set_size, FLAGS.batch_size): validation_fingerprints, validation_ground_truth = ( audio_processor.get_data(FLAGS.batch_size, i, model_settings, 0.0, 0.0, 0, 'validation', sess)) # Run a validation step and capture training summaries for TensorBoard # with the `merged` op. validation_summary, validation_accuracy, conf_matrix = sess.run( [merged_summaries, evaluation_step, confusion_matrix], feed_dict={ fingerprint_input: validation_fingerprints, ground_truth_input: validation_ground_truth, }) validation_writer.add_summary(validation_summary, training_step) batch_size = min(FLAGS.batch_size, set_size - i) total_accuracy += (validation_accuracy * batch_size) / set_size if total_conf_matrix is None: total_conf_matrix = conf_matrix else: total_conf_matrix += conf_matrix tf.logging.info('Confusion Matrix:\n %s' % (total_conf_matrix)) tf.logging.info('Step %d: Validation accuracy = %.2f%% (N=%d)' % (training_step, total_accuracy * 100, set_size)) # Save the model checkpoint when validation accuracy improves if total_accuracy > best_accuracy: best_accuracy = total_accuracy checkpoint_path = os.path.join(FLAGS.train_dir, 'best', FLAGS.model_architecture + '_' + str(int(best_accuracy * 10000)) + '.ckpt') tf.logging.info('Saving best model to "%s-%d"', checkpoint_path, training_step) saver.save(sess, checkpoint_path, global_step=training_step) tf.logging.info('So far the best validation accuracy is %.2f%%' % (best_accuracy * 100)) # pylint: disable=line-too-long # pylint: enable=line-too-long \ Where to download the speech training data to. \ How loud the background noise should be, between 0 and 1. \ How many of the training samples have background noise mixed in. \ How much of the training data should be silence. \ How much of the training data should be unknown words. \ Range to randomly shift the training audio by in time. # 只有当quant参数有效的时候这个参数才能生效
2.429794
2
click2pass/urls.py
iwagaki/click2pass
0
6625837
<filename>click2pass/urls.py from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'click2pass.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^service/$', 'service.views.index'), url(r'^service/add_bookmark/$', 'service.views.add_bookmark'), url(r'^service/delete_bookmark/(?P<objid>\d+)/$', 'service.views.delete_bookmark'), url(r'^service/update_bookmark/(?P<objid>\d+)/$', 'service.views.update_bookmark'), )
<filename>click2pass/urls.py from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'click2pass.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^service/$', 'service.views.index'), url(r'^service/add_bookmark/$', 'service.views.add_bookmark'), url(r'^service/delete_bookmark/(?P<objid>\d+)/$', 'service.views.delete_bookmark'), url(r'^service/update_bookmark/(?P<objid>\d+)/$', 'service.views.update_bookmark'), )
en
0.264136
# Examples: # url(r'^$', 'click2pass.views.home', name='home'), # url(r'^blog/', include('blog.urls')),
1.994119
2
net/net_nacl.gyp
domenic/mojo
5
6625838
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'chromium_code': 1, }, 'includes': [ '../native_client/build/untrusted.gypi', 'net.gypi', ], 'targets': [ { 'target_name': 'net_nacl', 'type': 'none', 'variables': { 'nacl_untrusted_build': 1, 'nlib_target': 'libnet_nacl.a', 'build_glibc': 0, 'build_newlib': 0, 'build_pnacl_newlib': 1, }, 'dependencies': [ '../crypto/crypto_nacl.gyp:crypto_nacl', '../native_client/tools.gyp:prep_toolchain', '../native_client_sdk/native_client_sdk_untrusted.gyp:nacl_io_untrusted', '../third_party/boringssl/boringssl_nacl.gyp:boringssl_nacl', '../url/url_nacl.gyp:url_nacl', 'net.gyp:net_derived_sources', 'net.gyp:net_resources', ], 'defines': [ 'NET_IMPLEMENTATION', ], 'pnacl_compile_flags': [ '-Wno-bind-to-temporary-copy', ], 'sources': [ '<@(net_nacl_common_sources)', ], }, ], }
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'chromium_code': 1, }, 'includes': [ '../native_client/build/untrusted.gypi', 'net.gypi', ], 'targets': [ { 'target_name': 'net_nacl', 'type': 'none', 'variables': { 'nacl_untrusted_build': 1, 'nlib_target': 'libnet_nacl.a', 'build_glibc': 0, 'build_newlib': 0, 'build_pnacl_newlib': 1, }, 'dependencies': [ '../crypto/crypto_nacl.gyp:crypto_nacl', '../native_client/tools.gyp:prep_toolchain', '../native_client_sdk/native_client_sdk_untrusted.gyp:nacl_io_untrusted', '../third_party/boringssl/boringssl_nacl.gyp:boringssl_nacl', '../url/url_nacl.gyp:url_nacl', 'net.gyp:net_derived_sources', 'net.gyp:net_resources', ], 'defines': [ 'NET_IMPLEMENTATION', ], 'pnacl_compile_flags': [ '-Wno-bind-to-temporary-copy', ], 'sources': [ '<@(net_nacl_common_sources)', ], }, ], }
en
0.917765
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file.
1.173097
1
itdagene/core/migrations/0017_remove_user_mail_prefix.py
itdagene-ntnu/itdagene
9
6625839
<reponame>itdagene-ntnu/itdagene<filename>itdagene/core/migrations/0017_remove_user_mail_prefix.py<gh_stars>1-10 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("core", "0016_auto_20141007_2055")] operations = [migrations.RemoveField(model_name="user", name="mail_prefix")]
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("core", "0016_auto_20141007_2055")] operations = [migrations.RemoveField(model_name="user", name="mail_prefix")]
none
1
1.390406
1
tests/vfs/encrypted_stream_file_system.py
Acidburn0zzz/dfvfs
1
6625840
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the encrypted stream file system implementation.""" from __future__ import unicode_literals import unittest from dfvfs.lib import definitions from dfvfs.path import encrypted_stream_path_spec from dfvfs.path import os_path_spec from dfvfs.resolver import context from dfvfs.resolver import resolver from dfvfs.vfs import encrypted_stream_file_system from tests import test_lib as shared_test_lib class EncryptedStreamFileSystemTest(shared_test_lib.BaseTestCase): """Tests the compressed stream file system.""" _RC4_KEY = b'rc4test' def setUp(self): """Sets up the needed objects used throughout the test.""" self._resolver_context = context.Context() test_file = self._GetTestFilePath(['syslog.rc4']) self._SkipIfPathNotExists(test_file) path_spec = os_path_spec.OSPathSpec(location=test_file) self._encrypted_stream_path_spec = ( encrypted_stream_path_spec.EncryptedStreamPathSpec( encryption_method=definitions.ENCRYPTION_METHOD_RC4, parent=path_spec)) resolver.Resolver.key_chain.SetCredential( self._encrypted_stream_path_spec, 'key', self._RC4_KEY) def testOpenAndClose(self): """Test the open and close functionality.""" file_system = encrypted_stream_file_system.EncryptedStreamFileSystem( self._resolver_context) self.assertIsNotNone(file_system) file_system.Open(self._encrypted_stream_path_spec) file_system.Close() def testFileEntryExistsByPathSpec(self): """Test the file entry exists by path specification functionality.""" file_system = encrypted_stream_file_system.EncryptedStreamFileSystem( self._resolver_context) self.assertIsNotNone(file_system) file_system.Open(self._encrypted_stream_path_spec) self.assertTrue(file_system.FileEntryExistsByPathSpec( self._encrypted_stream_path_spec)) file_system.Close() def testGetFileEntryByPathSpec(self): """Tests the GetFileEntryByPathSpec function.""" file_system = encrypted_stream_file_system.EncryptedStreamFileSystem( self._resolver_context) self.assertIsNotNone(file_system) file_system.Open(self._encrypted_stream_path_spec) file_entry = file_system.GetFileEntryByPathSpec( self._encrypted_stream_path_spec) self.assertIsNotNone(file_entry) self.assertEqual(file_entry.name, '') file_system.Close() def testGetRootFileEntry(self): """Test the get root file entry functionality.""" file_system = encrypted_stream_file_system.EncryptedStreamFileSystem( self._resolver_context) self.assertIsNotNone(file_system) file_system.Open(self._encrypted_stream_path_spec) file_entry = file_system.GetRootFileEntry() self.assertIsNotNone(file_entry) self.assertEqual(file_entry.name, '') file_system.Close() if __name__ == '__main__': unittest.main()
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for the encrypted stream file system implementation.""" from __future__ import unicode_literals import unittest from dfvfs.lib import definitions from dfvfs.path import encrypted_stream_path_spec from dfvfs.path import os_path_spec from dfvfs.resolver import context from dfvfs.resolver import resolver from dfvfs.vfs import encrypted_stream_file_system from tests import test_lib as shared_test_lib class EncryptedStreamFileSystemTest(shared_test_lib.BaseTestCase): """Tests the compressed stream file system.""" _RC4_KEY = b'rc4test' def setUp(self): """Sets up the needed objects used throughout the test.""" self._resolver_context = context.Context() test_file = self._GetTestFilePath(['syslog.rc4']) self._SkipIfPathNotExists(test_file) path_spec = os_path_spec.OSPathSpec(location=test_file) self._encrypted_stream_path_spec = ( encrypted_stream_path_spec.EncryptedStreamPathSpec( encryption_method=definitions.ENCRYPTION_METHOD_RC4, parent=path_spec)) resolver.Resolver.key_chain.SetCredential( self._encrypted_stream_path_spec, 'key', self._RC4_KEY) def testOpenAndClose(self): """Test the open and close functionality.""" file_system = encrypted_stream_file_system.EncryptedStreamFileSystem( self._resolver_context) self.assertIsNotNone(file_system) file_system.Open(self._encrypted_stream_path_spec) file_system.Close() def testFileEntryExistsByPathSpec(self): """Test the file entry exists by path specification functionality.""" file_system = encrypted_stream_file_system.EncryptedStreamFileSystem( self._resolver_context) self.assertIsNotNone(file_system) file_system.Open(self._encrypted_stream_path_spec) self.assertTrue(file_system.FileEntryExistsByPathSpec( self._encrypted_stream_path_spec)) file_system.Close() def testGetFileEntryByPathSpec(self): """Tests the GetFileEntryByPathSpec function.""" file_system = encrypted_stream_file_system.EncryptedStreamFileSystem( self._resolver_context) self.assertIsNotNone(file_system) file_system.Open(self._encrypted_stream_path_spec) file_entry = file_system.GetFileEntryByPathSpec( self._encrypted_stream_path_spec) self.assertIsNotNone(file_entry) self.assertEqual(file_entry.name, '') file_system.Close() def testGetRootFileEntry(self): """Test the get root file entry functionality.""" file_system = encrypted_stream_file_system.EncryptedStreamFileSystem( self._resolver_context) self.assertIsNotNone(file_system) file_system.Open(self._encrypted_stream_path_spec) file_entry = file_system.GetRootFileEntry() self.assertIsNotNone(file_entry) self.assertEqual(file_entry.name, '') file_system.Close() if __name__ == '__main__': unittest.main()
en
0.852492
#!/usr/bin/env python # -*- coding: utf-8 -*- Tests for the encrypted stream file system implementation. Tests the compressed stream file system. Sets up the needed objects used throughout the test. Test the open and close functionality. Test the file entry exists by path specification functionality. Tests the GetFileEntryByPathSpec function. Test the get root file entry functionality.
2.393392
2
pyalect/shims.py
rmorshea/pyalect
4
6625841
import ast import sys from traceback import print_exc from typing import Any, List, Optional, Type from .dialect import DialectReducer, dialect_reducer try: from IPython.core.interactiveshell import InteractiveShell from IPython.core.magic import magics_class, Magics, cell_magic except ImportError: pass else: _dialect_reducer_fifo_queue: List[DialectReducer] = [] class DialectNodeTransformer(ast.NodeTransformer): """Node transformer defined to hook into IPython.""" def visit(self, node: ast.AST) -> ast.AST: try: if isinstance(node, ast.Module): first_node = next(ast.iter_child_nodes(node)) if ( isinstance(first_node, ast.Assign) and isinstance(first_node.targets[0], ast.Name) and first_node.targets[0].id == "_DIALECT_" and isinstance(first_node.value, ast.Str) ): node.body.pop(0) node = _dialect_reducer_fifo_queue.pop(0).transform_ast(node) return node except Exception: print_exc(file=sys.stderr) return node else: return node def register_to_ipython_shell(shell: Optional[InteractiveShell] = None) -> None: """Register transpiler hooks to IPython shell.""" shell_inst: InteractiveShell = shell or InteractiveShell.instance() @magics_class class DialectMagics(Magics): # type: ignore def __init__(self, shell: InteractiveShell, **kwargs: Any) -> None: super().__init__(shell, **kwargs) for transformer in shell.ast_transformers: if isinstance(transformer, DialectNodeTransformer): break else: shell.ast_transformers.insert(0, DialectNodeTransformer()) @cell_magic # type: ignore def dialect(self, cell_dialect: str, raw_cell: str) -> None: reducer = dialect_reducer(cell_dialect) _dialect_reducer_fifo_queue.append(reducer) self.shell.run_cell( # We need to prepend this since we can't look for # the dialect comment when transforming the AST. f"_DIALECT_ = {cell_dialect!r}\n" + reducer.transform_src(raw_cell) ) shell_inst.register_magics(DialectMagics) if InteractiveShell.initialized(): register_to_ipython_shell() else: original = InteractiveShell.instance.__func__ def wrapper( cls: Type[InteractiveShell], *args: Any, **kwargs: Any ) -> InteractiveShell: inst = original(cls, *args, **kwargs) register_to_ipython_shell(inst) return inst InteractiveShell.instance = classmethod(wrapper)
import ast import sys from traceback import print_exc from typing import Any, List, Optional, Type from .dialect import DialectReducer, dialect_reducer try: from IPython.core.interactiveshell import InteractiveShell from IPython.core.magic import magics_class, Magics, cell_magic except ImportError: pass else: _dialect_reducer_fifo_queue: List[DialectReducer] = [] class DialectNodeTransformer(ast.NodeTransformer): """Node transformer defined to hook into IPython.""" def visit(self, node: ast.AST) -> ast.AST: try: if isinstance(node, ast.Module): first_node = next(ast.iter_child_nodes(node)) if ( isinstance(first_node, ast.Assign) and isinstance(first_node.targets[0], ast.Name) and first_node.targets[0].id == "_DIALECT_" and isinstance(first_node.value, ast.Str) ): node.body.pop(0) node = _dialect_reducer_fifo_queue.pop(0).transform_ast(node) return node except Exception: print_exc(file=sys.stderr) return node else: return node def register_to_ipython_shell(shell: Optional[InteractiveShell] = None) -> None: """Register transpiler hooks to IPython shell.""" shell_inst: InteractiveShell = shell or InteractiveShell.instance() @magics_class class DialectMagics(Magics): # type: ignore def __init__(self, shell: InteractiveShell, **kwargs: Any) -> None: super().__init__(shell, **kwargs) for transformer in shell.ast_transformers: if isinstance(transformer, DialectNodeTransformer): break else: shell.ast_transformers.insert(0, DialectNodeTransformer()) @cell_magic # type: ignore def dialect(self, cell_dialect: str, raw_cell: str) -> None: reducer = dialect_reducer(cell_dialect) _dialect_reducer_fifo_queue.append(reducer) self.shell.run_cell( # We need to prepend this since we can't look for # the dialect comment when transforming the AST. f"_DIALECT_ = {cell_dialect!r}\n" + reducer.transform_src(raw_cell) ) shell_inst.register_magics(DialectMagics) if InteractiveShell.initialized(): register_to_ipython_shell() else: original = InteractiveShell.instance.__func__ def wrapper( cls: Type[InteractiveShell], *args: Any, **kwargs: Any ) -> InteractiveShell: inst = original(cls, *args, **kwargs) register_to_ipython_shell(inst) return inst InteractiveShell.instance = classmethod(wrapper)
en
0.835855
Node transformer defined to hook into IPython. Register transpiler hooks to IPython shell. # type: ignore # type: ignore # We need to prepend this since we can't look for # the dialect comment when transforming the AST.
2.034158
2
medium/260-Single Number III.py
Davidxswang/leetcode
2
6625842
<reponame>Davidxswang/leetcode """ https://leetcode.com/problems/single-number-iii/ Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. Example: Input: [1,2,1,3,2,5] Output: [3,5] Note: The order of the result is not important. So in the above example, [5, 3] is also correct. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? """ # time complexity: O(n), space complexity: O(1) # the solution is inspired by @zhiqing_xiao in the discussion area. # the key here is to use one bit to separate the nums into two groups and use the xor(n1,n2) to find out the n1 in one group and n2 in the other group. class Solution: def singleNumber(self, nums: List[int]) -> List[int]: if len(nums) == 2: return nums xor = 0 for num in nums: xor ^= num testbit = 1 while testbit & xor == 0: testbit <<= 1 xor_set = xor xor_unset = xor for num in nums: if testbit & num != 0: xor_set ^= num else: xor_unset ^= num return [xor_set, xor_unset]
""" https://leetcode.com/problems/single-number-iii/ Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. Example: Input: [1,2,1,3,2,5] Output: [3,5] Note: The order of the result is not important. So in the above example, [5, 3] is also correct. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? """ # time complexity: O(n), space complexity: O(1) # the solution is inspired by @zhiqing_xiao in the discussion area. # the key here is to use one bit to separate the nums into two groups and use the xor(n1,n2) to find out the n1 in one group and n2 in the other group. class Solution: def singleNumber(self, nums: List[int]) -> List[int]: if len(nums) == 2: return nums xor = 0 for num in nums: xor ^= num testbit = 1 while testbit & xor == 0: testbit <<= 1 xor_set = xor xor_unset = xor for num in nums: if testbit & num != 0: xor_set ^= num else: xor_unset ^= num return [xor_set, xor_unset]
en
0.890938
https://leetcode.com/problems/single-number-iii/ Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. Example: Input: [1,2,1,3,2,5] Output: [3,5] Note: The order of the result is not important. So in the above example, [5, 3] is also correct. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity? # time complexity: O(n), space complexity: O(1) # the solution is inspired by @zhiqing_xiao in the discussion area. # the key here is to use one bit to separate the nums into two groups and use the xor(n1,n2) to find out the n1 in one group and n2 in the other group.
3.899644
4
tests/test_target_space.py
1aut/BayesianOptimization
6,106
6625843
import pytest import numpy as np from bayes_opt.target_space import TargetSpace def target_func(**kwargs): # arbitrary target func return sum(kwargs.values()) PBOUNDS = {'p1': (0, 1), 'p2': (1, 100)} def test_keys_and_bounds_in_same_order(): pbounds = { 'p1': (0, 1), 'p3': (0, 3), 'p2': (0, 2), 'p4': (0, 4), } space = TargetSpace(target_func, pbounds) assert space.dim == len(pbounds) assert space.empty assert space.keys == ["p1", "p2", "p3", "p4"] assert all(space.bounds[:, 0] == np.array([0, 0, 0, 0])) assert all(space.bounds[:, 1] == np.array([1, 2, 3, 4])) def test_params_to_array(): space = TargetSpace(target_func, PBOUNDS) assert all(space.params_to_array({"p1": 2, "p2": 3}) == np.array([2, 3])) assert all(space.params_to_array({"p2": 2, "p1": 9}) == np.array([9, 2])) with pytest.raises(ValueError): space.params_to_array({"p2": 1}) with pytest.raises(ValueError): space.params_to_array({"p2": 1, "p1": 7, "other": 4}) with pytest.raises(ValueError): space.params_to_array({"other": 1}) def test_array_to_params(): space = TargetSpace(target_func, PBOUNDS) assert space.array_to_params(np.array([2, 3])) == {"p1": 2, "p2": 3} with pytest.raises(ValueError): space.array_to_params(np.array([2])) with pytest.raises(ValueError): space.array_to_params(np.array([2, 3, 5])) def test_as_array(): space = TargetSpace(target_func, PBOUNDS) x = space._as_array([0, 1]) assert x.shape == (2,) assert all(x == np.array([0, 1])) x = space._as_array({"p2": 1, "p1": 2}) assert x.shape == (2,) assert all(x == np.array([2, 1])) with pytest.raises(ValueError): x = space._as_array([2, 1, 7]) with pytest.raises(ValueError): x = space._as_array({"p2": 1, "p1": 2, "other": 7}) with pytest.raises(ValueError): x = space._as_array({"p2": 1}) with pytest.raises(ValueError): x = space._as_array({"other": 7}) def test_register(): space = TargetSpace(target_func, PBOUNDS) assert len(space) == 0 # registering with dict space.register(params={"p1": 1, "p2": 2}, target=3) assert len(space) == 1 assert all(space.params[0] == np.array([1, 2])) assert all(space.target == np.array([3])) # registering with array space.register(params={"p1": 5, "p2": 4}, target=9) assert len(space) == 2 assert all(space.params[1] == np.array([5, 4])) assert all(space.target == np.array([3, 9])) with pytest.raises(KeyError): space.register(params={"p1": 1, "p2": 2}, target=3) with pytest.raises(KeyError): space.register(params={"p1": 5, "p2": 4}, target=9) def test_probe(): space = TargetSpace(target_func, PBOUNDS) assert len(space) == 0 # probing with dict space.probe(params={"p1": 1, "p2": 2}) assert len(space) == 1 assert all(space.params[0] == np.array([1, 2])) assert all(space.target == np.array([3])) # probing with array space.probe(np.array([5, 4])) assert len(space) == 2 assert all(space.params[1] == np.array([5, 4])) assert all(space.target == np.array([3, 9])) # probing same point with dict space.probe(params={"p1": 1, "p2": 2}) assert len(space) == 2 assert all(space.params[1] == np.array([5, 4])) assert all(space.target == np.array([3, 9])) # probing same point with array space.probe(np.array([5, 4])) assert len(space) == 2 assert all(space.params[1] == np.array([5, 4])) assert all(space.target == np.array([3, 9])) def test_random_sample(): pbounds = { 'p1': (0, 1), 'p3': (0, 3), 'p2': (0, 2), 'p4': (0, 4), } space = TargetSpace(target_func, pbounds, random_state=8) for _ in range(50): random_sample = space.random_sample() assert len(random_sample) == space.dim assert all(random_sample >= space.bounds[:, 0]) assert all(random_sample <= space.bounds[:, 1]) def test_max(): space = TargetSpace(target_func, PBOUNDS) assert space.max() == {} space.probe(params={"p1": 1, "p2": 2}) space.probe(params={"p1": 5, "p2": 4}) space.probe(params={"p1": 2, "p2": 3}) space.probe(params={"p1": 1, "p2": 6}) assert space.max() == {"params": {"p1": 5, "p2": 4}, "target": 9} def test_res(): space = TargetSpace(target_func, PBOUNDS) assert space.res() == [] space.probe(params={"p1": 1, "p2": 2}) space.probe(params={"p1": 5, "p2": 4}) space.probe(params={"p1": 2, "p2": 3}) space.probe(params={"p1": 1, "p2": 6}) expected_res = [ {"params": {"p1": 1, "p2": 2}, "target": 3}, {"params": {"p1": 5, "p2": 4}, "target": 9}, {"params": {"p1": 2, "p2": 3}, "target": 5}, {"params": {"p1": 1, "p2": 6}, "target": 7}, ] assert len(space.res()) == 4 assert space.res() == expected_res def test_set_bounds(): pbounds = { 'p1': (0, 1), 'p3': (0, 3), 'p2': (0, 2), 'p4': (0, 4), } space = TargetSpace(target_func, pbounds) # Ignore unknown keys space.set_bounds({"other": (7, 8)}) assert all(space.bounds[:, 0] == np.array([0, 0, 0, 0])) assert all(space.bounds[:, 1] == np.array([1, 2, 3, 4])) # Update bounds accordingly space.set_bounds({"p2": (1, 8)}) assert all(space.bounds[:, 0] == np.array([0, 1, 0, 0])) assert all(space.bounds[:, 1] == np.array([1, 8, 3, 4])) if __name__ == '__main__': r""" CommandLine: python tests/test_target_space.py """ pytest.main([__file__])
import pytest import numpy as np from bayes_opt.target_space import TargetSpace def target_func(**kwargs): # arbitrary target func return sum(kwargs.values()) PBOUNDS = {'p1': (0, 1), 'p2': (1, 100)} def test_keys_and_bounds_in_same_order(): pbounds = { 'p1': (0, 1), 'p3': (0, 3), 'p2': (0, 2), 'p4': (0, 4), } space = TargetSpace(target_func, pbounds) assert space.dim == len(pbounds) assert space.empty assert space.keys == ["p1", "p2", "p3", "p4"] assert all(space.bounds[:, 0] == np.array([0, 0, 0, 0])) assert all(space.bounds[:, 1] == np.array([1, 2, 3, 4])) def test_params_to_array(): space = TargetSpace(target_func, PBOUNDS) assert all(space.params_to_array({"p1": 2, "p2": 3}) == np.array([2, 3])) assert all(space.params_to_array({"p2": 2, "p1": 9}) == np.array([9, 2])) with pytest.raises(ValueError): space.params_to_array({"p2": 1}) with pytest.raises(ValueError): space.params_to_array({"p2": 1, "p1": 7, "other": 4}) with pytest.raises(ValueError): space.params_to_array({"other": 1}) def test_array_to_params(): space = TargetSpace(target_func, PBOUNDS) assert space.array_to_params(np.array([2, 3])) == {"p1": 2, "p2": 3} with pytest.raises(ValueError): space.array_to_params(np.array([2])) with pytest.raises(ValueError): space.array_to_params(np.array([2, 3, 5])) def test_as_array(): space = TargetSpace(target_func, PBOUNDS) x = space._as_array([0, 1]) assert x.shape == (2,) assert all(x == np.array([0, 1])) x = space._as_array({"p2": 1, "p1": 2}) assert x.shape == (2,) assert all(x == np.array([2, 1])) with pytest.raises(ValueError): x = space._as_array([2, 1, 7]) with pytest.raises(ValueError): x = space._as_array({"p2": 1, "p1": 2, "other": 7}) with pytest.raises(ValueError): x = space._as_array({"p2": 1}) with pytest.raises(ValueError): x = space._as_array({"other": 7}) def test_register(): space = TargetSpace(target_func, PBOUNDS) assert len(space) == 0 # registering with dict space.register(params={"p1": 1, "p2": 2}, target=3) assert len(space) == 1 assert all(space.params[0] == np.array([1, 2])) assert all(space.target == np.array([3])) # registering with array space.register(params={"p1": 5, "p2": 4}, target=9) assert len(space) == 2 assert all(space.params[1] == np.array([5, 4])) assert all(space.target == np.array([3, 9])) with pytest.raises(KeyError): space.register(params={"p1": 1, "p2": 2}, target=3) with pytest.raises(KeyError): space.register(params={"p1": 5, "p2": 4}, target=9) def test_probe(): space = TargetSpace(target_func, PBOUNDS) assert len(space) == 0 # probing with dict space.probe(params={"p1": 1, "p2": 2}) assert len(space) == 1 assert all(space.params[0] == np.array([1, 2])) assert all(space.target == np.array([3])) # probing with array space.probe(np.array([5, 4])) assert len(space) == 2 assert all(space.params[1] == np.array([5, 4])) assert all(space.target == np.array([3, 9])) # probing same point with dict space.probe(params={"p1": 1, "p2": 2}) assert len(space) == 2 assert all(space.params[1] == np.array([5, 4])) assert all(space.target == np.array([3, 9])) # probing same point with array space.probe(np.array([5, 4])) assert len(space) == 2 assert all(space.params[1] == np.array([5, 4])) assert all(space.target == np.array([3, 9])) def test_random_sample(): pbounds = { 'p1': (0, 1), 'p3': (0, 3), 'p2': (0, 2), 'p4': (0, 4), } space = TargetSpace(target_func, pbounds, random_state=8) for _ in range(50): random_sample = space.random_sample() assert len(random_sample) == space.dim assert all(random_sample >= space.bounds[:, 0]) assert all(random_sample <= space.bounds[:, 1]) def test_max(): space = TargetSpace(target_func, PBOUNDS) assert space.max() == {} space.probe(params={"p1": 1, "p2": 2}) space.probe(params={"p1": 5, "p2": 4}) space.probe(params={"p1": 2, "p2": 3}) space.probe(params={"p1": 1, "p2": 6}) assert space.max() == {"params": {"p1": 5, "p2": 4}, "target": 9} def test_res(): space = TargetSpace(target_func, PBOUNDS) assert space.res() == [] space.probe(params={"p1": 1, "p2": 2}) space.probe(params={"p1": 5, "p2": 4}) space.probe(params={"p1": 2, "p2": 3}) space.probe(params={"p1": 1, "p2": 6}) expected_res = [ {"params": {"p1": 1, "p2": 2}, "target": 3}, {"params": {"p1": 5, "p2": 4}, "target": 9}, {"params": {"p1": 2, "p2": 3}, "target": 5}, {"params": {"p1": 1, "p2": 6}, "target": 7}, ] assert len(space.res()) == 4 assert space.res() == expected_res def test_set_bounds(): pbounds = { 'p1': (0, 1), 'p3': (0, 3), 'p2': (0, 2), 'p4': (0, 4), } space = TargetSpace(target_func, pbounds) # Ignore unknown keys space.set_bounds({"other": (7, 8)}) assert all(space.bounds[:, 0] == np.array([0, 0, 0, 0])) assert all(space.bounds[:, 1] == np.array([1, 2, 3, 4])) # Update bounds accordingly space.set_bounds({"p2": (1, 8)}) assert all(space.bounds[:, 0] == np.array([0, 1, 0, 0])) assert all(space.bounds[:, 1] == np.array([1, 8, 3, 4])) if __name__ == '__main__': r""" CommandLine: python tests/test_target_space.py """ pytest.main([__file__])
en
0.734463
# arbitrary target func # registering with dict # registering with array # probing with dict # probing with array # probing same point with dict # probing same point with array # Ignore unknown keys # Update bounds accordingly CommandLine: python tests/test_target_space.py
2.173089
2
wevote_functions/tests.py
adborden/WeVoteBase
0
6625844
<reponame>adborden/WeVoteBase # wevote_functions/tests.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- from django.test import TestCase # Create your tests here.
# wevote_functions/tests.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- from django.test import TestCase # Create your tests here.
en
0.841974
# wevote_functions/tests.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- # Create your tests here.
1.233027
1
nova/api/openstack/compute/plugins/v3/instance_actions.py
bopopescu/nova-master
3
6625845
<reponame>bopopescu/nova-master<filename>nova/api/openstack/compute/plugins/v3/instance_actions.py<gh_stars>1-10 # Copyright 2013 Rackspace Hosting # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from webob import exc from nova.api.openstack import common from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova import compute from nova.openstack.common.gettextutils import _ ALIAS = "os-instance-actions" authorize_actions = extensions.extension_authorizer('compute', 'v3:' + ALIAS) authorize_events = extensions.soft_extension_authorizer('compute', 'v3:' + ALIAS + ':events') ACTION_KEYS = ['action', 'instance_uuid', 'request_id', 'user_id', 'project_id', 'start_time', 'message'] EVENT_KEYS = ['event', 'start_time', 'finish_time', 'result', 'traceback'] class InstanceActionsController(wsgi.Controller): def __init__(self): super(InstanceActionsController, self).__init__() self.compute_api = compute.API() self.action_api = compute.InstanceActionAPI() def _format_action(self, action_raw): action = {} for key in ACTION_KEYS: action[key] = action_raw.get(key) return action def _format_event(self, event_raw): event = {} for key in EVENT_KEYS: event[key] = event_raw.get(key) return event @extensions.expected_errors(404) def index(self, req, server_id): """Returns the list of actions recorded for a given instance.""" context = req.environ["nova.context"] instance = common.get_instance(self.compute_api, context, server_id) authorize_actions(context, target=instance) actions_raw = self.action_api.actions_get(context, instance) actions = [self._format_action(action) for action in actions_raw] return {'instance_actions': actions} @extensions.expected_errors(404) def show(self, req, server_id, id): """Return data about the given instance action.""" context = req.environ['nova.context'] instance = common.get_instance(self.compute_api, context, server_id) authorize_actions(context, target=instance) action = self.action_api.action_get_by_request_id(context, instance, id) if action is None: msg = _("Action %s not found") % id raise exc.HTTPNotFound(msg) action_id = action['id'] action = self._format_action(action) if authorize_events(context): events_raw = self.action_api.action_events_get(context, instance, action_id) action['events'] = [self._format_event(evt) for evt in events_raw] return {'instance_action': action} class InstanceActions(extensions.V3APIExtensionBase): """View a log of actions and events taken on an instance.""" name = "InstanceActions" alias = ALIAS version = 1 def get_resources(self): ext = extensions.ResourceExtension('os-instance-actions', InstanceActionsController(), parent=dict( member_name='server', collection_name='servers')) return [ext] def get_controller_extensions(self): """It's an abstract function V3APIExtensionBase and the extension will not be loaded without it. """ return []
# Copyright 2013 Rackspace Hosting # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from webob import exc from nova.api.openstack import common from nova.api.openstack import extensions from nova.api.openstack import wsgi from nova import compute from nova.openstack.common.gettextutils import _ ALIAS = "os-instance-actions" authorize_actions = extensions.extension_authorizer('compute', 'v3:' + ALIAS) authorize_events = extensions.soft_extension_authorizer('compute', 'v3:' + ALIAS + ':events') ACTION_KEYS = ['action', 'instance_uuid', 'request_id', 'user_id', 'project_id', 'start_time', 'message'] EVENT_KEYS = ['event', 'start_time', 'finish_time', 'result', 'traceback'] class InstanceActionsController(wsgi.Controller): def __init__(self): super(InstanceActionsController, self).__init__() self.compute_api = compute.API() self.action_api = compute.InstanceActionAPI() def _format_action(self, action_raw): action = {} for key in ACTION_KEYS: action[key] = action_raw.get(key) return action def _format_event(self, event_raw): event = {} for key in EVENT_KEYS: event[key] = event_raw.get(key) return event @extensions.expected_errors(404) def index(self, req, server_id): """Returns the list of actions recorded for a given instance.""" context = req.environ["nova.context"] instance = common.get_instance(self.compute_api, context, server_id) authorize_actions(context, target=instance) actions_raw = self.action_api.actions_get(context, instance) actions = [self._format_action(action) for action in actions_raw] return {'instance_actions': actions} @extensions.expected_errors(404) def show(self, req, server_id, id): """Return data about the given instance action.""" context = req.environ['nova.context'] instance = common.get_instance(self.compute_api, context, server_id) authorize_actions(context, target=instance) action = self.action_api.action_get_by_request_id(context, instance, id) if action is None: msg = _("Action %s not found") % id raise exc.HTTPNotFound(msg) action_id = action['id'] action = self._format_action(action) if authorize_events(context): events_raw = self.action_api.action_events_get(context, instance, action_id) action['events'] = [self._format_event(evt) for evt in events_raw] return {'instance_action': action} class InstanceActions(extensions.V3APIExtensionBase): """View a log of actions and events taken on an instance.""" name = "InstanceActions" alias = ALIAS version = 1 def get_resources(self): ext = extensions.ResourceExtension('os-instance-actions', InstanceActionsController(), parent=dict( member_name='server', collection_name='servers')) return [ext] def get_controller_extensions(self): """It's an abstract function V3APIExtensionBase and the extension will not be loaded without it. """ return []
en
0.860044
# Copyright 2013 Rackspace Hosting # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. Returns the list of actions recorded for a given instance. Return data about the given instance action. View a log of actions and events taken on an instance. It's an abstract function V3APIExtensionBase and the extension will not be loaded without it.
1.734924
2
src/euler_python_package/euler_python/medium/p318.py
wilsonify/euler
0
6625846
def problem318(): pass
def problem318(): pass
none
1
0.875471
1
nodular_JJ/finite_sc/Vj scan/E_Vj.py
tbcole/majoranaJJ
0
6625847
<reponame>tbcole/majoranaJJ<filename>nodular_JJ/finite_sc/Vj scan/E_Vj.py<gh_stars>0 import sys import os import numpy as np import gc import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.patches as patches import scipy.sparse as sparse import scipy.linalg as LA import scipy.sparse.linalg as spLA import majoranaJJ.operators.sparse.qmsops as spop #sparse operators import majoranaJJ.lattice.nbrs as nb #neighbor arrays import majoranaJJ.lattice.shapes as shps #lattice shapes import majoranaJJ.modules.plots as plots #plotting functions from majoranaJJ.operators.sparse.potentials import Vjj #potential JJ dir = os.getcwd() ################################################### #Defining System Nx = 20 #Number of lattice sites along x-direction Ny = 408 #Number of lattice sites along y-direction ax = 50 #lattice spacing in x-direction: [A] ay = 50 #lattice spacing in y-direction: [A] Wj = 11 #Junction region cutx = 0 #width of nodule cuty = 0 #height of nodule Junc_width = Wj*ay*.1 #nm SC_width = ((Ny - Wj)*ay*.10)/2 #nm Nod_widthx = cutx*ax*.1 #nm Nod_widthy = cuty*ay*.1 #nm print("Nodule Width in x-direction = ", Nod_widthx, "(nm)") print("Nodule Width in y-direction = ", Nod_widthy, "(nm)") print("Junction Width = ", Junc_width, "(nm)") print("Supercondicting Lead Width = ", SC_width, "(nm)") ################################################### coor = shps.square(Nx, Ny) #square lattice NN = nb.NN_Arr(coor) #neighbor array NNb = nb.Bound_Arr(coor) #boundary array lat_size = coor.shape[0] Lx = (max(coor[:, 0]) - min(coor[:, 0]) + 1)*ax #Unit cell size in x-direction Ly = (max(coor[:, 1]) - min(coor[:, 1]) + 1)*ay #Unit cell size in y-direction print("Lattice size in x-direction", Lx*.1, "(nm)") print("Lattice size in y-direction", Ly*.1, "(nm)") ################################################### #Hamiltonian Parameters alpha = 100 #Spin-Orbit Coupling constant: [meV*A] gx = 0 #parallel to junction: [meV] gz = 0 #normal to plane of junction: [meV] delta = 1.0 #Superconducting Gap: [meV] Vsc = -30 #Amplitude of potential: [meV] V = Vjj(coor, Wj = Wj, Vsc = Vsc, Vj = 0, cutx = cutx, cuty = cuty) ##################################### k = 44 #This is the number of eigenvalues and eigenvectors you want v_steps = 500 #Number of kx values that are evaluated v_i = -100 v_f = -50 Vj = np.linspace(v_i, v_f, v_steps) #Chemical Potential: [meV] bands = np.zeros((v_steps, k)) cmap = cm.get_cmap('Oranges') dirS = 'e_mu_data' if not os.path.exists(dirS): os.makedirs(dirS) try: PLOT = str(sys.argv[1]) except: PLOT = 'F' if PLOT != 'P': for j in range(v_steps): V = Vjj(coor, Wj = Wj, Vsc = Vsc, Vj = Vj[j], cutx = cutx, cuty = cuty) print(v_steps - j) H = spop.HBDG(coor, ax, ay, NN, NNb=NNb, Wj=Wj, cutx=cutx, cuty=cuty, V=V, mu=0, alpha=alpha, delta=delta, phi=0, qx=0, periodicX=True) eigs, vecs = spLA.eigsh(H, k=k, sigma=0, which='LM') idx_sort = np.argsort(eigs) eigs = eigs[idx_sort] bands[j, :] = eigs np.save("%s/bands Lx = %.1f Ly = %.1f Wsc = %.1f Wj = %.1f nodx = %.1f nody = %.1f alpha = %.1f delta = %.2f v_i = %.1f v_f = %.1f.npy" % (dirS, Lx*.1, Ly*.1, SC_width, Junc_width, Nod_widthx, Nod_widthy, alpha, delta, v_i, v_f), bands) np.save("%s/V0 Lx = %.1f Ly = %.1f Wsc = %.1f Wj = %.1f nodx = %.1f nody = %.1f alpha = %.1f delta = %.2f v_i = %.1f v_f = %.1f.npy" % (dirS, Lx*.1, Ly*.1, SC_width, Junc_width, Nod_widthx, Nod_widthy, alpha, delta, v_i, v_f), Vj) else: bands = np.load("%s/bands Lx = %.1f Ly = %.1f Wsc = %.1f Wj = %.1f nodx = %.1f nody = %.1f alpha = %.1f delta = %.2f v_i = %.1f v_f = %.1f.npy" % (dirS, Lx*.1, Ly*.1, SC_width, Junc_width, Nod_widthx, Nod_widthy, alpha, delta, v_i, v_f)) mu = np.load("%s/V0 Lx = %.1f Ly = %.1f Wsc = %.1f Wj = %.1f nodx = %.1f nody = %.1f alpha = %.1f delta = %.2f v_i = %.1f v_f = %.1f.npy" % (dirS, Lx*.1, Ly*.1, SC_width, Junc_width, Nod_widthx, Nod_widthy, alpha, delta, v_i, v_f)) fig = plt.figure() for j in range(bands.shape[1]): plt.plot(Vj, bands[:, j], c='r') plt.xlabel(r"$V_{j}$ (meV)") plt.ylabel("E (meV)") plt.title(r"Lx = %.1f nm, Ly = %.1f nm, $\Delta$ = %.2f meV, $\alpha$ = %.2f meV A, $W_{sc}$ = %.1f nm, $W_J$ = %.1f nm, $Nodule_x$ = %.1f nm, $Nodule_y$ = %.1f nm" % (Lx*.1, Ly*.1, delta, alpha, SC_width, Junc_width, Nod_widthx, Nod_widthy), loc = 'center', wrap=True) plt.ylim(-1.5, 1.5) plt.subplots_adjust(top=0.85) plt.savefig("nodx={} nody={}.png".format(Nod_widthx, Nod_widthy)) plt.show()
scan/E_Vj.py<gh_stars>0 import sys import os import numpy as np import gc import matplotlib.pyplot as plt import matplotlib.cm as cm import matplotlib.patches as patches import scipy.sparse as sparse import scipy.linalg as LA import scipy.sparse.linalg as spLA import majoranaJJ.operators.sparse.qmsops as spop #sparse operators import majoranaJJ.lattice.nbrs as nb #neighbor arrays import majoranaJJ.lattice.shapes as shps #lattice shapes import majoranaJJ.modules.plots as plots #plotting functions from majoranaJJ.operators.sparse.potentials import Vjj #potential JJ dir = os.getcwd() ################################################### #Defining System Nx = 20 #Number of lattice sites along x-direction Ny = 408 #Number of lattice sites along y-direction ax = 50 #lattice spacing in x-direction: [A] ay = 50 #lattice spacing in y-direction: [A] Wj = 11 #Junction region cutx = 0 #width of nodule cuty = 0 #height of nodule Junc_width = Wj*ay*.1 #nm SC_width = ((Ny - Wj)*ay*.10)/2 #nm Nod_widthx = cutx*ax*.1 #nm Nod_widthy = cuty*ay*.1 #nm print("Nodule Width in x-direction = ", Nod_widthx, "(nm)") print("Nodule Width in y-direction = ", Nod_widthy, "(nm)") print("Junction Width = ", Junc_width, "(nm)") print("Supercondicting Lead Width = ", SC_width, "(nm)") ################################################### coor = shps.square(Nx, Ny) #square lattice NN = nb.NN_Arr(coor) #neighbor array NNb = nb.Bound_Arr(coor) #boundary array lat_size = coor.shape[0] Lx = (max(coor[:, 0]) - min(coor[:, 0]) + 1)*ax #Unit cell size in x-direction Ly = (max(coor[:, 1]) - min(coor[:, 1]) + 1)*ay #Unit cell size in y-direction print("Lattice size in x-direction", Lx*.1, "(nm)") print("Lattice size in y-direction", Ly*.1, "(nm)") ################################################### #Hamiltonian Parameters alpha = 100 #Spin-Orbit Coupling constant: [meV*A] gx = 0 #parallel to junction: [meV] gz = 0 #normal to plane of junction: [meV] delta = 1.0 #Superconducting Gap: [meV] Vsc = -30 #Amplitude of potential: [meV] V = Vjj(coor, Wj = Wj, Vsc = Vsc, Vj = 0, cutx = cutx, cuty = cuty) ##################################### k = 44 #This is the number of eigenvalues and eigenvectors you want v_steps = 500 #Number of kx values that are evaluated v_i = -100 v_f = -50 Vj = np.linspace(v_i, v_f, v_steps) #Chemical Potential: [meV] bands = np.zeros((v_steps, k)) cmap = cm.get_cmap('Oranges') dirS = 'e_mu_data' if not os.path.exists(dirS): os.makedirs(dirS) try: PLOT = str(sys.argv[1]) except: PLOT = 'F' if PLOT != 'P': for j in range(v_steps): V = Vjj(coor, Wj = Wj, Vsc = Vsc, Vj = Vj[j], cutx = cutx, cuty = cuty) print(v_steps - j) H = spop.HBDG(coor, ax, ay, NN, NNb=NNb, Wj=Wj, cutx=cutx, cuty=cuty, V=V, mu=0, alpha=alpha, delta=delta, phi=0, qx=0, periodicX=True) eigs, vecs = spLA.eigsh(H, k=k, sigma=0, which='LM') idx_sort = np.argsort(eigs) eigs = eigs[idx_sort] bands[j, :] = eigs np.save("%s/bands Lx = %.1f Ly = %.1f Wsc = %.1f Wj = %.1f nodx = %.1f nody = %.1f alpha = %.1f delta = %.2f v_i = %.1f v_f = %.1f.npy" % (dirS, Lx*.1, Ly*.1, SC_width, Junc_width, Nod_widthx, Nod_widthy, alpha, delta, v_i, v_f), bands) np.save("%s/V0 Lx = %.1f Ly = %.1f Wsc = %.1f Wj = %.1f nodx = %.1f nody = %.1f alpha = %.1f delta = %.2f v_i = %.1f v_f = %.1f.npy" % (dirS, Lx*.1, Ly*.1, SC_width, Junc_width, Nod_widthx, Nod_widthy, alpha, delta, v_i, v_f), Vj) else: bands = np.load("%s/bands Lx = %.1f Ly = %.1f Wsc = %.1f Wj = %.1f nodx = %.1f nody = %.1f alpha = %.1f delta = %.2f v_i = %.1f v_f = %.1f.npy" % (dirS, Lx*.1, Ly*.1, SC_width, Junc_width, Nod_widthx, Nod_widthy, alpha, delta, v_i, v_f)) mu = np.load("%s/V0 Lx = %.1f Ly = %.1f Wsc = %.1f Wj = %.1f nodx = %.1f nody = %.1f alpha = %.1f delta = %.2f v_i = %.1f v_f = %.1f.npy" % (dirS, Lx*.1, Ly*.1, SC_width, Junc_width, Nod_widthx, Nod_widthy, alpha, delta, v_i, v_f)) fig = plt.figure() for j in range(bands.shape[1]): plt.plot(Vj, bands[:, j], c='r') plt.xlabel(r"$V_{j}$ (meV)") plt.ylabel("E (meV)") plt.title(r"Lx = %.1f nm, Ly = %.1f nm, $\Delta$ = %.2f meV, $\alpha$ = %.2f meV A, $W_{sc}$ = %.1f nm, $W_J$ = %.1f nm, $Nodule_x$ = %.1f nm, $Nodule_y$ = %.1f nm" % (Lx*.1, Ly*.1, delta, alpha, SC_width, Junc_width, Nod_widthx, Nod_widthy), loc = 'center', wrap=True) plt.ylim(-1.5, 1.5) plt.subplots_adjust(top=0.85) plt.savefig("nodx={} nody={}.png".format(Nod_widthx, Nod_widthy)) plt.show()
en
0.509114
#sparse operators #neighbor arrays #lattice shapes #plotting functions #potential JJ ################################################### #Defining System #Number of lattice sites along x-direction #Number of lattice sites along y-direction #lattice spacing in x-direction: [A] #lattice spacing in y-direction: [A] #Junction region #width of nodule #height of nodule #nm #nm #nm #nm ################################################### #square lattice #neighbor array #boundary array #Unit cell size in x-direction #Unit cell size in y-direction ################################################### #Hamiltonian Parameters #Spin-Orbit Coupling constant: [meV*A] #parallel to junction: [meV] #normal to plane of junction: [meV] #Superconducting Gap: [meV] #Amplitude of potential: [meV] ##################################### #This is the number of eigenvalues and eigenvectors you want #Number of kx values that are evaluated #Chemical Potential: [meV]
2.245164
2
congress/api/row_model.py
poobalan-arumugam/congress
0
6625848
# Copyright (c) 2014 VMware, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from __future__ import print_function from __future__ import division from __future__ import absolute_import from oslo_log import log as logging from congress.api import api_utils from congress.api import base from congress.api import webservice from congress import exception LOG = logging.getLogger(__name__) class RowModel(base.APIModel): """Model for handling API requests about Rows.""" # TODO(thinrichs): No rows have IDs right now. Maybe eventually # could make ID the hash of the row, but then might as well # just make the ID a string repr of the row. No use case # for it as of now since all rows are read-only. # def get_item(self, id_, context=None): # """Retrieve item with id id\_ from model. # Args: # id_: The ID of the item to retrieve # context: Key-values providing frame of reference of request # Returns: # The matching item or None if item with id\_ does not exist. # """ # Note(thread-safety): blocking function def get_items(self, params, context=None): """Get items in model. :param: params: A dict-like object containing parameters from the request query string and body. :param: context: Key-values providing frame of reference of request :returns: A dict containing at least a 'results' key whose value is a list of items in the model. Additional keys set in the dict will also be rendered for the user. """ LOG.info("get_items(context=%s)", context) gen_trace = False if 'trace' in params and params['trace'].lower() == 'true': gen_trace = True # Get the caller, it should be either policy or datasource # Note(thread-safety): blocking call caller, source_id = api_utils.get_id_from_context(context) # FIXME(threod-safety): in DSE2, the returned caller can be a # datasource name. But the datasource name may now refer to a new, # unrelated datasource. Causing the rest of this code to operate on # an unintended datasource. # It would have saved us if table_id was an UUID rather than a name, # but it appears that table_id is just another word for tablename. # Fix: check UUID of datasource before operating. Abort if mismatch table_id = context['table_id'] try: args = {'table_id': table_id, 'source_id': source_id, 'trace': gen_trace} if caller is base.ENGINE_SERVICE_ID: # allow extra time for row policy engine query # Note(thread-safety): blocking call result = self.invoke_rpc( caller, 'get_row_data', args, timeout=self.dse_long_timeout) else: # Note(thread-safety): blocking call result = self.invoke_rpc(caller, 'get_row_data', args) except exception.CongressException as e: m = ("Error occurred while processing source_id '%s' for row " "data of the table '%s'" % (source_id, table_id)) LOG.exception(m) raise webservice.DataModelException.create(e) if gen_trace and caller is base.ENGINE_SERVICE_ID: # DSE2 returns lists instead of tuples, so correct that. results = [{'data': tuple(x['data'])} for x in result[0]] return {'results': results, 'trace': result[1] or "Not available"} else: result = [{'data': tuple(x['data'])} for x in result] return {'results': result} # Note(thread-safety): blocking function def replace_items(self, items, params, context=None): """Replaces all data in a table. :param: id\_: A table id for replacing all row :param: items: A data for new rows :param: params: A dict-like object containing parameters from request query :param: context: Key-values providing frame of reference of request :returns: None :raises KeyError: table id doesn't exist :raises DataModelException: any error occurs during replacing rows. """ LOG.info("replace_items(context=%s)", context) # Note(thread-safety): blocking call caller, source_id = api_utils.get_id_from_context(context) # FIXME(threod-safety): in DSE2, the returned caller can be a # datasource name. But the datasource name may now refer to a new, # unrelated datasource. Causing the rest of this code to operate on # an unintended datasource. # It would have saved us if table_id was an UUID rather than a name, # but it appears that table_id is just another word for tablename. # Fix: check UUID of datasource before operating. Abort if mismatch table_id = context['table_id'] try: args = {'table_id': table_id, 'source_id': source_id, 'objs': items} # Note(thread-safety): blocking call self.invoke_rpc(caller, 'replace_entire_table_data', args) except exception.CongressException as e: LOG.exception("Error occurred while processing updating rows " "for source_id '%s' and table_id '%s'", source_id, table_id) raise webservice.DataModelException.create(e) LOG.info("finish replace_items(context=%s)", context) LOG.debug("replaced table %s with row items: %s", table_id, str(items)) # TODO(thinrichs): It makes sense to sometimes allow users to create # a new row for internal data sources. But since we don't have # those yet all tuples are read-only from the API. # def add_item(self, item, id_=None, context=None): # """Add item to model. # Args: # item: The item to add to the model # id_: The ID of the item, or None if an ID should be generated # context: Key-values providing frame of reference of request # Returns: # Tuple of (ID, newly_created_item) # Raises: # KeyError: ID already exists. # """ # TODO(thinrichs): once we have internal data sources, # add the ability to update a row. (Or maybe not and implement # via add+delete.) # def update_item(self, id_, item, context=None): # """Update item with id\_ with new data. # Args: # id_: The ID of the item to be updated # item: The new item # context: Key-values providing frame of reference of request # Returns: # The updated item. # Raises: # KeyError: Item with specified id\_ not present. # """ # # currently a noop since the owner_id cannot be changed # if id_ not in self.items: # raise KeyError("Cannot update item with ID '%s': " # "ID does not exist") # return item # TODO(thinrichs): once we can create, we should be able to delete # def delete_item(self, id_, context=None): # """Remove item from model. # Args: # id_: The ID of the item to be removed # context: Key-values providing frame of reference of request # Returns: # The removed item. # Raises: # KeyError: Item with specified id\_ not present. # """
# Copyright (c) 2014 VMware, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from __future__ import print_function from __future__ import division from __future__ import absolute_import from oslo_log import log as logging from congress.api import api_utils from congress.api import base from congress.api import webservice from congress import exception LOG = logging.getLogger(__name__) class RowModel(base.APIModel): """Model for handling API requests about Rows.""" # TODO(thinrichs): No rows have IDs right now. Maybe eventually # could make ID the hash of the row, but then might as well # just make the ID a string repr of the row. No use case # for it as of now since all rows are read-only. # def get_item(self, id_, context=None): # """Retrieve item with id id\_ from model. # Args: # id_: The ID of the item to retrieve # context: Key-values providing frame of reference of request # Returns: # The matching item or None if item with id\_ does not exist. # """ # Note(thread-safety): blocking function def get_items(self, params, context=None): """Get items in model. :param: params: A dict-like object containing parameters from the request query string and body. :param: context: Key-values providing frame of reference of request :returns: A dict containing at least a 'results' key whose value is a list of items in the model. Additional keys set in the dict will also be rendered for the user. """ LOG.info("get_items(context=%s)", context) gen_trace = False if 'trace' in params and params['trace'].lower() == 'true': gen_trace = True # Get the caller, it should be either policy or datasource # Note(thread-safety): blocking call caller, source_id = api_utils.get_id_from_context(context) # FIXME(threod-safety): in DSE2, the returned caller can be a # datasource name. But the datasource name may now refer to a new, # unrelated datasource. Causing the rest of this code to operate on # an unintended datasource. # It would have saved us if table_id was an UUID rather than a name, # but it appears that table_id is just another word for tablename. # Fix: check UUID of datasource before operating. Abort if mismatch table_id = context['table_id'] try: args = {'table_id': table_id, 'source_id': source_id, 'trace': gen_trace} if caller is base.ENGINE_SERVICE_ID: # allow extra time for row policy engine query # Note(thread-safety): blocking call result = self.invoke_rpc( caller, 'get_row_data', args, timeout=self.dse_long_timeout) else: # Note(thread-safety): blocking call result = self.invoke_rpc(caller, 'get_row_data', args) except exception.CongressException as e: m = ("Error occurred while processing source_id '%s' for row " "data of the table '%s'" % (source_id, table_id)) LOG.exception(m) raise webservice.DataModelException.create(e) if gen_trace and caller is base.ENGINE_SERVICE_ID: # DSE2 returns lists instead of tuples, so correct that. results = [{'data': tuple(x['data'])} for x in result[0]] return {'results': results, 'trace': result[1] or "Not available"} else: result = [{'data': tuple(x['data'])} for x in result] return {'results': result} # Note(thread-safety): blocking function def replace_items(self, items, params, context=None): """Replaces all data in a table. :param: id\_: A table id for replacing all row :param: items: A data for new rows :param: params: A dict-like object containing parameters from request query :param: context: Key-values providing frame of reference of request :returns: None :raises KeyError: table id doesn't exist :raises DataModelException: any error occurs during replacing rows. """ LOG.info("replace_items(context=%s)", context) # Note(thread-safety): blocking call caller, source_id = api_utils.get_id_from_context(context) # FIXME(threod-safety): in DSE2, the returned caller can be a # datasource name. But the datasource name may now refer to a new, # unrelated datasource. Causing the rest of this code to operate on # an unintended datasource. # It would have saved us if table_id was an UUID rather than a name, # but it appears that table_id is just another word for tablename. # Fix: check UUID of datasource before operating. Abort if mismatch table_id = context['table_id'] try: args = {'table_id': table_id, 'source_id': source_id, 'objs': items} # Note(thread-safety): blocking call self.invoke_rpc(caller, 'replace_entire_table_data', args) except exception.CongressException as e: LOG.exception("Error occurred while processing updating rows " "for source_id '%s' and table_id '%s'", source_id, table_id) raise webservice.DataModelException.create(e) LOG.info("finish replace_items(context=%s)", context) LOG.debug("replaced table %s with row items: %s", table_id, str(items)) # TODO(thinrichs): It makes sense to sometimes allow users to create # a new row for internal data sources. But since we don't have # those yet all tuples are read-only from the API. # def add_item(self, item, id_=None, context=None): # """Add item to model. # Args: # item: The item to add to the model # id_: The ID of the item, or None if an ID should be generated # context: Key-values providing frame of reference of request # Returns: # Tuple of (ID, newly_created_item) # Raises: # KeyError: ID already exists. # """ # TODO(thinrichs): once we have internal data sources, # add the ability to update a row. (Or maybe not and implement # via add+delete.) # def update_item(self, id_, item, context=None): # """Update item with id\_ with new data. # Args: # id_: The ID of the item to be updated # item: The new item # context: Key-values providing frame of reference of request # Returns: # The updated item. # Raises: # KeyError: Item with specified id\_ not present. # """ # # currently a noop since the owner_id cannot be changed # if id_ not in self.items: # raise KeyError("Cannot update item with ID '%s': " # "ID does not exist") # return item # TODO(thinrichs): once we can create, we should be able to delete # def delete_item(self, id_, context=None): # """Remove item from model. # Args: # id_: The ID of the item to be removed # context: Key-values providing frame of reference of request # Returns: # The removed item. # Raises: # KeyError: Item with specified id\_ not present. # """
en
0.802917
# Copyright (c) 2014 VMware, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # Model for handling API requests about Rows. # TODO(thinrichs): No rows have IDs right now. Maybe eventually # could make ID the hash of the row, but then might as well # just make the ID a string repr of the row. No use case # for it as of now since all rows are read-only. # def get_item(self, id_, context=None): # """Retrieve item with id id\_ from model. # Args: # id_: The ID of the item to retrieve # context: Key-values providing frame of reference of request # Returns: # The matching item or None if item with id\_ does not exist. # """ # Note(thread-safety): blocking function Get items in model. :param: params: A dict-like object containing parameters from the request query string and body. :param: context: Key-values providing frame of reference of request :returns: A dict containing at least a 'results' key whose value is a list of items in the model. Additional keys set in the dict will also be rendered for the user. # Get the caller, it should be either policy or datasource # Note(thread-safety): blocking call # FIXME(threod-safety): in DSE2, the returned caller can be a # datasource name. But the datasource name may now refer to a new, # unrelated datasource. Causing the rest of this code to operate on # an unintended datasource. # It would have saved us if table_id was an UUID rather than a name, # but it appears that table_id is just another word for tablename. # Fix: check UUID of datasource before operating. Abort if mismatch # allow extra time for row policy engine query # Note(thread-safety): blocking call # Note(thread-safety): blocking call # DSE2 returns lists instead of tuples, so correct that. # Note(thread-safety): blocking function Replaces all data in a table. :param: id\_: A table id for replacing all row :param: items: A data for new rows :param: params: A dict-like object containing parameters from request query :param: context: Key-values providing frame of reference of request :returns: None :raises KeyError: table id doesn't exist :raises DataModelException: any error occurs during replacing rows. # Note(thread-safety): blocking call # FIXME(threod-safety): in DSE2, the returned caller can be a # datasource name. But the datasource name may now refer to a new, # unrelated datasource. Causing the rest of this code to operate on # an unintended datasource. # It would have saved us if table_id was an UUID rather than a name, # but it appears that table_id is just another word for tablename. # Fix: check UUID of datasource before operating. Abort if mismatch # Note(thread-safety): blocking call # TODO(thinrichs): It makes sense to sometimes allow users to create # a new row for internal data sources. But since we don't have # those yet all tuples are read-only from the API. # def add_item(self, item, id_=None, context=None): # """Add item to model. # Args: # item: The item to add to the model # id_: The ID of the item, or None if an ID should be generated # context: Key-values providing frame of reference of request # Returns: # Tuple of (ID, newly_created_item) # Raises: # KeyError: ID already exists. # """ # TODO(thinrichs): once we have internal data sources, # add the ability to update a row. (Or maybe not and implement # via add+delete.) # def update_item(self, id_, item, context=None): # """Update item with id\_ with new data. # Args: # id_: The ID of the item to be updated # item: The new item # context: Key-values providing frame of reference of request # Returns: # The updated item. # Raises: # KeyError: Item with specified id\_ not present. # """ # # currently a noop since the owner_id cannot be changed # if id_ not in self.items: # raise KeyError("Cannot update item with ID '%s': " # "ID does not exist") # return item # TODO(thinrichs): once we can create, we should be able to delete # def delete_item(self, id_, context=None): # """Remove item from model. # Args: # id_: The ID of the item to be removed # context: Key-values providing frame of reference of request # Returns: # The removed item. # Raises: # KeyError: Item with specified id\_ not present. # """
2.299921
2
tools/plotjuggler/juggle.py
aolin480/openpilot
70
6625849
<filename>tools/plotjuggler/juggle.py #!/usr/bin/env python3 import os import sys import multiprocessing import platform import shutil import subprocess import tarfile import tempfile import requests import argparse from common.basedir import BASEDIR from selfdrive.test.process_replay.compare_logs import save_log from tools.lib.api import CommaApi from tools.lib.auth_config import get_token from tools.lib.robust_logreader import RobustLogReader from tools.lib.route import Route, SegmentName from urllib.parse import urlparse, parse_qs juggle_dir = os.path.dirname(os.path.realpath(__file__)) DEMO_ROUTE = "4cf7a6ad03080c90|2021-09-29--13-46-36" RELEASES_URL="https://github.com/commaai/PlotJuggler/releases/download/latest" INSTALL_DIR = os.path.join(juggle_dir, "bin") def install(): m = f"{platform.system()}-{platform.machine()}" supported = ("Linux-x86_64", "Darwin-arm64", "Darwin-x86_64") if m not in supported: raise Exception(f"Unsupported platform: '{m}'. Supported platforms: {supported}") if os.path.exists(INSTALL_DIR): shutil.rmtree(INSTALL_DIR) os.mkdir(INSTALL_DIR) url = os.path.join(RELEASES_URL, m + ".tar.gz") with requests.get(url, stream=True) as r, tempfile.NamedTemporaryFile() as tmp: r.raise_for_status() with open(tmp.name, 'wb') as tmpf: for chunk in r.iter_content(chunk_size=1024*1024): tmpf.write(chunk) with tarfile.open(tmp.name) as tar: tar.extractall(path=INSTALL_DIR) def load_segment(segment_name): if segment_name is None: return [] try: return list(RobustLogReader(segment_name)) except ValueError as e: print(f"Error parsing {segment_name}: {e}") return [] def start_juggler(fn=None, dbc=None, layout=None): env = os.environ.copy() env["BASEDIR"] = BASEDIR env["PATH"] = f"{INSTALL_DIR}:{os.getenv('PATH', '')}" if dbc: env["DBC_NAME"] = dbc extra_args = "" if fn is not None: extra_args += f" -d {fn}" if layout is not None: extra_args += f" -l {layout}" cmd = f'plotjuggler --plugin_folders {INSTALL_DIR}{extra_args}' subprocess.call(cmd, shell=True, env=env, cwd=juggle_dir) def juggle_route(route_or_segment_name, segment_count, qlog, can, layout): segment_start = 0 if 'cabana' in route_or_segment_name: query = parse_qs(urlparse(route_or_segment_name).query) api = CommaApi(get_token()) logs = api.get(f'v1/route/{query["route"][0]}/log_urls?sig={query["sig"][0]}&exp={query["exp"][0]}') elif route_or_segment_name.startswith("http://") or route_or_segment_name.startswith("https://") or os.path.isfile(route_or_segment_name): logs = [route_or_segment_name] else: route_or_segment_name = SegmentName(route_or_segment_name, allow_route_name=True) segment_start = max(route_or_segment_name.segment_num, 0) if route_or_segment_name.segment_num != -1 and segment_count is None: segment_count = 1 r = Route(route_or_segment_name.route_name.canonical_name) logs = r.qlog_paths() if qlog else r.log_paths() segment_end = segment_start + segment_count if segment_count else -1 logs = logs[segment_start:segment_end] if None in logs: ans = input(f"{logs.count(None)}/{len(logs)} of the rlogs in this segment are missing, would you like to fall back to the qlogs? (y/n) ") if ans == 'y': logs = r.qlog_paths()[segment_start:segment_end] else: print("Please try a different route or segment") return all_data = [] with multiprocessing.Pool(24) as pool: for d in pool.map(load_segment, logs): all_data += d if not can: all_data = [d for d in all_data if d.which() not in ['can', 'sendcan']] # Infer DBC name from logs dbc = None for cp in [m for m in all_data if m.which() == 'carParams']: try: DBC = __import__(f"selfdrive.car.{cp.carParams.carName}.values", fromlist=['DBC']).DBC dbc = DBC[cp.carParams.carFingerprint]['pt'] except Exception: pass break with tempfile.NamedTemporaryFile(suffix='.rlog', dir=juggle_dir) as tmp: save_log(tmp.name, all_data, compress=False) del all_data start_juggler(tmp.name, dbc, layout) if __name__ == "__main__": parser = argparse.ArgumentParser(description="A helper to run PlotJuggler on openpilot routes", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--demo", action="store_true", help="Use the demo route instead of providing one") parser.add_argument("--qlog", action="store_true", help="Use qlogs") parser.add_argument("--can", action="store_true", help="Parse CAN data") parser.add_argument("--stream", action="store_true", help="Start PlotJuggler in streaming mode") parser.add_argument("--layout", nargs='?', help="Run PlotJuggler with a pre-defined layout") parser.add_argument("--install", action="store_true", help="Install or update PlotJuggler + plugins") parser.add_argument("route_or_segment_name", nargs='?', help="The route or segment name to plot (cabana share URL accepted)") parser.add_argument("segment_count", type=int, nargs='?', help="The number of segments to plot") if len(sys.argv) == 1: parser.print_help() sys.exit() args = parser.parse_args() if args.install: install() sys.exit() if args.stream: start_juggler(layout=args.layout) else: route_or_segment_name = DEMO_ROUTE if args.demo else args.route_or_segment_name.strip() juggle_route(route_or_segment_name, args.segment_count, args.qlog, args.can, args.layout)
<filename>tools/plotjuggler/juggle.py #!/usr/bin/env python3 import os import sys import multiprocessing import platform import shutil import subprocess import tarfile import tempfile import requests import argparse from common.basedir import BASEDIR from selfdrive.test.process_replay.compare_logs import save_log from tools.lib.api import CommaApi from tools.lib.auth_config import get_token from tools.lib.robust_logreader import RobustLogReader from tools.lib.route import Route, SegmentName from urllib.parse import urlparse, parse_qs juggle_dir = os.path.dirname(os.path.realpath(__file__)) DEMO_ROUTE = "4cf7a6ad03080c90|2021-09-29--13-46-36" RELEASES_URL="https://github.com/commaai/PlotJuggler/releases/download/latest" INSTALL_DIR = os.path.join(juggle_dir, "bin") def install(): m = f"{platform.system()}-{platform.machine()}" supported = ("Linux-x86_64", "Darwin-arm64", "Darwin-x86_64") if m not in supported: raise Exception(f"Unsupported platform: '{m}'. Supported platforms: {supported}") if os.path.exists(INSTALL_DIR): shutil.rmtree(INSTALL_DIR) os.mkdir(INSTALL_DIR) url = os.path.join(RELEASES_URL, m + ".tar.gz") with requests.get(url, stream=True) as r, tempfile.NamedTemporaryFile() as tmp: r.raise_for_status() with open(tmp.name, 'wb') as tmpf: for chunk in r.iter_content(chunk_size=1024*1024): tmpf.write(chunk) with tarfile.open(tmp.name) as tar: tar.extractall(path=INSTALL_DIR) def load_segment(segment_name): if segment_name is None: return [] try: return list(RobustLogReader(segment_name)) except ValueError as e: print(f"Error parsing {segment_name}: {e}") return [] def start_juggler(fn=None, dbc=None, layout=None): env = os.environ.copy() env["BASEDIR"] = BASEDIR env["PATH"] = f"{INSTALL_DIR}:{os.getenv('PATH', '')}" if dbc: env["DBC_NAME"] = dbc extra_args = "" if fn is not None: extra_args += f" -d {fn}" if layout is not None: extra_args += f" -l {layout}" cmd = f'plotjuggler --plugin_folders {INSTALL_DIR}{extra_args}' subprocess.call(cmd, shell=True, env=env, cwd=juggle_dir) def juggle_route(route_or_segment_name, segment_count, qlog, can, layout): segment_start = 0 if 'cabana' in route_or_segment_name: query = parse_qs(urlparse(route_or_segment_name).query) api = CommaApi(get_token()) logs = api.get(f'v1/route/{query["route"][0]}/log_urls?sig={query["sig"][0]}&exp={query["exp"][0]}') elif route_or_segment_name.startswith("http://") or route_or_segment_name.startswith("https://") or os.path.isfile(route_or_segment_name): logs = [route_or_segment_name] else: route_or_segment_name = SegmentName(route_or_segment_name, allow_route_name=True) segment_start = max(route_or_segment_name.segment_num, 0) if route_or_segment_name.segment_num != -1 and segment_count is None: segment_count = 1 r = Route(route_or_segment_name.route_name.canonical_name) logs = r.qlog_paths() if qlog else r.log_paths() segment_end = segment_start + segment_count if segment_count else -1 logs = logs[segment_start:segment_end] if None in logs: ans = input(f"{logs.count(None)}/{len(logs)} of the rlogs in this segment are missing, would you like to fall back to the qlogs? (y/n) ") if ans == 'y': logs = r.qlog_paths()[segment_start:segment_end] else: print("Please try a different route or segment") return all_data = [] with multiprocessing.Pool(24) as pool: for d in pool.map(load_segment, logs): all_data += d if not can: all_data = [d for d in all_data if d.which() not in ['can', 'sendcan']] # Infer DBC name from logs dbc = None for cp in [m for m in all_data if m.which() == 'carParams']: try: DBC = __import__(f"selfdrive.car.{cp.carParams.carName}.values", fromlist=['DBC']).DBC dbc = DBC[cp.carParams.carFingerprint]['pt'] except Exception: pass break with tempfile.NamedTemporaryFile(suffix='.rlog', dir=juggle_dir) as tmp: save_log(tmp.name, all_data, compress=False) del all_data start_juggler(tmp.name, dbc, layout) if __name__ == "__main__": parser = argparse.ArgumentParser(description="A helper to run PlotJuggler on openpilot routes", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--demo", action="store_true", help="Use the demo route instead of providing one") parser.add_argument("--qlog", action="store_true", help="Use qlogs") parser.add_argument("--can", action="store_true", help="Parse CAN data") parser.add_argument("--stream", action="store_true", help="Start PlotJuggler in streaming mode") parser.add_argument("--layout", nargs='?', help="Run PlotJuggler with a pre-defined layout") parser.add_argument("--install", action="store_true", help="Install or update PlotJuggler + plugins") parser.add_argument("route_or_segment_name", nargs='?', help="The route or segment name to plot (cabana share URL accepted)") parser.add_argument("segment_count", type=int, nargs='?', help="The number of segments to plot") if len(sys.argv) == 1: parser.print_help() sys.exit() args = parser.parse_args() if args.install: install() sys.exit() if args.stream: start_juggler(layout=args.layout) else: route_or_segment_name = DEMO_ROUTE if args.demo else args.route_or_segment_name.strip() juggle_route(route_or_segment_name, args.segment_count, args.qlog, args.can, args.layout)
en
0.421663
#!/usr/bin/env python3 # Infer DBC name from logs
1.876137
2
nli_mixed_models/eval/nli_eval.py
wgantt/nli-mixed-models
1
6625850
<reponame>wgantt/nli-mixed-models import torch import logging import numpy as np import pandas as pd from torch.optim import Adam from torch.nn import CrossEntropyLoss, BCEWithLogitsLoss from ..modules.nli_base import NaturalLanguageInference from ..modules.nli_random_intercepts import ( UnitRandomIntercepts, CategoricalRandomIntercepts, ) from scripts.setup_logging import setup_logging from ..modules.nli_random_slopes import UnitRandomSlopes, CategoricalRandomSlopes from ..trainers.nli_trainer import BetaLogProbLoss, beta_mode from scripts.eval_utils import ( accuracy, absolute_error, accuracy_best, ) from torch.distributions import Beta LOG = setup_logging() class NaturalLanguageInferenceEval: def __init__( self, model: NaturalLanguageInference, subtask: str = "a", device="cpu" ): self.nli = model self.subtask = subtask self.lossfunc = self.LOSS_CLASS() self.device = device def eval(self, test_data: pd.DataFrame, batch_size: int = 32): self.nli.eval() with torch.no_grad(): n_batches = np.ceil(test_data.shape[0] / batch_size) test_data = test_data.sample(frac=1).reset_index(drop=True) test_data.loc[:, "batch_idx"] = np.repeat(np.arange(n_batches), batch_size)[ : test_data.shape[0] ] loss_trace = [] fixed_loss_trace = [] random_loss_trace = [] metric_trace = [] best_trace = [] # Tensors for accumulating predictions, targets, and modal # responses across batches. if isinstance(self.nli, CategoricalRandomIntercepts) or isinstance( self.nli, CategoricalRandomSlopes ): all_predictions = torch.FloatTensor().to(self.device) all_targets = torch.LongTensor().to(self.device) all_modal_responses = torch.LongTensor().to(self.device) all_best = torch.LongTensor().to(self.device) naive_prediction = test_data.target.mode().item() naive_acc = len(test_data[test_data.target == naive_prediction]) / len( test_data ) LOG.info(f"naive accuracy across fold: {naive_acc}") else: all_predictions = torch.FloatTensor().to(self.device) all_targets = torch.FloatTensor().to(self.device) all_modal_responses = torch.FloatTensor().to(self.device) all_best = torch.LongTensor().to(self.device) # Calculate metrics for each batch in test set for batch, items in test_data.groupby("batch_idx"): LOG.info("evaluating batch [%s/%s]" % (int(batch), int(n_batches))) if self.subtask == "a": participant = torch.LongTensor(items.participant.values) else: participant = None # Get target values of appropriate type if isinstance(self.nli, CategoricalRandomIntercepts) or isinstance( self.nli, CategoricalRandomSlopes ): target = torch.LongTensor(items.target.values).to(self.device) modal_response = torch.LongTensor(items.modal_response.values).to( self.device ) else: target = torch.FloatTensor(items.target.values).to(self.device) modal_response = torch.FloatTensor(items.modal_response.values).to( self.device ) all_targets = torch.cat((all_targets, target)) all_modal_responses = torch.cat((all_modal_responses, modal_response)) # Embed items embedding = self.nli.embed(items) # Calculate model prediction and compute fixed & random loss if isinstance(self.nli, UnitRandomIntercepts) or isinstance( self.nli, UnitRandomSlopes ): prediction, random_loss = self.nli(embedding, participant) alpha, beta = prediction prediction = alpha / (alpha + beta) fixed_loss = self.lossfunc(alpha, beta, target) else: prediction, random_loss = self.nli(embedding, participant) fixed_loss = self.lossfunc(prediction, target) all_predictions = torch.cat((all_predictions, prediction)) random_loss = ( random_loss if isinstance(random_loss, float) else random_loss.item() ) # Add total loss to trace loss = fixed_loss + random_loss loss_trace.append(loss.item()) fixed_loss_trace.append(fixed_loss.item()) random_loss_trace.append(random_loss) # If categorical, calculate accuracy (and Spearman's coefficient) if isinstance(self.nli, CategoricalRandomIntercepts) or isinstance( self.nli, CategoricalRandomSlopes ): acc = accuracy(prediction, target) best = accuracy_best(items) metric_trace.append(acc) best_trace.append(acc / best) # If unit, calculate absolute error else: error = absolute_error(prediction, target) best = absolute_error(modal_response, target) metric_trace.append(error) best_trace.append(1 - (error - best) / best) # Calculate Spearman's correlation coefficient between # 1. Best possible (i.e. modal) responses and true responses # 2. Predicted responses and true responses """ spearman_df = pd.DataFrame() spearman_df["true"] = pd.Series(all_targets.cpu().detach().numpy()) spearman_df["predicted"] = pd.Series( all_predictions.cpu().detach().numpy() ) spearman_df["best"] = pd.Series( all_modal_responses.cpu().detach().numpy() ) spearman_predicted = ( spearman_df[["true", "predicted"]] .corr(method="spearman") .iloc[0, 1] ) spearman_best = ( spearman_df[["true", "best"]].corr(method="spearman").iloc[0, 1] ) """ # Calculate and return mean of metrics across all batches loss_mean = np.round(np.mean(loss_trace), 4) fixed_loss_mean = np.round(np.mean(fixed_loss_trace), 4) random_loss_mean = np.round(np.mean(random_loss_trace), 4) metric_mean = np.round(np.mean(metric_trace), 4) best_mean = np.round(np.mean(best_trace), 4) """ spearman_predicted = np.round(spearman_predicted, 4) spearman_best = np.round(spearman_best, 4) """ spearman_predicted = 0 spearman_best = 1 # Macroaverage best_mean = (all_modal_responses == all_targets).cpu().numpy().mean() worst_mean = naive_acc metric_mean = accuracy(all_predictions, all_targets) # An undefined Spearman means that all the predicted values are # the same. This is unlikely to occur across an entire test fold, # but not impossible. As noted in the paper, an undefined Spearman # correlation essentially represents *0* correlation. if np.isnan(spearman_predicted): spearman_predicted = 0.0 return ( loss_mean, fixed_loss_mean, random_loss_mean, metric_mean, best_mean, spearman_predicted, spearman_best, worst_mean, ) # Unit eval class UnitEval(NaturalLanguageInferenceEval): LOSS_CLASS = BetaLogProbLoss TARGET_TYPE = torch.FloatTensor # Categorical eval class CategoricalEval(NaturalLanguageInferenceEval): LOSS_CLASS = CrossEntropyLoss TARGET_TYPE = torch.LongTensor
import torch import logging import numpy as np import pandas as pd from torch.optim import Adam from torch.nn import CrossEntropyLoss, BCEWithLogitsLoss from ..modules.nli_base import NaturalLanguageInference from ..modules.nli_random_intercepts import ( UnitRandomIntercepts, CategoricalRandomIntercepts, ) from scripts.setup_logging import setup_logging from ..modules.nli_random_slopes import UnitRandomSlopes, CategoricalRandomSlopes from ..trainers.nli_trainer import BetaLogProbLoss, beta_mode from scripts.eval_utils import ( accuracy, absolute_error, accuracy_best, ) from torch.distributions import Beta LOG = setup_logging() class NaturalLanguageInferenceEval: def __init__( self, model: NaturalLanguageInference, subtask: str = "a", device="cpu" ): self.nli = model self.subtask = subtask self.lossfunc = self.LOSS_CLASS() self.device = device def eval(self, test_data: pd.DataFrame, batch_size: int = 32): self.nli.eval() with torch.no_grad(): n_batches = np.ceil(test_data.shape[0] / batch_size) test_data = test_data.sample(frac=1).reset_index(drop=True) test_data.loc[:, "batch_idx"] = np.repeat(np.arange(n_batches), batch_size)[ : test_data.shape[0] ] loss_trace = [] fixed_loss_trace = [] random_loss_trace = [] metric_trace = [] best_trace = [] # Tensors for accumulating predictions, targets, and modal # responses across batches. if isinstance(self.nli, CategoricalRandomIntercepts) or isinstance( self.nli, CategoricalRandomSlopes ): all_predictions = torch.FloatTensor().to(self.device) all_targets = torch.LongTensor().to(self.device) all_modal_responses = torch.LongTensor().to(self.device) all_best = torch.LongTensor().to(self.device) naive_prediction = test_data.target.mode().item() naive_acc = len(test_data[test_data.target == naive_prediction]) / len( test_data ) LOG.info(f"naive accuracy across fold: {naive_acc}") else: all_predictions = torch.FloatTensor().to(self.device) all_targets = torch.FloatTensor().to(self.device) all_modal_responses = torch.FloatTensor().to(self.device) all_best = torch.LongTensor().to(self.device) # Calculate metrics for each batch in test set for batch, items in test_data.groupby("batch_idx"): LOG.info("evaluating batch [%s/%s]" % (int(batch), int(n_batches))) if self.subtask == "a": participant = torch.LongTensor(items.participant.values) else: participant = None # Get target values of appropriate type if isinstance(self.nli, CategoricalRandomIntercepts) or isinstance( self.nli, CategoricalRandomSlopes ): target = torch.LongTensor(items.target.values).to(self.device) modal_response = torch.LongTensor(items.modal_response.values).to( self.device ) else: target = torch.FloatTensor(items.target.values).to(self.device) modal_response = torch.FloatTensor(items.modal_response.values).to( self.device ) all_targets = torch.cat((all_targets, target)) all_modal_responses = torch.cat((all_modal_responses, modal_response)) # Embed items embedding = self.nli.embed(items) # Calculate model prediction and compute fixed & random loss if isinstance(self.nli, UnitRandomIntercepts) or isinstance( self.nli, UnitRandomSlopes ): prediction, random_loss = self.nli(embedding, participant) alpha, beta = prediction prediction = alpha / (alpha + beta) fixed_loss = self.lossfunc(alpha, beta, target) else: prediction, random_loss = self.nli(embedding, participant) fixed_loss = self.lossfunc(prediction, target) all_predictions = torch.cat((all_predictions, prediction)) random_loss = ( random_loss if isinstance(random_loss, float) else random_loss.item() ) # Add total loss to trace loss = fixed_loss + random_loss loss_trace.append(loss.item()) fixed_loss_trace.append(fixed_loss.item()) random_loss_trace.append(random_loss) # If categorical, calculate accuracy (and Spearman's coefficient) if isinstance(self.nli, CategoricalRandomIntercepts) or isinstance( self.nli, CategoricalRandomSlopes ): acc = accuracy(prediction, target) best = accuracy_best(items) metric_trace.append(acc) best_trace.append(acc / best) # If unit, calculate absolute error else: error = absolute_error(prediction, target) best = absolute_error(modal_response, target) metric_trace.append(error) best_trace.append(1 - (error - best) / best) # Calculate Spearman's correlation coefficient between # 1. Best possible (i.e. modal) responses and true responses # 2. Predicted responses and true responses """ spearman_df = pd.DataFrame() spearman_df["true"] = pd.Series(all_targets.cpu().detach().numpy()) spearman_df["predicted"] = pd.Series( all_predictions.cpu().detach().numpy() ) spearman_df["best"] = pd.Series( all_modal_responses.cpu().detach().numpy() ) spearman_predicted = ( spearman_df[["true", "predicted"]] .corr(method="spearman") .iloc[0, 1] ) spearman_best = ( spearman_df[["true", "best"]].corr(method="spearman").iloc[0, 1] ) """ # Calculate and return mean of metrics across all batches loss_mean = np.round(np.mean(loss_trace), 4) fixed_loss_mean = np.round(np.mean(fixed_loss_trace), 4) random_loss_mean = np.round(np.mean(random_loss_trace), 4) metric_mean = np.round(np.mean(metric_trace), 4) best_mean = np.round(np.mean(best_trace), 4) """ spearman_predicted = np.round(spearman_predicted, 4) spearman_best = np.round(spearman_best, 4) """ spearman_predicted = 0 spearman_best = 1 # Macroaverage best_mean = (all_modal_responses == all_targets).cpu().numpy().mean() worst_mean = naive_acc metric_mean = accuracy(all_predictions, all_targets) # An undefined Spearman means that all the predicted values are # the same. This is unlikely to occur across an entire test fold, # but not impossible. As noted in the paper, an undefined Spearman # correlation essentially represents *0* correlation. if np.isnan(spearman_predicted): spearman_predicted = 0.0 return ( loss_mean, fixed_loss_mean, random_loss_mean, metric_mean, best_mean, spearman_predicted, spearman_best, worst_mean, ) # Unit eval class UnitEval(NaturalLanguageInferenceEval): LOSS_CLASS = BetaLogProbLoss TARGET_TYPE = torch.FloatTensor # Categorical eval class CategoricalEval(NaturalLanguageInferenceEval): LOSS_CLASS = CrossEntropyLoss TARGET_TYPE = torch.LongTensor
en
0.673311
# Tensors for accumulating predictions, targets, and modal # responses across batches. # Calculate metrics for each batch in test set # Get target values of appropriate type # Embed items # Calculate model prediction and compute fixed & random loss # Add total loss to trace # If categorical, calculate accuracy (and Spearman's coefficient) # If unit, calculate absolute error # Calculate Spearman's correlation coefficient between # 1. Best possible (i.e. modal) responses and true responses # 2. Predicted responses and true responses spearman_df = pd.DataFrame() spearman_df["true"] = pd.Series(all_targets.cpu().detach().numpy()) spearman_df["predicted"] = pd.Series( all_predictions.cpu().detach().numpy() ) spearman_df["best"] = pd.Series( all_modal_responses.cpu().detach().numpy() ) spearman_predicted = ( spearman_df[["true", "predicted"]] .corr(method="spearman") .iloc[0, 1] ) spearman_best = ( spearman_df[["true", "best"]].corr(method="spearman").iloc[0, 1] ) # Calculate and return mean of metrics across all batches spearman_predicted = np.round(spearman_predicted, 4) spearman_best = np.round(spearman_best, 4) # Macroaverage # An undefined Spearman means that all the predicted values are # the same. This is unlikely to occur across an entire test fold, # but not impossible. As noted in the paper, an undefined Spearman # correlation essentially represents *0* correlation. # Unit eval # Categorical eval
2.092568
2